@bettertui/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["require","generateId","createNativeKeymap","ESC","ESC","Buffer","Buffer","g","createTimeline","tiny","block","shade","slick","huge","grid","pallet","StyledTextClass","TextClass","InputClass","SelectClass","TabSelectClass","CodeClass","FrameBufferClass","ASCIIFontClass","BoxClass","ScrollBox","ASCIIFont","RESET","fg","bg","labelled","labelled","RESET","CliRendererClass"],"sources":["../src/command/buffer.ts","../src/command/tree.ts","../src/reconciler.ts","../src/lib/clock.ts","../src/platform/binding.ts","../src/runtime.ts","../src/renderable.ts","../src/lib/keybinding.ts","../src/lib/parseKeypressKitty.ts","../src/lib/parseKeypress.ts","../src/lib/parseMouse.ts","../src/lib/keyHandler.ts","../src/lib/renderableKeyBindings.ts","../src/lib/stdinParser.ts","../src/lib/keyInput.ts","../src/lib/rgba.ts","../src/lib/styledText.ts","../src/lib/renderableEvents.ts","../src/lib/singleton.ts","../src/lib/env.ts","../src/lib/timeline.ts","../src/renderables/Box.ts","../src/renderables/Input.ts","../src/renderables/Select.ts","../src/lib/fonts/block.json","../src/lib/fonts/grid.json","../src/lib/fonts/huge.json","../src/lib/fonts/pallet.json","../src/lib/fonts/shade.json","../src/lib/fonts/slick.json","../src/lib/fonts/tiny.json","../src/lib/asciiFont.ts","../src/renderables/TextNode.ts","../src/renderables/Text.ts","../src/renderables/Stubs.ts","../src/renderables/TabSelect.ts","../src/lib/vnode.ts","../src/lib/index.ts","../src/devtools/logger.ts","../src/devtools/commandInspector.ts","../src/devtools/eventInspector.ts","../src/devtools/performance.ts","../src/devtools/treeInspector.ts","../src/devtools/schedulerInspector.ts","../src/devtools/focusInspector.ts","../src/devtools/capabilityInspector.ts","../src/devtools/timeline.ts","../src/devtools/snapshot.ts","../src/devtools/export.ts","../src/lib/outputCapture.ts","../src/devtools/consoleCapture.ts","../src/devtools/overlay/ansiUtils.ts","../src/devtools/overlay/panel.types.ts","../src/devtools/overlay/panels/dirtyRegionsPanel.ts","../src/devtools/overlay/panels/eventsPanel.ts","../src/devtools/overlay/panels/layoutPanel.ts","../src/devtools/overlay/panels/performancePanel.ts","../src/devtools/overlay/panels/treePanel.ts","../src/devtools/overlay/overlayHost.ts","../src/devtools/index.ts","../src/platform/layoutSerializer.ts","../src/platform/cliRenderer.ts","../src/platform/logger.ts","../src/testing/mockKeys.ts","../src/testing/mockMouse.ts","../src/testing/testStreams.ts","../src/testing/testRenderer.ts","../src/testing/spy.ts","../src/testing/terminalCapabilities.ts","../src/testing/testing.ts","../src/animations.ts","../src/graphics.ts","../src/audio.ts","../src/renderables/ScrollBox.ts","../src/renderables/Textarea.ts","../src/renderables/Slider.ts","../src/renderables/Canvas.ts","../src/renderables/index.ts","../src/index.ts"],"sourcesContent":["import type { Command } from \"./command.types\";\n\nexport class CommandBuffer {\n private commands: Command[] = [];\n\n push(command: Command): void {\n this.commands.push(command);\n }\n\n drain(): Command[] {\n const commands = this.commands;\n this.commands = [];\n return commands;\n }\n\n peek(): readonly Command[] {\n return this.commands;\n }\n\n clear(): void {\n this.commands = [];\n }\n\n get length(): number {\n return this.commands.length;\n }\n\n get isEmpty(): boolean {\n return this.commands.length === 0;\n }\n}\n","import type { LayoutConstraints, Style } from \"@bettertui/shared\";\nimport { generateId } from \"@bettertui/shared\";\nimport type { Instance, TextInstance } from \"./command.types\";\n\nexport function createInstance(type: string, props: Record<string, unknown>): Instance {\n const id = generateId();\n const { children, style, layout, ...restProps } = props;\n\n return {\n id,\n type,\n props: restProps,\n style: (style as Style) || {},\n layout: (layout as LayoutConstraints) || {},\n children: [],\n parent: null,\n };\n}\n\nexport function createTextInstance(text: string): TextInstance {\n return {\n id: generateId(),\n type: \"#text\",\n text,\n parent: null,\n };\n}\n\nexport function appendChild(parent: Instance, child: Instance | TextInstance): void {\n child.parent = parent;\n if (\"children\" in parent) {\n parent.children.push(child as Instance);\n }\n}\n\nexport function removeChild(parent: Instance, child: Instance | TextInstance): void {\n child.parent = null;\n if (\"children\" in parent) {\n const index = parent.children.indexOf(child as Instance);\n if (index !== -1) {\n parent.children.splice(index, 1);\n }\n }\n}\n\nexport function insertBefore(\n parent: Instance,\n child: Instance | TextInstance,\n reference: Instance | TextInstance,\n): void {\n child.parent = parent;\n if (\"children\" in parent) {\n const index = parent.children.indexOf(reference as Instance);\n if (index !== -1) {\n parent.children.splice(index, 0, child as Instance);\n } else {\n parent.children.push(child as Instance);\n }\n }\n}\n\nexport function prepareUpdate(\n _instance: Instance,\n _type: string,\n _oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n): Record<string, unknown> | null {\n const { children, style, layout, ...restProps } = newProps;\n return restProps;\n}\n\nexport function commitUpdate(instance: Instance, updatePayload: Record<string, unknown>): void {\n Object.assign(instance.props, updatePayload);\n}\n\nexport function commitTextUpdate(textInstance: TextInstance, text: string): void {\n textInstance.text = text;\n}\n\nexport function finalizeInitialChildren(_instance: Instance): boolean {\n return false;\n}\n\nexport function resetAfterCommit(): void {\n // Flush happens at a higher level\n}\n\nexport { generateId };\n","import type { Style } from \"@bettertui/shared\";\nimport {\n appendChild,\n commitTextUpdate,\n commitUpdate,\n createInstance,\n createTextInstance,\n finalizeInitialChildren,\n insertBefore,\n prepareUpdate,\n removeChild,\n resetAfterCommit,\n} from \"./command\";\nimport type { CommandBuffer, Instance, TextInstance } from \"./command\";\n\nexport function createReconciler(buffer: CommandBuffer): {\n createInstance: (type: string, props: Record<string, unknown>) => Instance;\n createTextInstance: (text: string) => TextInstance;\n appendChild: (parent: Instance, child: Instance | TextInstance) => void;\n removeChild: (parent: Instance, child: Instance | TextInstance) => void;\n insertBefore: (\n parent: Instance,\n child: Instance | TextInstance,\n reference: Instance | TextInstance,\n ) => void;\n prepareUpdate: (\n instance: Instance,\n type: string,\n oldProps: Record<string, unknown>,\n newProps: Record<string, unknown>,\n ) => Record<string, unknown> | null;\n commitUpdate: (instance: Instance, updatePayload: Record<string, unknown>) => void;\n commitTextUpdate: (textInstance: TextInstance, text: string) => void;\n finalizeInitialChildren: (instance: Instance) => boolean;\n resetAfterCommit: () => void;\n} {\n function emitCreateNode(id: string, type: string): void {\n buffer.push({ type: \"CreateNode\", id, kind: type });\n }\n\n function emitAppendChild(parentId: string, childId: string): void {\n buffer.push({ type: \"AppendChild\", parent: parentId, child: childId });\n }\n\n function emitRemoveNode(id: string): void {\n buffer.push({ type: \"RemoveNode\", id });\n }\n\n function emitInsertBefore(referenceId: string, childId: string): void {\n buffer.push({ type: \"InsertBefore\", reference: referenceId, child: childId });\n }\n\n function emitSetText(id: string, text: string): void {\n buffer.push({ type: \"SetText\", id, text });\n }\n\n function emitSetStyle(id: string, style: Style): void {\n buffer.push({ type: \"SetStyle\", id, style });\n }\n\n function wrappedCreateInstance(type: string, props: Record<string, unknown>): Instance {\n const instance = createInstance(type, props);\n emitCreateNode(instance.id, type);\n if (Object.keys(instance.style).length > 0) {\n emitSetStyle(instance.id, instance.style);\n }\n return instance;\n }\n\n function wrappedCreateTextInstance(text: string): TextInstance {\n const instance = createTextInstance(text);\n emitCreateNode(instance.id, \"Text\");\n emitSetText(instance.id, text);\n return instance;\n }\n\n function wrappedAppendChild(parent: Instance, child: Instance | TextInstance): void {\n appendChild(parent, child);\n emitAppendChild(parent.id, child.id);\n }\n\n function wrappedRemoveChild(parent: Instance, child: Instance | TextInstance): void {\n removeChild(parent, child);\n emitRemoveNode(child.id);\n }\n\n function wrappedInsertBefore(\n parent: Instance,\n child: Instance | TextInstance,\n reference: Instance | TextInstance,\n ): void {\n insertBefore(parent, child, reference);\n emitInsertBefore(reference.id, child.id);\n }\n\n function wrappedCommitUpdate(instance: Instance, updatePayload: Record<string, unknown>): void {\n commitUpdate(instance, updatePayload);\n if (updatePayload[\"style\"]) {\n emitSetStyle(instance.id, updatePayload[\"style\"] as Style);\n }\n }\n\n function wrappedCommitTextUpdate(textInstance: TextInstance, text: string): void {\n commitTextUpdate(textInstance, text);\n if (textInstance.id) {\n emitSetText(textInstance.id, text);\n }\n }\n\n return {\n createInstance: wrappedCreateInstance,\n createTextInstance: wrappedCreateTextInstance,\n appendChild: wrappedAppendChild,\n removeChild: wrappedRemoveChild,\n insertBefore: wrappedInsertBefore,\n prepareUpdate,\n commitUpdate: wrappedCommitUpdate,\n commitTextUpdate: wrappedCommitTextUpdate,\n finalizeInitialChildren,\n resetAfterCommit,\n };\n}\n","export type TimerHandle = ReturnType<typeof globalThis.setTimeout>;\n\nexport interface Clock {\n now(): number;\n setTimeout(fn: () => void, delayMs: number): TimerHandle;\n clearTimeout(handle: TimerHandle): void;\n setInterval(fn: () => void, delayMs: number): TimerHandle;\n clearInterval(handle: TimerHandle): void;\n}\n\nexport class SystemClock implements Clock {\n now(): number {\n return globalThis.performance.now();\n }\n\n setTimeout(fn: () => void, delayMs: number): TimerHandle {\n return globalThis.setTimeout(fn, delayMs);\n }\n\n clearTimeout(handle: TimerHandle): void {\n globalThis.clearTimeout(handle);\n }\n\n setInterval(fn: () => void, delayMs: number): TimerHandle {\n return globalThis.setInterval(fn, delayMs);\n }\n\n clearInterval(handle: TimerHandle): void {\n globalThis.clearInterval(handle);\n }\n}\n\nexport class TestClock implements Clock {\n private _now = 0;\n private timeouts: Array<{ at: number; fn: () => void; id: number }> = [];\n private intervals: Array<{ at: number; fn: () => void; id: number; delayMs: number }> = [];\n private nextId = 1;\n\n now(): number {\n return this._now;\n }\n\n advance(ms: number): void {\n this._now += ms;\n this.tick();\n }\n\n setTime(time: number): void {\n this._now = time;\n }\n\n private tick(): void {\n const dueTimeouts = this.timeouts.filter((t) => t.at <= this._now);\n this.timeouts = this.timeouts.filter((t) => t.at > this._now);\n for (const t of dueTimeouts) {\n t.fn();\n }\n\n const dueIntervals = this.intervals.filter((t) => t.at <= this._now);\n for (const t of dueIntervals) {\n t.fn();\n t.at = this._now + t.delayMs;\n }\n }\n\n setTimeout(fn: () => void, delayMs: number): TimerHandle {\n const id = this.nextId++;\n this.timeouts.push({ at: this._now + delayMs, fn, id });\n return id as unknown as TimerHandle;\n }\n\n clearTimeout(handle: TimerHandle): void {\n const id = handle as unknown as number;\n this.timeouts = this.timeouts.filter((t) => t.id !== id);\n }\n\n setInterval(fn: () => void, delayMs: number): TimerHandle {\n const id = this.nextId++;\n this.intervals.push({ at: this._now + delayMs, fn, id, delayMs });\n return id as unknown as TimerHandle;\n }\n\n clearInterval(handle: TimerHandle): void {\n const id = handle as unknown as number;\n this.intervals = this.intervals.filter((t) => t.id !== id);\n }\n}\n","import { createRequire } from \"node:module\";\nimport type { BindingInfo } from \"./platform.types\";\n\nconst require = createRequire(import.meta.url);\n\ninterface NativeModule {\n NativeEngine: new (width: number, height: number) => NativeEngine;\n NativeEventBus: new () => NativeEventBus;\n NativeFocusManager: new () => NativeFocusManager;\n NativeKeymap: new () => NativeKeymap;\n NativeScheduler: new (fps?: number | null) => NativeScheduler;\n NativeTextEngine: new (text?: string | null) => NativeTextEngine;\n NativeSpanFeed: new (options?: NativeSpanFeedOptions | null) => NativeSpanFeed;\n NativeHitGrid: new (width: number, height: number) => NativeHitGrid;\n NativePluginHost: new () => NativePluginHost;\n NativeTimeline: new (\n duration?: number | null,\n looping?: boolean | null,\n ) => NativeTimelineInstance;\n TerminalCapabilities: TerminalCapabilities;\n detectCapabilities: () => TerminalCapabilities;\n getVersion: () => string;\n createDarkTheme: () => NapiTheme;\n createLightTheme: () => NapiTheme;\n loggerInit: (config: NapiLoggerConfig) => void;\n loggerSetLevel: (level: string) => void;\n loggerGetLevel: () => string;\n loggerSetModuleFilter: (include?: string[] | null, exclude?: string[] | null) => void;\n loggerGetDiagnostics: () => NapiDiagnosticSnapshot;\n loggerFlush: () => void;\n highlightCode: (code: string, language: string) => NativeHighlightedLine[];\n // Graphics protocol (may be absent in debug builds)\n graphicsKittyWrite?: (\n format: string,\n width: number,\n height: number,\n data: Buffer,\n id: number,\n ) => Buffer;\n graphicsKittyDelete?: (id: number) => Buffer;\n graphicsKittyDeleteAll?: () => Buffer;\n graphicsItermWrite?: (\n fileBytes: Buffer,\n name?: string | null,\n width?: number | null,\n height?: number | null,\n ) => Buffer;\n graphicsSixelWrite?: (format: string, width: number, height: number, data: Buffer) => Buffer;\n graphicsQuery?: () => Buffer;\n clipboardSetSequence?: (selection: string, text: string) => Buffer;\n clipboardQuerySequence?: (selection: string) => Buffer;\n clipboardDecode?: (payload: string) => string | null;\n}\n\ninterface NativeTimelineInstance {\n addTween(\n from: number,\n to: number,\n duration: number,\n startTime: number,\n easing?: string | null,\n ): number;\n play(): void;\n pause(): void;\n restart(): void;\n update(dt: number): void;\n animationValue(index: number): number | null;\n currentTime(): number;\n isComplete(): boolean;\n isPlaying(): boolean;\n setSpeed(speed: number): void;\n progress(): number | null;\n}\n\ninterface NativeEngine {\n processCommands(commandsJson: string): string;\n beginFrame(): void;\n commitFrame(): void;\n render(): string;\n renderFull(): string;\n setScreenMode(mode: string, footerHeight?: number | null): void;\n setBackgroundColor?(color: string): void;\n resize(width: number, height: number): void;\n nodeCount(): number;\n frameCount(): number;\n printTree(): string;\n validate(): boolean;\n shutdown(): void;\n setStyle(id: number, styleJson: string): void;\n setLayout(id: number, layoutJson: string): void;\n getNode(id: number): string;\n treeSummary(): string;\n root(): number;\n createNode(kind: string): number;\n appendChild(parent: number, child: number): boolean;\n insertBefore(before: number, child: number): boolean;\n removeNode(id: number): void;\n setText(id: number, text: string): void;\n setScrollOffset(id: number, scrollX: number, scrollY: number): void;\n hitGridCheck(x: number, y: number): number;\n hitGridIsDirty(): boolean;\n hitGridClearCurrent(): void;\n hitGridPushScissor(x: number, y: number, width: number, height: number): void;\n hitGridPopScissor(): void;\n hitGridAddCurrentClipped(x: number, y: number, width: number, height: number, id: number): void;\n hitGridDump(): string;\n}\n\ninterface NativeEventBus {\n pushKey(key: string, ctrl: boolean, shift: boolean, alt: boolean): void;\n pushMouse(button: string, x: number, y: number): void;\n pushMouseMotion(x: number, y: number): void;\n pushPaste(text: string): void;\n pushResize(width: number, height: number, prevWidth: number, prevHeight: number): void;\n drain(): string;\n len(): number;\n isEmpty(): boolean;\n clear(): void;\n}\n\ninterface NativeFocusManager {\n focus(id: number): boolean;\n blur(id: number): boolean;\n blurCurrent(): boolean;\n focused(): number;\n isFocused(id: number): boolean;\n traverse(direction: string): string;\n focusOrder(): number[];\n clear(): void;\n}\n\ninterface NativeTextEngine {\n insertChar(ch: string): void;\n insertStr(text: string): void;\n deleteChar(): void;\n getText(): string;\n clear(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n undo(): boolean;\n redo(): boolean;\n cursorLeft(): void;\n cursorRight(): void;\n cursorPosition(): number;\n setCursorPosition(pos: number): void;\n length(): number;\n lineCount(): number;\n isEmpty(): boolean;\n wordCount(): number;\n}\n\ninterface NativeScheduler {\n requestFrame(): void;\n beginFrame(): boolean;\n endFrame(): void;\n isIdle(): boolean;\n frameCount(): number;\n fps(): number;\n shouldRender(): boolean;\n requestRenderCoalesced(): void;\n requestRenderImmediate(): void;\n hasScheduledFrame(): boolean;\n isRendering(): boolean;\n beginRender(): void;\n endRender(): boolean;\n}\n\ninterface NativeKeymap {\n addBinding(\n layer: string,\n id: string,\n keys: string,\n command: string,\n description: string | null,\n priority: number,\n ): boolean;\n handleKey(key: string): string;\n hasPending(): boolean;\n clearPending(): void;\n setMode(mode: string): void;\n currentMode(): string;\n clearMode(): void;\n removeLayer(name: string): boolean;\n setChordTimeout(ms: number): void;\n chordTimeout(): number;\n pendingKeys(): string[];\n activeBindings(): string;\n allBindings(): string;\n commandHistory(): string[];\n clearHistory(): void;\n parseKey(keyStr: string): string;\n parseSequence(keyStr: string): string[];\n}\n\nexport interface TerminalCapabilities {\n brand: string;\n true_color: boolean;\n kitty_keyboard: boolean;\n csi_u: boolean;\n bracketed_paste: boolean;\n focus_events: boolean;\n mouse: boolean;\n osc52: boolean;\n osc52_support: boolean;\n osc8: boolean;\n sync: boolean;\n sgr_pixel: boolean;\n underline_color: boolean;\n strikethrough: boolean;\n cursor_style: boolean;\n alternate_scroll: boolean;\n inline_images: boolean;\n sixel: boolean;\n columns: number;\n rows: number;\n}\n\n/**\n * npm `libc` values understood by package managers (`glibc` / `musl`), mapped\n * from the Rust target ABI suffix used by our platform package names.\n */\nconst SUPPORTED_NATIVE_TRIPLES = [\n \"darwin-x64\",\n \"darwin-arm64\",\n \"linux-x64-gnu\",\n \"linux-arm64-gnu\",\n \"linux-x64-musl\",\n \"linux-arm64-musl\",\n \"win32-x64\",\n \"win32-arm64\",\n] as const;\n\ninterface ProcessReport {\n getReport(): { header: { glibcVersionRuntime?: string } };\n}\n\n/** Resolve the platform-package triple matching the current host. */\nfunction detectNativeTriple(): string | null {\n const { platform, arch } = process;\n if (platform === \"darwin\" || platform === \"win32\") {\n return `${platform}-${arch}`;\n }\n if (platform === \"linux\") {\n const report = (process as unknown as { report?: ProcessReport }).report;\n const libc = report?.getReport().header.glibcVersionRuntime ? \"gnu\" : \"musl\";\n return `linux-${arch}-${libc}`;\n }\n return null;\n}\n\n/**\n * Load the napi-rs engine addon: prefer the platform-specific optional\n * dependency resolved through node_modules, then the dev-tree fallbacks.\n */\nfunction loadNativeModule(): NativeModule {\n const triple = detectNativeTriple();\n if (triple && (SUPPORTED_NATIVE_TRIPLES as readonly string[]).includes(triple)) {\n try {\n return require(`@bettertui/core-${triple}`);\n } catch {\n // Platform package not installed (development checkout) — fall through.\n }\n }\n try {\n return require(\"./bettertui_engine.node\");\n } catch {\n // Not adjacent to source during test/dev runs.\n }\n try {\n return require(\"../../dist/bettertui_engine.node\");\n } catch {\n // Not built yet.\n }\n throw new Error(\n `@bettertui/core: no native engine binary found for ${process.platform}/${process.arch}. Supported platforms: ${SUPPORTED_NATIVE_TRIPLES.join(\", \")}. Install the matching \"@bettertui/core-<platform>\" package or rebuild locally with \"pnpm build\".`,\n );\n}\n\nconst native: NativeModule = loadNativeModule();\n\nexport interface CommandResult {\n success: number;\n errors: string[];\n id_mappings: Array<{ temp: number; real: number }>;\n}\n\nexport interface RenderResult {\n output_data: string;\n width: number;\n height: number;\n dirty_region_count: number;\n}\n\nexport interface NapiEngine {\n processCommands(commandsJson: string): CommandResult;\n beginFrame(): void;\n commitFrame(): void;\n render(): RenderResult;\n renderFull(): RenderResult;\n resize(width: number, height: number): void;\n setScreenMode(mode: string, footerHeight?: number | null): void;\n setBackgroundColor?(color: string): void;\n setStyle(id: number, styleJson: string): void;\n setLayout(id: number, layoutJson: string): void;\n getNode(id: number): string;\n treeSummary(): string;\n nodeCount(): number;\n frameCount(): number;\n createNode(kind: string): number;\n appendChild(parent: number, child: number): boolean;\n /** Fast path: insert `child` immediately before `before` in the tree. */\n insertBefore(before: number, child: number): boolean;\n removeNode(id: number): void;\n setText(id: number, text: string): void;\n setScrollOffset(id: number, scrollX: number, scrollY: number): void;\n root(): number;\n validate(): boolean;\n printTree(): string;\n shutdown(): void;\n hitGridCheck(x: number, y: number): number;\n hitGridIsDirty(): boolean;\n hitGridClearCurrent(): void;\n hitGridPushScissor(x: number, y: number, width: number, height: number): void;\n hitGridPopScissor(): void;\n hitGridAddCurrentClipped(x: number, y: number, width: number, height: number, id: number): void;\n hitGridDump(): string;\n}\n\nexport interface NapiEventBus {\n pushKey(key: string, ctrl: boolean, shift: boolean, alt: boolean): void;\n pushMouse(button: string, x: number, y: number): void;\n pushMouseMotion(x: number, y: number): void;\n pushPaste(text: string): void;\n pushResize(width: number, height: number, prevWidth: number, prevHeight: number): void;\n drain(): string;\n len(): number;\n isEmpty(): boolean;\n clear(): void;\n}\n\nexport interface NapiFocusManager {\n focus(id: number): boolean;\n blur(id: number): boolean;\n blurCurrent(): boolean;\n focused(): number;\n isFocused(id: number): boolean;\n traverse(direction: string): number;\n focusOrder(): number[];\n clear(): void;\n}\n\nexport interface NapiTextEngine {\n insertChar(ch: string): void;\n insertStr(text: string): void;\n deleteChar(): void;\n cursorLeft(): void;\n cursorRight(): void;\n getText(): string;\n cursorPosition(): number;\n setCursorPosition(pos: number): void;\n length(): number;\n lineCount(): number;\n isEmpty(): boolean;\n wordCount(): number;\n canUndo(): boolean;\n canRedo(): boolean;\n undo(): boolean;\n redo(): boolean;\n clear(): void;\n}\n\nexport interface NapiScheduler {\n requestFrame(): void;\n beginFrame(): boolean;\n endFrame(): void;\n shouldRender(): boolean;\n isIdle(): boolean;\n frameCount(): number;\n fps(): number;\n requestRenderCoalesced(): void;\n requestRenderImmediate(): void;\n hasScheduledFrame(): boolean;\n isRendering(): boolean;\n beginRender(): void;\n endRender(): boolean;\n}\n\nexport interface NapiKeymap {\n addBinding(\n layer: string,\n id: string,\n keys: string,\n command: string,\n description: string | null,\n priority: number,\n ): boolean;\n handleKey(key: string): string;\n hasPending(): boolean;\n clearPending(): void;\n setMode(mode: string): void;\n currentMode(): string;\n clearMode(): void;\n removeLayer(name: string): boolean;\n setChordTimeout(ms: number): void;\n chordTimeout(): number;\n pendingKeys(): string[];\n activeBindings(): BindingInfo[];\n allBindings(): BindingInfo[];\n commandHistory(): string[];\n clearHistory(): void;\n parseKey(keyStr: string): string;\n parseSequence(keyStr: string): string[];\n}\n\nclass EngineWrapper implements NapiEngine {\n constructor(private engine: NativeEngine) {}\n processCommands(commandsJson: string): CommandResult {\n return JSON.parse(this.engine.processCommands(commandsJson));\n }\n beginFrame(): void {\n this.engine.beginFrame();\n }\n commitFrame(): void {\n this.engine.commitFrame();\n }\n render(): RenderResult {\n return JSON.parse(this.engine.render());\n }\n renderFull(): RenderResult {\n return JSON.parse(this.engine.renderFull());\n }\n resize(width: number, height: number): void {\n this.engine.resize(width, height);\n }\n setScreenMode(mode: string, footerHeight?: number | null): void {\n this.engine.setScreenMode(mode, footerHeight ?? null);\n }\n setBackgroundColor(color: string): void {\n this.engine.setBackgroundColor?.(color);\n }\n setStyle(id: number, styleJson: string): void {\n this.engine.setStyle(id, styleJson);\n }\n setLayout(id: number, layoutJson: string): void {\n this.engine.setLayout(id, layoutJson);\n }\n getNode(id: number): string {\n return this.engine.getNode(id);\n }\n treeSummary(): string {\n return this.engine.treeSummary();\n }\n nodeCount(): number {\n return this.engine.nodeCount();\n }\n frameCount(): number {\n return this.engine.frameCount();\n }\n createNode(kind: string): number {\n return this.engine.createNode(kind);\n }\n appendChild(parent: number, child: number): boolean {\n return this.engine.appendChild(parent, child);\n }\n insertBefore(before: number, child: number): boolean {\n return this.engine.insertBefore(before, child);\n }\n removeNode(id: number): void {\n this.engine.removeNode(id);\n }\n setText(id: number, text: string): void {\n this.engine.setText(id, text);\n }\n setScrollOffset(id: number, scrollX: number, scrollY: number): void {\n this.engine.setScrollOffset(id, scrollX, scrollY);\n }\n root(): number {\n return this.engine.root();\n }\n validate(): boolean {\n return this.engine.validate();\n }\n printTree(): string {\n return this.engine.printTree();\n }\n shutdown(): void {\n this.engine.shutdown();\n }\n hitGridCheck(x: number, y: number): number {\n return this.engine.hitGridCheck(x, y);\n }\n hitGridIsDirty(): boolean {\n return this.engine.hitGridIsDirty();\n }\n hitGridClearCurrent(): void {\n this.engine.hitGridClearCurrent();\n }\n hitGridPushScissor(x: number, y: number, width: number, height: number): void {\n this.engine.hitGridPushScissor(x, y, width, height);\n }\n hitGridPopScissor(): void {\n this.engine.hitGridPopScissor();\n }\n hitGridAddCurrentClipped(x: number, y: number, width: number, height: number, id: number): void {\n this.engine.hitGridAddCurrentClipped(x, y, width, height, id);\n }\n hitGridDump(): string {\n return this.engine.hitGridDump();\n }\n}\n\nexport function createEngine(width = 80, height = 24): NapiEngine {\n return new EngineWrapper(new native.NativeEngine(width, height));\n}\n\nexport function createEventBus(): NapiEventBus {\n const bus = new native.NativeEventBus();\n return {\n pushKey: (key, ctrl, shift, alt) => bus.pushKey(key, ctrl, shift, alt),\n pushMouse: (button, x, y) => bus.pushMouse(button, x, y),\n pushMouseMotion: (x, y) => bus.pushMouseMotion(x, y),\n pushPaste: (text) => bus.pushPaste(text),\n pushResize: (w, h, pw, ph) => bus.pushResize(w, h, pw, ph),\n drain: () => bus.drain(),\n len: () => bus.len(),\n isEmpty: () => bus.isEmpty(),\n clear: () => bus.clear(),\n };\n}\n\nexport function createFocusManager(): NapiFocusManager {\n const fm = new native.NativeFocusManager();\n return {\n focus: (id) => fm.focus(id),\n blur: (id) => fm.blur(id),\n blurCurrent: () => fm.blurCurrent(),\n focused: () => fm.focused(),\n isFocused: (id) => fm.isFocused(id),\n traverse: (dir) => {\n const result = fm.traverse(dir);\n return result === \"null\" ? 0 : Number.parseInt(result, 10);\n },\n focusOrder: () => fm.focusOrder(),\n clear: () => fm.clear(),\n };\n}\n\nexport function createTextEngine(text?: string): NapiTextEngine {\n const te = new native.NativeTextEngine(text ?? null);\n return {\n insertChar: (ch) => te.insertChar(ch),\n insertStr: (t) => te.insertStr(t),\n deleteChar: () => te.deleteChar(),\n getText: () => te.getText(),\n clear: () => te.clear(),\n canUndo: () => te.canUndo(),\n canRedo: () => te.canRedo(),\n undo: () => te.undo(),\n redo: () => te.redo(),\n cursorLeft: () => te.cursorLeft(),\n cursorRight: () => te.cursorRight(),\n cursorPosition: () => te.cursorPosition(),\n setCursorPosition: (pos) => te.setCursorPosition(pos),\n length: () => te.length(),\n lineCount: () => te.lineCount(),\n isEmpty: () => te.isEmpty(),\n wordCount: () => te.wordCount(),\n };\n}\n\nexport function createScheduler(fps?: number): NapiScheduler {\n const sched = new native.NativeScheduler(fps ?? null);\n return {\n requestFrame: () => sched.requestFrame(),\n beginFrame: () => sched.beginFrame(),\n endFrame: () => sched.endFrame(),\n isIdle: () => sched.isIdle(),\n frameCount: () => sched.frameCount(),\n fps: () => sched.fps(),\n shouldRender: () => sched.shouldRender(),\n requestRenderCoalesced: () => sched.requestRenderCoalesced(),\n requestRenderImmediate: () => sched.requestRenderImmediate(),\n hasScheduledFrame: () => sched.hasScheduledFrame(),\n isRendering: () => sched.isRendering(),\n beginRender: () => sched.beginRender(),\n endRender: () => sched.endRender(),\n };\n}\n\nexport function createKeymap(): NapiKeymap {\n const km = new native.NativeKeymap();\n return {\n addBinding: (layer, id, keys, command, desc, priority) =>\n km.addBinding(layer, id, keys, command, desc, priority),\n handleKey: (key) => km.handleKey(key),\n hasPending: () => km.hasPending(),\n clearPending: () => km.clearPending(),\n setMode: (mode) => km.setMode(mode),\n currentMode: () => km.currentMode(),\n clearMode: () => km.clearMode(),\n removeLayer: (name) => km.removeLayer(name),\n setChordTimeout: (ms) => km.setChordTimeout(ms),\n chordTimeout: () => km.chordTimeout(),\n pendingKeys: () => km.pendingKeys(),\n activeBindings: () => JSON.parse(km.activeBindings()),\n allBindings: () => JSON.parse(km.allBindings()),\n commandHistory: () => km.commandHistory(),\n clearHistory: () => km.clearHistory(),\n parseKey: (keyStr) => km.parseKey(keyStr),\n parseSequence: (keyStr) => km.parseSequence(keyStr),\n };\n}\n\nexport function detectCapabilities(): TerminalCapabilities {\n return native.detectCapabilities();\n}\n\nexport function getVersion(): string {\n return native.getVersion();\n}\n\nexport function getNativePackageName(): string {\n return \"bettertui_engine\";\n}\n\nexport interface HighlightSegment {\n text: string;\n fg: string | null;\n bg: string | null;\n bold: boolean | null;\n italic: boolean | null;\n underline: boolean | null;\n dim: boolean | null;\n strikethrough: boolean | null;\n}\n\ninterface NativeHighlightedLine {\n segments: HighlightSegment[];\n}\n\nexport interface HighlightedLine {\n segments: HighlightSegment[];\n}\n\nexport function highlightCode(code: string, language: string): HighlightedLine[] {\n try {\n if (typeof native.highlightCode === \"function\") {\n return native.highlightCode(code, language);\n }\n } catch {\n // native binary not yet rebuilt — fall through to empty\n }\n return [];\n}\n\nexport interface NapiWidgetHost {\n widgetCount(): number;\n}\n\nexport function createWidgetHost(): NapiWidgetHost {\n return {\n widgetCount: () => 0,\n };\n}\n\n// ─── NativeSpanFeed ─────────────────────────────────────────────────────────────\n\nexport interface NativeSpanFeedOptions {\n chunkSize?: number;\n initialChunks?: number;\n maxBytes?: number;\n /** 0 = grow, 1 = block */\n growthPolicy?: number;\n autoCommitOnFull?: boolean;\n spanQueueCapacity?: number;\n}\n\ninterface NativeSpanFeed {\n write(data: Buffer): number;\n drainSpans(out: Buffer): number;\n close(): void;\n reset(): void;\n pendingSpans(): number;\n pendingBytes(): number;\n isClosed(): boolean;\n isBackpressured(): boolean;\n stats(): NapiSpanFeedStats;\n markConsumed(chunkIndex: number): void;\n}\n\ninterface NativeHitGrid {\n resize(width: number, height: number): void;\n add(x: number, y: number, width: number, height: number, id: number): void;\n check(x: number, y: number): number;\n clearNext(): void;\n clearCurrent(): void;\n swap(): boolean;\n isDirty(): boolean;\n dimensions(): string;\n pushScissor(x: number, y: number, width: number, height: number): void;\n popScissor(): void;\n clearScissors(): void;\n}\n\nexport interface NapiSpanFeedStats {\n bytesWritten: number;\n spansCommitted: number;\n chunks: number;\n pendingSpans: number;\n}\n\nexport class NapiSpanFeed {\n constructor(private feed: NativeSpanFeed) {}\n\n write(data: Buffer): number {\n return this.feed.write(data);\n }\n\n drainSpans(out: Buffer): number {\n return this.feed.drainSpans(out);\n }\n\n close(): void {\n this.feed.close();\n }\n\n reset(): void {\n this.feed.reset();\n }\n\n get pendingSpans(): number {\n return this.feed.pendingSpans();\n }\n\n get pendingBytes(): number {\n return this.feed.pendingBytes();\n }\n\n get isClosed(): boolean {\n return this.feed.isClosed();\n }\n\n get isBackpressured(): boolean {\n return this.feed.isBackpressured();\n }\n\n stats(): NapiSpanFeedStats {\n return this.feed.stats();\n }\n\n markConsumed(chunkIndex: number): void {\n this.feed.markConsumed(chunkIndex);\n }\n}\n\nexport function createSpanFeed(options?: NativeSpanFeedOptions): NapiSpanFeed {\n const nativeOptions = options\n ? {\n chunkSize: options.chunkSize ?? 65536,\n initialChunks: options.initialChunks ?? 2,\n maxBytes: options.maxBytes ?? 0,\n growthPolicy: options.growthPolicy ?? 0,\n autoCommitOnFull: options.autoCommitOnFull ?? true,\n spanQueueCapacity: options.spanQueueCapacity ?? 4096,\n }\n : null;\n return new NapiSpanFeed(new native.NativeSpanFeed(nativeOptions));\n}\n\nexport class NapiHitGrid {\n constructor(private grid: NativeHitGrid) {}\n\n resize(width: number, height: number): void {\n this.grid.resize(width, height);\n }\n\n add(x: number, y: number, width: number, height: number, id: number): void {\n this.grid.add(x, y, width, height, id);\n }\n\n check(x: number, y: number): number {\n return this.grid.check(x, y);\n }\n\n clearNext(): void {\n this.grid.clearNext();\n }\n\n clearCurrent(): void {\n this.grid.clearCurrent();\n }\n\n swap(): boolean {\n return this.grid.swap();\n }\n\n get isDirty(): boolean {\n return this.grid.isDirty();\n }\n\n pushScissor(x: number, y: number, width: number, height: number): void {\n this.grid.pushScissor(x, y, width, height);\n }\n\n popScissor(): void {\n this.grid.popScissor();\n }\n\n clearScissors(): void {\n this.grid.clearScissors();\n }\n}\n\nexport function createHitGrid(width: number, height: number): NapiHitGrid {\n return new NapiHitGrid(new native.NativeHitGrid(width, height));\n}\n\n// ─── Theme Functions ─────────────────────────────────────────────────────────────\n\nexport interface NapiThemeColors {\n background: string;\n surface: string;\n surfaceHigh: string;\n surfaceLow: string;\n primary: string;\n primaryForeground: string;\n secondary: string;\n secondaryForeground: string;\n text: string;\n textMuted: string;\n textDim: string;\n border: string;\n borderFocused: string;\n accent: string;\n accentForeground: string;\n error: string;\n warning: string;\n success: string;\n info: string;\n scrollbar: string;\n scrollbarThumb: string;\n}\n\nexport interface NapiThemeSpacing {\n none: number;\n xxs: number;\n xs: number;\n sm: number;\n md: number;\n lg: number;\n xl: number;\n xxl: number;\n}\n\nexport interface NapiThemeBorders {\n style: string;\n fg: string;\n}\n\nexport interface NapiTheme {\n name: string;\n colors: NapiThemeColors;\n spacing: NapiThemeSpacing;\n borders: NapiThemeBorders;\n}\n\nexport function createDarkTheme(): NapiTheme {\n return native.createDarkTheme();\n}\n\nexport function createLightTheme(): NapiTheme {\n return native.createLightTheme();\n}\n\n// ─── Logger Functions ─────────────────────────────────────────────────────────────\n\nexport interface NapiLoggerConfig {\n level?: string;\n color?: boolean;\n timestamp?: boolean;\n module?: boolean;\n thread?: boolean;\n file?: string;\n maxFileSize?: number;\n maxFiles?: number;\n dev?: boolean;\n}\n\nexport interface NapiDiagnosticSnapshot {\n renderCalls: number;\n renderBytes: number;\n eventDispatches: number;\n layoutComputations: number;\n cacheHits: number;\n cacheMisses: number;\n allocations: number;\n averageFrameTime: number;\n fps: number;\n}\n\nexport function loggerInit(config: NapiLoggerConfig = {}): void {\n native.loggerInit(config);\n}\n\nexport function loggerSetLevel(level: string): void {\n native.loggerSetLevel(level);\n}\n\nexport function loggerGetLevel(): string {\n return native.loggerGetLevel();\n}\n\nexport function loggerSetModuleFilter(include?: string[], exclude?: string[]): void {\n native.loggerSetModuleFilter(include ?? null, exclude ?? null);\n}\n\nexport function loggerGetDiagnostics(): NapiDiagnosticSnapshot {\n return native.loggerGetDiagnostics();\n}\n\nexport function loggerFlush(): void {\n native.loggerFlush();\n}\n\n// ─── Plugin host + slot composition ──────────────────────────────────────────\n\ninterface NativePluginHost {\n register(name: string, version: string, author: string, capabilities: string[]): string | null;\n unregister(name: string): string | null;\n initialize(name: string): string | null;\n start(name: string): string | null;\n stop(name: string): string | null;\n markError(name: string): string | null;\n state(name: string): string | null;\n pluginNames(): string[];\n ensureSlot(slot: string, mode: string): void;\n slotRegister(slot: string, pluginId: string, priority: number, value: string): number;\n slotRemove(slot: string, token: number): boolean;\n slotResolve(slot: string): string[];\n slotTakeDirty(slot: string): boolean;\n}\n\n/** Plugin lifecycle state names returned by {@link NapiPluginHost.state}. */\nexport type PluginStateName = \"registered\" | \"initialized\" | \"running\" | \"stopped\" | \"error\";\n\n/** Slot resolution mode. */\nexport type SlotMode = \"append\" | \"single-winner\" | \"replace\";\n\n/**\n * TypeScript wrapper around the native plugin host + slot registry — the\n * BetterTUI plugin API.\n * methods return an error string when the transition is illegal, else `null`.\n * Slot values are strings (typically a node id or serialized descriptor).\n */\nexport class NapiPluginHost {\n constructor(private host: NativePluginHost) {}\n\n register(\n name: string,\n version: string,\n author: string,\n capabilities: string[] = [],\n ): string | null {\n return this.host.register(name, version, author, capabilities);\n }\n\n unregister(name: string): string | null {\n return this.host.unregister(name);\n }\n\n initialize(name: string): string | null {\n return this.host.initialize(name);\n }\n\n start(name: string): string | null {\n return this.host.start(name);\n }\n\n stop(name: string): string | null {\n return this.host.stop(name);\n }\n\n markError(name: string): string | null {\n return this.host.markError(name);\n }\n\n state(name: string): PluginStateName | null {\n return this.host.state(name) as PluginStateName | null;\n }\n\n pluginNames(): string[] {\n return this.host.pluginNames();\n }\n\n ensureSlot(slot: string, mode: SlotMode = \"append\"): void {\n this.host.ensureSlot(slot, mode);\n }\n\n slotRegister(slot: string, pluginId: string, priority: number, value: string): number {\n return this.host.slotRegister(slot, pluginId, priority, value);\n }\n\n slotRemove(slot: string, token: number): boolean {\n return this.host.slotRemove(slot, token);\n }\n\n slotResolve(slot: string): string[] {\n return this.host.slotResolve(slot);\n }\n\n slotTakeDirty(slot: string): boolean {\n return this.host.slotTakeDirty(slot);\n }\n}\n\nexport function createPluginHost(): NapiPluginHost {\n return new NapiPluginHost(new native.NativePluginHost());\n}\n\n// ─── Timeline ────────────────────────────────────────────────────────────────\n\n/**\n * TypeScript wrapper around the native tween/spring animation timeline.\n * Wraps `NativeTimeline` from the napi-rs binary.\n */\nexport class NapiTimeline {\n private _tl: NativeTimelineInstance;\n\n constructor(duration?: number, looping?: boolean) {\n this._tl = new native.NativeTimeline(duration ?? null, looping ?? null);\n }\n\n /**\n * Schedule a tween from `from` → `to` over `duration` seconds starting at\n * `startTime`. Returns the animation index for {@link animationValue}.\n */\n addTween(from: number, to: number, duration: number, startTime: number, easing?: string): number {\n return this._tl.addTween(from, to, duration, startTime, easing ?? null);\n }\n\n play(): void {\n this._tl.play();\n }\n pause(): void {\n this._tl.pause();\n }\n restart(): void {\n this._tl.restart();\n }\n\n /** Advance by `dt` seconds (frame delta). Call once per frame. */\n update(dt: number): void {\n this._tl.update(dt);\n }\n\n /** Current interpolated value of tween at `index`. */\n animationValue(index: number): number | null {\n return this._tl.animationValue(index);\n }\n\n currentTime(): number {\n return this._tl.currentTime();\n }\n isComplete(): boolean {\n return this._tl.isComplete();\n }\n isPlaying(): boolean {\n return this._tl.isPlaying();\n }\n setSpeed(speed: number): void {\n this._tl.setSpeed(speed);\n }\n\n /** Progress 0.0–1.0 if timeline has a fixed duration, else `null`. */\n progress(): number | null {\n return this._tl.progress();\n }\n}\n\nexport function createTimeline(duration?: number, looping?: boolean): NapiTimeline {\n return new NapiTimeline(duration, looping);\n}\n\n// ─── Graphics protocol ───────────────────────────────────────────────────────\n\nexport type GraphicsFormat = \"rgb\" | \"rgba\" | \"png\";\n\n/**\n * Build a Kitty graphics-protocol sequence transmitting+displaying raw pixel\n * or PNG data with the given numeric `id`.\n */\nexport function graphicsKittyWrite(\n format: GraphicsFormat,\n width: number,\n height: number,\n data: Buffer,\n id: number,\n): Buffer {\n try {\n return native.graphicsKittyWrite?.(format, width, height, data, id) ?? Buffer.alloc(0);\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n/** Build the Kitty sequence deleting image `id`. */\nexport function graphicsKittyDelete(id: number): Buffer {\n try {\n return native.graphicsKittyDelete?.(id) ?? Buffer.alloc(0);\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n/** Build the Kitty sequence deleting all transmitted images. */\nexport function graphicsKittyDeleteAll(): Buffer {\n try {\n return native.graphicsKittyDeleteAll?.() ?? Buffer.alloc(0);\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n/**\n * Build an iTerm2 inline-image sequence for `fileBytes` (e.g. PNG file data).\n */\nexport function graphicsItermWrite(\n fileBytes: Buffer,\n name?: string,\n width?: number,\n height?: number,\n): Buffer {\n try {\n return (\n native.graphicsItermWrite?.(fileBytes, name ?? null, width ?? null, height ?? null) ??\n Buffer.alloc(0)\n );\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n/** Build a Sixel sequence for a raw `rgb`/`rgba` image (empty for `png`). */\nexport function graphicsSixelWrite(\n format: GraphicsFormat,\n width: number,\n height: number,\n data: Buffer,\n): Buffer {\n try {\n return native.graphicsSixelWrite?.(format, width, height, data) ?? Buffer.alloc(0);\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n/**\n * Build the probe sequence(s) that detect which graphics protocols the\n * terminal supports (Kitty query + DA1 for Sixel). Write the returned bytes\n * to stdout, then wait for the terminal's DA1 response.\n */\nexport function graphicsQuery(): Buffer {\n try {\n return native.graphicsQuery?.() ?? Buffer.alloc(0);\n } catch {\n return Buffer.alloc(0);\n }\n}\n\n// ─── Clipboard (OSC 52) ──────────────────────────────────────────────────────\n\n/**\n * Build the OSC 52 sequence that sets the terminal clipboard to `text`.\n * Write the returned bytes to stdout.\n * `selection`: `\"clipboard\"` | `\"primary\"` | `\"secondary\"` | `\"tertiary\"`\n */\nexport function clipboardSetSequence(selection: string, text: string): number[] {\n try {\n const buf = native.clipboardSetSequence?.(selection, text);\n return buf ? Array.from(buf) : [];\n } catch {\n return [];\n }\n}\n\n/**\n * Build the OSC 52 query sequence asking the terminal to report clipboard\n * contents. Write the returned bytes to stdout; the response arrives as an\n * inbound OSC 52 which {@link clipboardDecode} can decode.\n */\nexport function clipboardQuerySequence(selection: string): number[] {\n try {\n const buf = native.clipboardQuerySequence?.(selection);\n return buf ? Array.from(buf) : [];\n } catch {\n return [];\n }\n}\n\n/**\n * Decode a base64 OSC 52 clipboard payload into UTF-8 text.\n * Returns `null` for the `?` query marker or invalid base64/UTF-8.\n */\nexport function clipboardDecode(payload: string): string | null {\n try {\n return native.clipboardDecode?.(payload) ?? null;\n } catch {\n return null;\n }\n}\n","import type { Command } from \"./command\";\nimport { CommandBuffer } from \"./command\";\nimport { SystemClock } from \"./lib/clock\";\nimport type { Clock, TimerHandle } from \"./lib/clock\";\nimport type { NapiEngine } from \"./platform/binding\";\nimport { detectCapabilities } from \"./platform/binding\";\n\nexport interface CommandRuntimeOptions {\n frameIntervalMs?: number;\n autoStart?: boolean;\n engine?: NapiEngine;\n clock?: Clock;\n}\n\nexport class CommandRuntime {\n private buffer: CommandBuffer;\n private running = false;\n private frameHandle: TimerHandle | null = null;\n private subscribers: Array<(commands: Command[]) => void> = [];\n private frameCallbacks: Array<(deltaMs: number) => void> = [];\n private lastFrameTime = 0;\n private frameIntervalMs: number;\n private engine: NapiEngine | undefined;\n private width: number;\n private height: number;\n private clock: Clock;\n\n constructor(bufferOrOptions?: CommandBuffer | CommandRuntimeOptions) {\n this.clock = new SystemClock();\n if (bufferOrOptions instanceof CommandBuffer) {\n this.buffer = bufferOrOptions;\n this.frameIntervalMs = 16;\n this.width = 80;\n this.height = 24;\n } else {\n this.buffer = new CommandBuffer();\n this.frameIntervalMs = bufferOrOptions?.frameIntervalMs ?? 16;\n this.engine = bufferOrOptions?.engine;\n if (bufferOrOptions?.clock) {\n this.clock = bufferOrOptions.clock;\n }\n const caps = detectCapabilities();\n this.width = caps.columns;\n this.height = caps.rows;\n if (bufferOrOptions?.autoStart) {\n this.startFrameLoop();\n }\n }\n }\n\n get commandBuffer(): CommandBuffer {\n return this.buffer;\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n get terminalWidth(): number {\n return this.width;\n }\n\n get terminalHeight(): number {\n return this.height;\n }\n\n drain(): Command[] {\n return this.buffer.drain();\n }\n\n flush(): void {\n const commands = this.drain();\n if (commands.length > 0) {\n for (const sub of this.subscribers) {\n sub(commands);\n }\n }\n }\n\n subscribe(fn: (commands: Command[]) => void): () => void {\n this.subscribers.push(fn);\n return () => {\n this.subscribers = this.subscribers.filter((s) => s !== fn);\n };\n }\n\n onFrame(callback: (deltaMs: number) => void): () => void {\n this.frameCallbacks.push(callback);\n return () => {\n this.frameCallbacks = this.frameCallbacks.filter((cb) => cb !== callback);\n };\n }\n\n startFrameLoop(intervalMs?: number): void {\n if (this.running) return;\n this.running = true;\n if (intervalMs !== undefined) {\n this.frameIntervalMs = intervalMs;\n }\n this.lastFrameTime = this.clock.now();\n const tick = () => {\n if (!this.running) return;\n const now = this.clock.now();\n const delta = now - this.lastFrameTime;\n this.lastFrameTime = now;\n for (const cb of this.frameCallbacks) {\n cb(delta);\n }\n this.flush();\n if (this.running) {\n this.frameHandle = this.clock.setTimeout(tick, this.frameIntervalMs);\n }\n };\n tick();\n }\n\n stopFrameLoop(): void {\n this.running = false;\n if (this.frameHandle !== null) {\n this.clock.clearTimeout(this.frameHandle);\n this.frameHandle = null;\n }\n }\n\n requestFrame(): void {\n if (!this.running) return;\n this.flush();\n }\n\n resize(width: number, height: number): void {\n this.width = width;\n this.height = height;\n this.engine?.resize(width, height);\n }\n\n render(): { outputData: Buffer; width: number; height: number } | null {\n if (!this.engine) return null;\n this.engine.beginFrame();\n const frame = this.engine.render();\n this.engine.commitFrame();\n if (frame.output_data) {\n return {\n outputData: Buffer.from(frame.output_data, \"base64\"),\n width: frame.width,\n height: frame.height,\n };\n }\n return null;\n }\n\n dispose(): void {\n this.stopFrameLoop();\n this.subscribers = [];\n this.frameCallbacks = [];\n this.buffer.clear();\n this.engine?.shutdown();\n }\n}\n","import { generateId } from \"@bettertui/shared\";\nimport type { KeyEvent, MouseEvent } from \"@bettertui/shared\";\nimport type { Command, CommandBufferConsumer } from \"./command/command.types\";\nimport type { CliRenderer } from \"./platform/cliRenderer\";\n\nexport interface WidgetContext {\n buffer: CommandBufferConsumer;\n onKey?: (handler: (key: KeyEvent) => boolean) => void;\n offKey?: (handler: (key: KeyEvent) => boolean) => void;\n}\n\nexport interface WidgetLifecycle {\n mount(ctx: WidgetContext): void;\n unmount(): void;\n}\n\nexport interface ImperativeContext {\n renderer: CliRenderer;\n parentId: number;\n}\n\nexport abstract class Renderable<TOptions = Record<string, unknown>> {\n readonly id: string;\n protected ctx: WidgetContext | null = null;\n protected opts: TOptions;\n protected children: Renderable[] = [];\n protected _focused = false;\n protected _visible = true;\n protected _isDestroyed = false;\n protected _nodeId: number | null = null;\n\n constructor(options: TOptions = {} as TOptions) {\n this.id = generateId();\n this.opts = { ...options };\n }\n\n get options(): Readonly<TOptions> {\n return this.opts;\n }\n\n get visible(): boolean {\n return this._visible;\n }\n\n get focused(): boolean {\n return this._focused;\n }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n get nodeId(): number | null {\n return this._nodeId;\n }\n\n mount(ctx: WidgetContext): void {\n this.ctx = ctx;\n for (const child of this.children) {\n child.mount(ctx);\n }\n }\n\n unmount(): void {\n for (const child of this.children) {\n child.unmount();\n }\n this.ctx = null;\n }\n\n update(options: Partial<TOptions>): void {\n this.opts = { ...this.opts, ...options } as TOptions;\n }\n\n abstract renderCommands(id: string): Command[];\n\n add(child: Renderable): void {\n this.children.push(child);\n if (this.ctx) {\n child.mount(this.ctx);\n }\n }\n\n remove(child: Renderable): void {\n const index = this.children.indexOf(child);\n if (index !== -1) {\n child.unmount();\n this.children.splice(index, 1);\n }\n }\n\n handleKey?(key: KeyEvent): boolean;\n handleMouse?(event: MouseEvent): boolean;\n handleFocus?(): void;\n handleBlur?(): void;\n\n focus(): void {\n this._focused = true;\n this.handleFocus?.();\n }\n\n blur(): void {\n this._focused = false;\n this.handleBlur?.();\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._isDestroyed = true;\n for (const child of [...this.children]) {\n child.destroy();\n }\n this.children = [];\n this.unmount();\n }\n\n protected emitCommands(cmds: Command[]): void {\n if (!this.ctx) return;\n for (const cmd of cmds) {\n this.ctx.buffer.push(cmd);\n }\n }\n\n renderImperative(ctx: ImperativeContext): number {\n const nodeId = ctx.renderer.createNode(this.getNodeKind());\n this._nodeId = nodeId;\n\n this.applyImperativeStyle(ctx.renderer, nodeId);\n this.applyImperativeLayout(ctx.renderer, nodeId);\n this.applyImperativeContent(ctx.renderer, nodeId);\n\n ctx.renderer.appendChild(ctx.parentId, nodeId);\n\n for (const child of this.children) {\n child.renderImperative({ renderer: ctx.renderer, parentId: nodeId });\n }\n\n return nodeId;\n }\n\n protected getNodeKind(): string {\n return \"Box\";\n }\n\n protected applyImperativeStyle(_renderer: CliRenderer, _nodeId: number): void {}\n protected applyImperativeLayout(_renderer: CliRenderer, _nodeId: number): void {}\n protected applyImperativeContent(_renderer: CliRenderer, _nodeId: number): void {}\n\n protected layoutCommands(id: string, layout: Record<string, unknown>): Command[] {\n const cmds: Command[] = [];\n for (const [key, value] of Object.entries(layout)) {\n if (value === undefined || value === null) continue;\n switch (key) {\n case \"flexDirection\":\n cmds.push({\n type: \"SetFlexDirection\",\n id,\n direction: value as never,\n });\n break;\n case \"justifyContent\":\n cmds.push({ type: \"SetJustifyContent\", id, value: value as never });\n break;\n case \"alignItems\":\n cmds.push({ type: \"SetAlignItems\", id, value: value as never });\n break;\n case \"alignSelf\":\n cmds.push({ type: \"SetAlignSelf\", id, value: value as never });\n break;\n case \"flexGrow\":\n cmds.push({ type: \"SetFlexGrow\", id, value: value as number });\n break;\n case \"flexShrink\":\n cmds.push({ type: \"SetFlexShrink\", id, value: value as number });\n break;\n case \"flexBasis\":\n cmds.push({ type: \"SetFlexBasis\", id, value: value as never });\n break;\n case \"position\":\n cmds.push({ type: \"SetPosition\", id, value: value as never });\n break;\n case \"width\":\n cmds.push({ type: \"SetWidth\", id, value: value as never });\n break;\n case \"height\":\n cmds.push({ type: \"SetHeight\", id, value: value as never });\n break;\n case \"minWidth\":\n cmds.push({ type: \"SetMinWidth\", id, value: value as never });\n break;\n case \"maxWidth\":\n cmds.push({ type: \"SetMaxWidth\", id, value: value as never });\n break;\n case \"minHeight\":\n cmds.push({ type: \"SetMinHeight\", id, value: value as never });\n break;\n case \"maxHeight\":\n cmds.push({ type: \"SetMaxHeight\", id, value: value as never });\n break;\n case \"overflow\":\n cmds.push({ type: \"SetOverflow\", id, value: value as never });\n break;\n case \"opacity\":\n cmds.push({ type: \"SetOpacity\", id, value: value as number });\n break;\n case \"zIndex\":\n cmds.push({ type: \"SetZIndex\", id, value: value as number });\n break;\n case \"padding\":\n case \"paddingTop\":\n case \"paddingRight\":\n case \"paddingBottom\":\n case \"paddingLeft\":\n cmds.push({ type: \"SetPadding\", id, value: value as never });\n break;\n case \"margin\":\n case \"marginTop\":\n case \"marginRight\":\n case \"marginBottom\":\n case \"marginLeft\":\n cmds.push({ type: \"SetMargin\", id, value: value as never });\n break;\n case \"gap\":\n cmds.push({ type: \"SetGap\", id, value: value as never });\n break;\n case \"inset\":\n case \"top\":\n case \"right\":\n case \"bottom\":\n case \"left\":\n cmds.push({ type: \"SetInset\", id, value: value as never });\n break;\n }\n }\n return cmds;\n }\n\n protected styleCommands(id: string, style: Record<string, unknown>): Command[] {\n const cmds: Command[] = [];\n for (const [key, value] of Object.entries(style)) {\n if (value === undefined || value === null) continue;\n switch (key) {\n case \"color\":\n case \"fg\":\n cmds.push({ type: \"SetForeground\", id, color: value as never });\n break;\n case \"bg\":\n case \"bgColor\":\n case \"backgroundColor\":\n cmds.push({ type: \"SetBackground\", id, color: value as never });\n break;\n case \"bold\":\n cmds.push({ type: \"SetBold\", id, value: value as boolean });\n break;\n case \"italic\":\n cmds.push({ type: \"SetItalic\", id, value: value as boolean });\n break;\n case \"underline\":\n cmds.push({ type: \"SetUnderline\", id, value: value as boolean });\n break;\n case \"dim\":\n cmds.push({ type: \"SetDim\", id, value: value as boolean });\n break;\n case \"strikethrough\":\n cmds.push({ type: \"SetStrikethrough\", id, value: value as boolean });\n break;\n case \"inverse\":\n cmds.push({ type: \"SetInverse\", id, value: value as boolean });\n break;\n case \"hidden\":\n cmds.push({ type: \"SetHidden\", id, value: value as boolean });\n break;\n case \"blink\":\n cmds.push({ type: \"SetBlink\", id, value: value as boolean });\n break;\n }\n }\n return cmds;\n }\n}\n","import { createKeymap as createNativeKeymap } from \"../platform/binding\";\nimport type { NapiKeymap } from \"../platform/binding\";\n\nexport interface BindingInfo {\n id: string;\n keys: string;\n command: string;\n description: string | null;\n enabled: boolean;\n layer: string;\n}\n\nexport interface KeymapEvent {\n phase:\n | \"sequence-start\"\n | \"sequence-advance\"\n | \"sequence-clear\"\n | \"binding-execute\"\n | \"binding-reject\";\n key: string;\n command: string | null;\n keys: string[];\n}\n\nexport type CommandHandler = (ctx: CommandContext) => boolean | undefined;\n\nexport interface CommandContext {\n keymap: Keymap;\n event: KeymapEvent;\n command: string;\n payload?: Record<string, unknown>;\n data: Record<string, unknown>;\n}\n\nexport interface CommandEntry {\n name: string;\n handler: CommandHandler;\n}\n\nexport type InterceptHandler = (ctx: InterceptContext) => boolean | undefined;\n\nexport interface InterceptContext {\n key: string;\n event: KeymapEvent;\n preventDefault(): void;\n stopPropagation(): void;\n defaultPrevented: boolean;\n propagationStopped: boolean;\n}\n\nexport type KeyListener = (event: KeymapEvent) => void;\n\nexport type KeymapOptions = {\n chordTimeoutMs?: number;\n mode?: string;\n};\n\nexport interface ActiveKeyInfo {\n keys: string;\n command: string;\n description: string | null;\n layer: string;\n id: string;\n}\n\nexport class Keymap {\n private native: NapiKeymap;\n private commands = new Map<string, CommandHandler>();\n private keyIntercepts: Array<{ priority: number; handler: InterceptHandler }> = [];\n private keyAfterIntercepts: Array<{ priority: number; handler: InterceptHandler }> = [];\n private listeners = new Map<string, Set<KeyListener>>();\n private runtimeData = new Map<string, unknown>();\n private bindings: BindingInfo[] = [];\n private layers = new Set<string>([\"default\"]);\n private currentModeValue: string | null = null;\n private chordTimeoutMsValue = 500;\n private pendingKeysValue: string[] = [];\n private commandHistoryValue: string[] = [];\n\n constructor(native?: NapiKeymap, options?: KeymapOptions) {\n this.native = native ?? createNativeKeymap();\n if (options?.chordTimeoutMs !== undefined) {\n this.chordTimeoutMsValue = options.chordTimeoutMs;\n }\n if (options?.mode !== undefined) {\n this.currentModeValue = options.mode;\n }\n }\n\n addBinding(\n layer: string,\n id: string,\n keys: string,\n command: string,\n description?: string,\n priority?: number,\n ): boolean {\n const result = this.native.addBinding(\n layer,\n id,\n keys,\n command,\n description ?? null,\n priority ?? 0,\n );\n if (result) {\n this.bindings.push({\n id,\n keys,\n command,\n description: description ?? null,\n enabled: true,\n layer,\n });\n this.layers.add(layer);\n }\n return result;\n }\n\n addSimpleBinding(keys: string, command: string, description?: string): boolean {\n return this.addBinding(\"default\", command, keys, command, description, 0);\n }\n\n removeLayer(name: string): boolean {\n this.bindings = this.bindings.filter((b) => b.layer !== name);\n this.layers.delete(name);\n return true;\n }\n\n setChordTimeout(ms: number): void {\n this.chordTimeoutMsValue = ms;\n }\n\n chordTimeout(): number {\n return this.chordTimeoutMsValue;\n }\n\n registerCommand(name: string, handler: CommandHandler): void {\n this.commands.set(name, handler);\n }\n\n unregisterCommand(name: string): boolean {\n return this.commands.delete(name);\n }\n\n getCommand(name: string): CommandHandler | undefined {\n return this.commands.get(name);\n }\n\n hasCommand(name: string): boolean {\n return this.commands.has(name);\n }\n\n getCommands(): CommandEntry[] {\n const entries: CommandEntry[] = [];\n for (const [name, handler] of this.commands) {\n entries.push({ name, handler });\n }\n return entries;\n }\n\n intercept(name: \"key\" | \"key:after\", handler: InterceptHandler, priority?: number): () => void {\n const pri = priority ?? 0;\n const entry = { priority: pri, handler };\n if (name === \"key\") {\n this.keyIntercepts.push(entry);\n this.keyIntercepts.sort((a, b) => b.priority - a.priority);\n } else {\n this.keyAfterIntercepts.push(entry);\n this.keyAfterIntercepts.sort((a, b) => b.priority - a.priority);\n }\n return () => {\n if (name === \"key\") {\n this.keyIntercepts = this.keyIntercepts.filter((e) => e.handler !== handler);\n } else {\n this.keyAfterIntercepts = this.keyAfterIntercepts.filter((e) => e.handler !== handler);\n }\n };\n }\n\n on(event: \"state\" | \"pendingSequence\" | \"dispatch\", listener: KeyListener): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)?.add(listener);\n return () => {\n this.listeners.get(event)?.delete(listener);\n };\n }\n\n off(event: \"state\" | \"pendingSequence\" | \"dispatch\", listener: KeyListener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n private emit(event: string, data: KeymapEvent): void {\n const fire = (name: string) => {\n const set = this.listeners.get(name);\n if (!set) return;\n for (const listener of set) {\n try {\n listener(data);\n } catch {\n // Swallow errors\n }\n }\n };\n fire(event);\n if (event !== \"state\") fire(\"state\");\n }\n\n handleKey(keyStr: string): string | null {\n const event: KeymapEvent = {\n phase: \"sequence-start\",\n key: keyStr,\n command: null,\n keys: this.hasPending() ? [...this.pendingKeysValue, keyStr] : [keyStr],\n };\n\n for (const intercept of this.keyIntercepts) {\n const ctx: InterceptContext = {\n key: keyStr,\n event,\n preventDefault() {\n ctx.defaultPrevented = true;\n },\n stopPropagation() {\n ctx.propagationStopped = true;\n },\n defaultPrevented: false,\n propagationStopped: false,\n };\n intercept.handler(ctx);\n if (ctx.defaultPrevented || ctx.propagationStopped) {\n return null;\n }\n }\n\n const command = this.native.handleKey(keyStr);\n const commandOrNull = command.length > 0 ? command : null;\n\n if (commandOrNull !== null) {\n event.phase = \"binding-execute\";\n event.command = commandOrNull;\n this.emit(\"dispatch\", event);\n if (this.hasPending()) {\n this.emit(\"pendingSequence\", event);\n }\n this.commandHistoryValue.push(commandOrNull);\n const handler = this.commands.get(commandOrNull);\n if (handler) {\n const ctx: CommandContext = {\n keymap: this,\n event,\n command: commandOrNull,\n data: Object.fromEntries(this.runtimeData),\n };\n handler(ctx);\n }\n } else if (this.hasPending()) {\n event.phase = \"sequence-advance\";\n this.pendingKeysValue.push(keyStr);\n this.emit(\"pendingSequence\", event);\n } else {\n event.phase = \"sequence-clear\";\n this.emit(\"dispatch\", event);\n }\n\n for (const intercept of this.keyAfterIntercepts) {\n const ctx: InterceptContext = {\n key: keyStr,\n event,\n preventDefault() {\n ctx.defaultPrevented = true;\n },\n stopPropagation() {\n ctx.propagationStopped = true;\n },\n defaultPrevented: false,\n propagationStopped: false,\n };\n intercept.handler(ctx);\n }\n\n this.emit(\"state\", event);\n return commandOrNull;\n }\n\n setMode(mode: string): void {\n this.currentModeValue = mode;\n }\n\n currentMode(): string | null {\n return this.currentModeValue;\n }\n\n clearMode(): void {\n this.currentModeValue = null;\n }\n\n hasPending(): boolean {\n return this.native.hasPending();\n }\n\n clearPending(): void {\n this.native.clearPending();\n this.pendingKeysValue = [];\n }\n\n pendingKeys(): string[] {\n return this.pendingKeysValue;\n }\n\n activeBindings(): BindingInfo[] {\n return this.bindings.filter((b) => b.enabled);\n }\n\n allBindings(): BindingInfo[] {\n return [...this.bindings];\n }\n\n commandHistory(): string[] {\n return [...this.commandHistoryValue];\n }\n\n clearHistory(): void {\n this.commandHistoryValue = [];\n }\n\n setData(key: string, value: unknown): void {\n this.runtimeData.set(key, value);\n }\n\n getData(key: string): unknown {\n return this.runtimeData.get(key);\n }\n\n getCommandBindings(command: string): BindingInfo[] {\n return this.bindings.filter((b) => b.command === command);\n }\n\n getBindingsForCommands(commands: string[]): Map<string, BindingInfo[]> {\n const result = new Map<string, BindingInfo[]>();\n for (const cmd of commands) {\n result.set(\n cmd,\n this.bindings.filter((b) => b.command === cmd),\n );\n }\n return result;\n }\n\n runCommand(command: string, payload?: Record<string, unknown>): boolean {\n const handler = this.commands.get(command);\n if (!handler) return false;\n const event: KeymapEvent = {\n phase: \"binding-execute\",\n key: \"\",\n command,\n keys: [],\n };\n const ctx: CommandContext = {\n keymap: this,\n event,\n command,\n ...(payload !== undefined ? { payload } : {}),\n data: Object.fromEntries(this.runtimeData),\n };\n handler(ctx);\n return true;\n }\n\n parseKey(keyStr: string): string | null {\n return keyStr.length > 0 ? keyStr : null;\n }\n\n parseSequence(keyStr: string): string[] {\n return keyStr.split(\" \").filter((k) => k.length > 0);\n }\n\n formatKeySequence(keys: string[]): string {\n return keys.join(\" \");\n }\n\n stringifyKeySequence(\n keys: string[],\n options?: { preferDisplay?: boolean; separator?: string },\n ): string {\n return keys.join(options?.separator ?? \" \");\n }\n\n formatBinding(binding: BindingInfo): string {\n const parts = [binding.keys];\n if (binding.description) {\n parts.push(`- ${binding.description}`);\n }\n return parts.join(\" \");\n }\n\n formatCommandBindings(entries: Array<{ command: string; bindings: BindingInfo[] }>): string[] {\n return entries.map((entry) => {\n const keys = entry.bindings.map((b) => b.keys).join(\", \");\n return `${entry.command}: ${keys}`;\n });\n }\n\n getNative(): NapiKeymap {\n return this.native;\n }\n}\n","// Kitty Keyboard Protocol parser\n// Based on https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\nimport type { KeyEventType, ParsedKey } from \"./parseKeypress\";\n\nconst ESC = \"\\x1b\";\n\nconst kittyKeyMap: Record<number, string> = {\n // Standard keys\n 27: \"escape\",\n 9: \"tab\",\n 13: \"return\",\n 127: \"backspace\",\n\n // Arrow keys\n 57344: \"escape\",\n 57345: \"return\",\n 57346: \"tab\",\n 57347: \"backspace\",\n 57348: \"insert\",\n 57349: \"delete\",\n 57350: \"left\",\n 57351: \"right\",\n 57352: \"up\",\n 57353: \"down\",\n 57354: \"pageup\",\n 57355: \"pagedown\",\n 57356: \"home\",\n 57357: \"end\",\n 57358: \"capslock\",\n 57359: \"scrolllock\",\n 57360: \"numlock\",\n 57361: \"printscreen\",\n 57362: \"pause\",\n 57363: \"menu\",\n\n // Function keys\n 57364: \"f1\",\n 57365: \"f2\",\n 57366: \"f3\",\n 57367: \"f4\",\n 57368: \"f5\",\n 57369: \"f6\",\n 57370: \"f7\",\n 57371: \"f8\",\n 57372: \"f9\",\n 57373: \"f10\",\n 57374: \"f11\",\n 57375: \"f12\",\n 57376: \"f13\",\n 57377: \"f14\",\n 57378: \"f15\",\n 57379: \"f16\",\n 57380: \"f17\",\n 57381: \"f18\",\n 57382: \"f19\",\n 57383: \"f20\",\n 57384: \"f21\",\n 57385: \"f22\",\n 57386: \"f23\",\n 57387: \"f24\",\n 57388: \"f25\",\n 57389: \"f26\",\n 57390: \"f27\",\n 57391: \"f28\",\n 57392: \"f29\",\n 57393: \"f30\",\n 57394: \"f31\",\n 57395: \"f32\",\n 57396: \"f33\",\n 57397: \"f34\",\n 57398: \"f35\",\n\n // Keypad\n 57399: \"kp0\",\n 57400: \"kp1\",\n 57401: \"kp2\",\n 57402: \"kp3\",\n 57403: \"kp4\",\n 57404: \"kp5\",\n 57405: \"kp6\",\n 57406: \"kp7\",\n 57407: \"kp8\",\n 57408: \"kp9\",\n 57409: \"kpdecimal\",\n 57410: \"kpdivide\",\n 57411: \"kpmultiply\",\n 57412: \"kpminus\",\n 57413: \"kpplus\",\n 57414: \"kpenter\",\n 57415: \"kpequal\",\n 57416: \"kpseparator\",\n 57417: \"kpleft\",\n 57418: \"kpright\",\n 57419: \"kpup\",\n 57420: \"kpdown\",\n 57421: \"kppageup\",\n 57422: \"kppagedown\",\n 57423: \"kphome\",\n 57424: \"kpend\",\n 57425: \"kpinsert\",\n 57426: \"kpdelete\",\n 57427: \"clear\",\n\n // Media keys\n 57428: \"mediaplay\",\n 57429: \"mediapause\",\n 57430: \"mediaplaypause\",\n 57431: \"mediareverse\",\n 57432: \"mediastop\",\n 57433: \"mediafastforward\",\n 57434: \"mediarewind\",\n 57435: \"medianext\",\n 57436: \"mediaprev\",\n 57437: \"mediarecord\",\n\n // Volume keys\n 57438: \"volumedown\",\n 57439: \"volumeup\",\n 57440: \"mute\",\n\n // Modifiers\n 57441: \"leftshift\",\n 57442: \"leftctrl\",\n 57443: \"leftalt\",\n 57444: \"leftsuper\",\n 57445: \"lefthyper\",\n 57446: \"leftmeta\",\n 57447: \"rightshift\",\n 57448: \"rightctrl\",\n 57449: \"rightalt\",\n 57450: \"rightsuper\",\n 57451: \"righthyper\",\n 57452: \"rightmeta\",\n\n // Special\n 57453: \"iso_level3_shift\",\n 57454: \"iso_level5_shift\",\n};\n\nexport const kittyNamedSingleStrokeKeys = [...new Set(Object.values(kittyKeyMap))];\n\nconst printableKeypadText: Record<string, string> = {\n kp0: \"0\",\n kp1: \"1\",\n kp2: \"2\",\n kp3: \"3\",\n kp4: \"4\",\n kp5: \"5\",\n kp6: \"6\",\n kp7: \"7\",\n kp8: \"8\",\n kp9: \"9\",\n kpdecimal: \".\",\n kpdivide: \"/\",\n kpmultiply: \"*\",\n kpminus: \"-\",\n kpplus: \"+\",\n kpequal: \"=\",\n kpseparator: \",\",\n};\n\nfunction getPrintableKittyKeyText(name: string): string | undefined {\n return printableKeypadText[name];\n}\n\nfunction fromKittyMods(mod: number): {\n shift: boolean;\n alt: boolean;\n ctrl: boolean;\n super: boolean;\n hyper: boolean;\n meta: boolean;\n capsLock: boolean;\n numLock: boolean;\n} {\n return {\n shift: (mod & 1) === 1,\n alt: (mod & 2) === 2,\n ctrl: (mod & 4) === 4,\n super: (mod & 8) === 8,\n hyper: (mod & 16) === 16,\n meta: (mod & 32) === 32,\n capsLock: (mod & 64) === 64,\n numLock: (mod & 128) === 128,\n };\n}\n\n// Map functional key CSI codes to key names\nconst functionalKeyMap: Record<string, string> = {\n A: \"up\",\n B: \"down\",\n C: \"right\",\n D: \"left\",\n H: \"home\",\n F: \"end\",\n E: \"clear\",\n P: \"f1\",\n Q: \"f2\",\n S: \"f4\",\n};\n\n// Map tilde key numbers to key names (CSI number ~ format)\nconst tildeKeyMap: Record<string, string> = {\n \"1\": \"home\",\n \"2\": \"insert\",\n \"3\": \"delete\",\n \"4\": \"end\",\n \"5\": \"pageup\",\n \"6\": \"pagedown\",\n \"7\": \"home\",\n \"8\": \"end\",\n \"11\": \"f1\",\n \"12\": \"f2\",\n \"13\": \"f3\",\n \"14\": \"f4\",\n \"15\": \"f5\",\n \"17\": \"f6\",\n \"18\": \"f7\",\n \"19\": \"f8\",\n \"20\": \"f9\",\n \"21\": \"f10\",\n \"23\": \"f11\",\n \"24\": \"f12\",\n \"29\": \"menu\",\n \"57427\": \"clear\",\n};\n\nfunction createDefaultParsedKey(_sequence: string): ParsedKey {\n return {\n name: \"\",\n ctrl: false,\n meta: false,\n shift: false,\n option: false,\n number: false,\n sequence: _sequence,\n raw: _sequence,\n eventType: \"press\" as KeyEventType,\n source: \"kitty\",\n };\n}\n\n/**\n * Parse Kitty keyboard protocol special keys (functional and tilde) with event type.\n * Formats:\n * Functional: CSI 1;modifiers:event_type LETTER (e.g., ESC[1;1:1A = up arrow press)\n * Tilde: CSI number;modifiers:event_type ~ (e.g., ESC[5;1:1~ = pageup press)\n */\nfunction parseKittySpecialKey(sequence: string): ParsedKey | null {\n const specialKeyRe = new RegExp(`^${ESC}\\\\[(\\\\d+);(\\\\d+):(\\\\d+)([A-Z~])$`);\n const match = specialKeyRe.exec(sequence);\n\n if (!match) return null;\n\n const keyNumOrOne = match[1];\n const modifierStr = match[2];\n const eventTypeStr = match[3];\n const terminator = match[4];\n\n if (!keyNumOrOne || !modifierStr || !eventTypeStr || !terminator) return null;\n\n // Determine key name based on terminator\n let keyName: string | undefined;\n if (terminator === \"~\") {\n keyName = tildeKeyMap[keyNumOrOne];\n } else {\n if (keyNumOrOne !== \"1\") return null;\n keyName = functionalKeyMap[terminator];\n }\n\n if (!keyName) return null;\n\n const key = createDefaultParsedKey(sequence);\n key.name = keyName;\n key.code = sequence;\n\n // Parse modifiers\n if (modifierStr) {\n const modifierMask = Number.parseInt(modifierStr, 10);\n if (!Number.isNaN(modifierMask) && modifierMask > 1) {\n const mods = fromKittyMods(modifierMask - 1);\n key.shift = mods.shift;\n key.ctrl = mods.ctrl;\n key.option = mods.alt;\n key.meta = mods.alt || mods.meta;\n key.super = mods.super;\n key.hyper = mods.hyper;\n key.capsLock = mods.capsLock;\n key.numLock = mods.numLock;\n }\n }\n\n // Parse event type: 1 = press, 2 = repeat, 3 = release.\n // We map repeat to `\"press\"` + `repeated: true` so downstream\n // KeyHandler delivers it as a `keypress`.\n if (eventTypeStr === \"1\" || !eventTypeStr) {\n key.eventType = \"press\";\n } else if (eventTypeStr === \"2\") {\n key.eventType = \"press\";\n key.repeated = true;\n } else if (eventTypeStr === \"3\") {\n key.eventType = \"release\";\n }\n\n return key;\n}\n\n/**\n * Parse Kitty keyboard protocol sequence.\n *\n * Format: CSI unicode-key-code:alternate-key-codes ; modifiers:event-type ; text-as-codepoints u\n *\n * Examples:\n * ESC[99;1:1u = 'c' key press\n * ESC[99:99:99;2:1u = 'c' key press with base layout codepoint 99\n * ESC[1;1:1A = up arrow press (special key format)\n */\nexport function parseKittyKeyboard(sequence: string): ParsedKey | null {\n // Try special key format (functional letters or tilde keys with event type)\n const specialResult = parseKittySpecialKey(sequence);\n if (specialResult) return specialResult;\n\n // Kitty keyboard protocol: CSI unicode-key-code:alternate-key-codes ; modifiers:event-type ; text-as-codepoints u\n const kittyRe = new RegExp(`^${ESC}\\\\[([^${ESC}]+)u$`);\n const match = kittyRe.exec(sequence);\n\n if (!match) return null;\n\n const params = match[1];\n if (!params) return null;\n const fields = params.split(\";\");\n\n if (fields.length < 1) return null;\n\n const key = createDefaultParsedKey(sequence);\n\n let text = \"\";\n\n // Parse field 1: unicode-key-code:shifted_codepoint:base_layout_codepoint\n const field1 = fields[0]?.split(\":\") || [];\n const codepointStr = field1[0];\n if (!codepointStr) return null;\n\n const codepoint = Number.parseInt(codepointStr, 10);\n if (Number.isNaN(codepoint)) return null;\n\n let shiftedCodepoint: number | undefined;\n // Parse shifted and base codepoints\n if (field1[1]) {\n const shifted = Number.parseInt(field1[1], 10);\n if (!Number.isNaN(shifted) && shifted > 0 && shifted <= 0x10ffff) {\n shiftedCodepoint = shifted;\n }\n }\n\n // Store base layout codepoint if available\n if (field1[2]) {\n const base = Number.parseInt(field1[2], 10);\n if (!Number.isNaN(base) && base > 0) {\n key.baseCode = base;\n }\n }\n\n const knownKey = kittyKeyMap[codepoint];\n if (knownKey) {\n key.name = knownKey;\n key.code = `[${codepoint}u`;\n } else if (codepoint === 0) {\n key.name = \"\";\n } else {\n // It's a Unicode character\n if (codepoint > 0 && codepoint <= 0x10ffff) {\n const char = String.fromCodePoint(codepoint);\n key.name = char === \" \" ? \"space\" : char;\n } else {\n return null; // Invalid codepoint\n }\n }\n\n // Parse field 2: modifier_mask:event_type\n if (fields[1]) {\n const field2 = fields[1].split(\":\");\n const modifierStr = field2[0];\n const eventTypeStr = field2[1];\n\n if (modifierStr) {\n const modifierMask = Number.parseInt(modifierStr, 10);\n if (!Number.isNaN(modifierMask) && modifierMask > 1) {\n const mods = fromKittyMods(modifierMask - 1); // Kitty modifiers start from 1\n key.shift = mods.shift;\n key.ctrl = mods.ctrl;\n key.option = mods.alt;\n key.meta = mods.alt || mods.meta;\n key.super = mods.super;\n key.hyper = mods.hyper;\n key.capsLock = mods.capsLock;\n key.numLock = mods.numLock;\n }\n }\n\n // Parse event type: 1 = press (default), 2 = repeat, 3 = release.\n // We map repeat to `\"press\"` + `repeated: true`.\n if (eventTypeStr === \"1\" || !eventTypeStr) {\n key.eventType = \"press\";\n } else if (eventTypeStr === \"2\") {\n key.eventType = \"press\";\n key.repeated = true;\n } else if (eventTypeStr === \"3\") {\n key.eventType = \"release\";\n } else {\n key.eventType = \"press\";\n }\n }\n\n // Parse field 3: text_as_codepoint[:text_as_codepoint]\n if (fields[2]) {\n const codepoints = fields[2].split(\":\");\n for (const cpStr of codepoints) {\n const cp = Number.parseInt(cpStr, 10);\n if (!Number.isNaN(cp) && cp > 0 && cp <= 0x10ffff) {\n text += String.fromCodePoint(cp);\n }\n }\n }\n\n if (text === \"\") {\n text = getPrintableKittyKeyText(key.name) ?? \"\";\n }\n\n // Handle text generation for printable characters\n if (text === \"\") {\n const isPrintable = key.name.length > 0 && !kittyKeyMap[codepoint];\n if (isPrintable) {\n if (codepoint === 32) {\n text = \" \";\n } else if (key.shift && shiftedCodepoint) {\n text = String.fromCodePoint(shiftedCodepoint);\n } else if (key.shift && key.name.length === 1) {\n text = key.name.toLocaleUpperCase();\n } else {\n text = key.name;\n }\n }\n }\n\n if (text) {\n if (codepoint === 0) {\n key.name = text;\n }\n key.sequence = text;\n }\n\n // Mark as number key if applicable\n if (key.name.length === 1 && key.name >= \"0\" && key.name <= \"9\") {\n key.number = true;\n }\n\n if (codepoint === 0 && text === \"\") {\n return null;\n }\n\n return key;\n}\n","// Traditional terminal keypress parser (CSI/SS3/meta sequences)\n// Handles: arrows, F-keys, Home/End, PageUp/Down, modifier combos, meta keys\n\nimport { Buffer } from \"node:buffer\";\nimport { kittyNamedSingleStrokeKeys, parseKittyKeyboard } from \"./parseKeypressKitty\";\n\nconst ESC = \"\\x1b\";\n\nconst metaKeyCodeRe = new RegExp(`^(?:${ESC})([a-zA-Z0-9])$`);\n\nconst fnKeyRe = new RegExp(\n `^(?:${ESC}+)(O|N|\\\\[|\\\\[\\\\[)(?:(\\\\d+)(?:;(\\\\d+))?([~^$])|(?:1;)?(\\\\d+)?([a-zA-Z]))`,\n);\n\nconst modifyOtherKeysRe = new RegExp(`^${ESC}\\\\[27;(\\\\d+);(\\\\d+)~$`);\n\nconst mouseSgrCompleteRe = new RegExp(`^${ESC}\\\\[<\\\\d+;\\\\d+;\\\\d+[Mm]$`);\nconst mouseSgrPartialRe = new RegExp(`^${ESC}\\\\[<[\\\\d;]*$`);\nconst mouseSgrPartialNoEscRe = /^\\[<\\d+;\\d+;\\d+[Mm]$/;\nconst mouseSgrPartialNoEsc2Re = /^\\[<[\\d;]*$/;\n\nconst termResponseWindowSizeRe = new RegExp(`^${ESC}\\\\[\\\\d+;\\\\d+;\\\\d+t$`);\nconst termResponseCprRe = new RegExp(`^${ESC}\\\\[\\\\d+;\\\\d+R$`);\nconst termResponseDaRe = new RegExp(`^${ESC}\\\\[\\\\?[\\\\d;]+c$`);\nconst termResponseModeRe = new RegExp(`^${ESC}\\\\[\\\\?[\\\\d;]+\\\\$y$`);\nconst termResponseOscRe = new RegExp(`^${ESC}\\\\][\\\\d;].*(${ESC}\\\\\\\\|\\x07)$`);\n\nconst keyName: Record<string, string> = {\n /* xterm/gnome ESC O letter */\n OP: \"f1\",\n OQ: \"f2\",\n OR: \"f3\",\n OS: \"f4\",\n /* xterm/rxvt ESC [ number ~ */\n \"[11~\": \"f1\",\n \"[12~\": \"f2\",\n \"[13~\": \"f3\",\n \"[14~\": \"f4\",\n /* from Cygwin and used in libuv */\n \"[[A\": \"f1\",\n \"[[B\": \"f2\",\n \"[[C\": \"f3\",\n \"[[D\": \"f4\",\n \"[[E\": \"f5\",\n /* common */\n \"[15~\": \"f5\",\n \"[17~\": \"f6\",\n \"[18~\": \"f7\",\n \"[19~\": \"f8\",\n \"[20~\": \"f9\",\n \"[21~\": \"f10\",\n \"[23~\": \"f11\",\n \"[24~\": \"f12\",\n \"[29~\": \"menu\",\n \"[57427~\": \"clear\",\n /* xterm ESC [ letter */\n \"[A\": \"up\",\n \"[B\": \"down\",\n \"[C\": \"right\",\n \"[D\": \"left\",\n \"[E\": \"clear\",\n \"[F\": \"end\",\n \"[H\": \"home\",\n \"[P\": \"f1\",\n \"[Q\": \"f2\",\n \"[S\": \"f4\",\n /* xterm/gnome ESC O letter */\n OA: \"up\",\n OB: \"down\",\n OC: \"right\",\n OD: \"left\",\n OE: \"clear\",\n OF: \"end\",\n OH: \"home\",\n /* VT100 application keypad (SS3) — sent when terminal enables DECKPAM (ESC =).\n * macOS Terminal.app and other xterm-based terminals emit these when running\n * full-screen apps with the alternate screen. */\n OM: \"return\",\n Oj: \"*\",\n Ok: \"+\",\n Ol: \",\",\n Om: \"-\",\n On: \".\",\n Oo: \"/\",\n Op: \"0\",\n Oq: \"1\",\n Or: \"2\",\n Os: \"3\",\n Ot: \"4\",\n Ou: \"5\",\n Ov: \"6\",\n Ow: \"7\",\n Ox: \"8\",\n Oy: \"9\",\n OX: \"=\",\n /* xterm/rxvt ESC [ number ~ */\n \"[1~\": \"home\",\n \"[2~\": \"insert\",\n \"[3~\": \"delete\",\n \"[4~\": \"end\",\n \"[5~\": \"pageup\",\n \"[6~\": \"pagedown\",\n /* putty */\n \"[[5~\": \"pageup\",\n \"[[6~\": \"pagedown\",\n /* rxvt */\n \"[7~\": \"home\",\n \"[8~\": \"end\",\n /* rxvt keys with modifiers */\n \"[a\": \"up\",\n \"[b\": \"down\",\n \"[c\": \"right\",\n \"[d\": \"left\",\n \"[e\": \"clear\",\n /* option + arrow keys (old style) */\n f: \"right\",\n b: \"left\",\n p: \"up\",\n n: \"down\",\n \"[2$\": \"insert\",\n \"[3$\": \"delete\",\n \"[5$\": \"pageup\",\n \"[6$\": \"pagedown\",\n \"[7$\": \"home\",\n \"[8$\": \"end\",\n Oa: \"up\",\n Ob: \"down\",\n Oc: \"right\",\n Od: \"left\",\n Oe: \"clear\",\n \"[2^\": \"insert\",\n \"[3^\": \"delete\",\n \"[5^\": \"pageup\",\n \"[6^\": \"pagedown\",\n \"[7^\": \"home\",\n \"[8^\": \"end\",\n /* misc. */\n \"[Z\": \"tab\",\n};\n\nexport const nonAlphanumericKeys = [...Object.values(keyName), \"backspace\"];\n\nexport const terminalNamedSingleStrokeKeys = [\n ...new Set([\n \"return\",\n \"linefeed\",\n \"tab\",\n \"escape\",\n \"space\",\n ...nonAlphanumericKeys,\n ...kittyNamedSingleStrokeKeys,\n ]),\n];\n\nconst isShiftKey = (code: string) => {\n return [\"[a\", \"[b\", \"[c\", \"[d\", \"[e\", \"[2$\", \"[3$\", \"[5$\", \"[6$\", \"[7$\", \"[8$\", \"[Z\"].includes(\n code,\n );\n};\n\nconst isCtrlKey = (code: string) => {\n return [\"Oa\", \"Ob\", \"Oc\", \"Od\", \"Oe\", \"[2^\", \"[3^\", \"[5^\", \"[6^\", \"[7^\", \"[8^\"].includes(code);\n};\n\nconst getCtrlKeyName = (charCode: number): string | undefined => {\n if (charCode === 0) {\n return \"space\";\n }\n\n if (charCode >= 1 && charCode <= 26) {\n return String.fromCharCode(charCode + \"a\".charCodeAt(0) - 1);\n }\n\n if (charCode >= 28 && charCode <= 31) {\n return String.fromCharCode(charCode + 64);\n }\n\n return undefined;\n};\n\nexport type KeyEventType = \"press\" | \"repeat\" | \"release\";\n\nexport interface ParsedKey {\n name: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n option: boolean;\n sequence: string;\n number: boolean;\n raw: string;\n eventType: KeyEventType;\n source: \"raw\" | \"kitty\";\n code?: string;\n super?: boolean;\n hyper?: boolean;\n capsLock?: boolean;\n numLock?: boolean;\n baseCode?: number;\n repeated?: boolean;\n}\n\nexport type ParseKeypressOptions = {\n useKittyKeyboard?: boolean;\n};\n\n// Printable characters for VT100 SS3 application-keypad sequences.\nconst ss3NumpadPrintable: Record<string, string> = {\n Op: \"0\",\n Oq: \"1\",\n Or: \"2\",\n Os: \"3\",\n Ot: \"4\",\n Ou: \"5\",\n Ov: \"6\",\n Ow: \"7\",\n Ox: \"8\",\n Oy: \"9\",\n Oj: \"*\",\n Ok: \"+\",\n Ol: \",\",\n Om: \"-\",\n On: \".\",\n Oo: \"/\",\n OX: \"=\",\n};\n\nexport const parseKeypress = (\n input: Buffer | string = \"\",\n options: ParseKeypressOptions = {},\n): ParsedKey | null => {\n let str: string;\n\n if (Buffer.isBuffer(input)) {\n const firstByte = input[0];\n if (firstByte !== undefined && firstByte > 127 && input[1] === undefined) {\n const modifiedBuffer = Buffer.from(input);\n modifiedBuffer[0] = firstByte - 128;\n str = `${ESC}${String(modifiedBuffer)}`;\n } else {\n str = String(input);\n }\n } else if (input !== undefined && typeof input !== \"string\") {\n str = String(input);\n } else {\n str = input || \"\";\n }\n\n // Filter out mouse events (SGR and basic)\n if (mouseSgrCompleteRe.test(str)) {\n return null;\n }\n if (mouseSgrPartialNoEscRe.test(str)) {\n return null;\n }\n if (mouseSgrPartialRe.test(str)) {\n return null;\n }\n if (mouseSgrPartialNoEsc2Re.test(str)) {\n return null;\n }\n if (str.startsWith(`${ESC}[M`) && str.length >= 6) {\n return null;\n }\n\n // Filter out terminal response sequences (not keyboard events)\n if (termResponseWindowSizeRe.test(str)) {\n return null;\n }\n if (termResponseCprRe.test(str)) {\n return null;\n }\n if (termResponseDaRe.test(str)) {\n return null;\n }\n if (termResponseModeRe.test(str)) {\n return null;\n }\n if (str === `${ESC}[I` || str === `${ESC}[O`) {\n return null;\n }\n if (termResponseOscRe.test(str)) {\n return null;\n }\n if (str === `${ESC}[200~` || str === `${ESC}[201~`) {\n return null;\n }\n\n const key: ParsedKey = {\n name: \"\",\n ctrl: false,\n meta: false,\n shift: false,\n option: false,\n number: false,\n sequence: str,\n raw: str,\n eventType: \"press\",\n source: \"raw\",\n };\n\n key.sequence = key.sequence || str || key.name;\n\n const ctrlKeyName = str.length === 1 ? getCtrlKeyName(str.charCodeAt(0)) : undefined;\n const metaCtrlKeyName =\n str.length === 2 && str[0] === ESC ? getCtrlKeyName(str.charCodeAt(1)) : undefined;\n\n // Check for Kitty keyboard protocol if enabled\n if (options.useKittyKeyboard) {\n const kittyResult = parseKittyKeyboard(str);\n if (kittyResult) {\n return kittyResult;\n }\n }\n\n // Check for modifyOtherKeys sequences (CSI u protocol variant)\n const modifyOtherKeysMatch = modifyOtherKeysRe.exec(str);\n if (modifyOtherKeysMatch) {\n const modifierStr = modifyOtherKeysMatch[1];\n const charStr = modifyOtherKeysMatch[2];\n if (modifierStr && charStr) {\n const modifier = Number.parseInt(modifierStr, 10) - 1;\n const charCode = Number.parseInt(charStr, 10);\n\n key.ctrl = (modifier & 4) !== 0;\n key.meta = (modifier & 2) !== 0;\n key.shift = (modifier & 1) !== 0;\n key.option = (modifier & 2) !== 0;\n key.super = (modifier & 8) !== 0;\n key.hyper = (modifier & 16) !== 0;\n\n if (charCode === 13) {\n key.name = \"return\";\n } else if (charCode === 27) {\n key.name = \"escape\";\n } else if (charCode === 9) {\n key.name = \"tab\";\n } else if (charCode === 32) {\n key.name = \"space\";\n } else if (charCode === 127 || charCode === 8) {\n key.name = \"backspace\";\n } else {\n const char = String.fromCharCode(charCode);\n key.name = char;\n key.sequence = char;\n if (charCode >= 48 && charCode <= 57) {\n key.number = true;\n }\n }\n\n return key;\n }\n }\n\n if (str === \"\\r\" || str === `${ESC}\\r`) {\n key.name = \"return\";\n key.meta = str.length === 2;\n } else if (str === \"\\n\" || str === `${ESC}\\n`) {\n key.name = \"linefeed\";\n key.meta = str.length === 2;\n } else if (str === \"\\t\") {\n key.name = \"tab\";\n } else if (str === \"\\b\" || str === `${ESC}\\b` || str === \"\\x7f\" || str === `${ESC}\\x7f`) {\n key.name = \"backspace\";\n key.meta = str.charAt(0) === ESC;\n } else if (str === ESC || str === `${ESC}${ESC}`) {\n key.name = \"escape\";\n key.meta = str.length === 2;\n } else if (str === \" \" || str === `${ESC} `) {\n key.name = \"space\";\n key.meta = str.length === 2;\n } else if (ctrlKeyName) {\n key.name = ctrlKeyName;\n key.ctrl = true;\n } else if (str.length === 1 && str >= \"0\" && str <= \"9\") {\n key.name = str;\n key.number = true;\n } else if (str.length === 1 && str >= \"a\" && str <= \"z\") {\n key.name = str;\n } else if (str.length === 1 && str >= \"A\" && str <= \"Z\") {\n key.name = str.toLowerCase();\n key.shift = true;\n } else if (str.length === 1 || (str.length === 2 && (str.codePointAt(0) ?? 0) > 0xffff)) {\n key.name = str;\n } else {\n const metaMatch = metaKeyCodeRe.exec(str);\n if (metaMatch) {\n key.meta = true;\n const char = metaMatch[1];\n if (char) {\n const isUpperCase = /^[A-Z]$/.test(char);\n\n if (char === \"F\") {\n key.name = \"right\";\n } else if (char === \"B\") {\n key.name = \"left\";\n } else if (isUpperCase) {\n key.shift = true;\n key.name = char;\n } else {\n key.name = char;\n }\n }\n } else if (metaCtrlKeyName) {\n key.meta = true;\n key.ctrl = true;\n key.name = metaCtrlKeyName;\n } else {\n const fnMatch = fnKeyRe.exec(str);\n if (fnMatch) {\n const segs = [...str];\n\n if (segs[0] === ESC && segs[1] === ESC) {\n key.option = true;\n key.meta = true;\n }\n\n const code = [fnMatch[1], fnMatch[2], fnMatch[4], fnMatch[6]].filter(Boolean).join(\"\");\n\n const modifier = Number.parseInt(fnMatch[3] || fnMatch[5] || \"1\", 10) - 1;\n\n key.ctrl = key.ctrl || (modifier & 4) !== 0;\n key.meta = key.meta || (modifier & 2) !== 0;\n key.shift = key.shift || (modifier & 1) !== 0;\n key.option = key.option || (modifier & 2) !== 0;\n key.super = (modifier & 8) !== 0;\n key.hyper = (modifier & 16) !== 0;\n key.code = code;\n\n const keyNameResult = keyName[code];\n if (keyNameResult) {\n key.name = keyNameResult;\n key.shift = isShiftKey(code) || key.shift;\n key.ctrl = isCtrlKey(code) || key.ctrl;\n\n const ss3Char = ss3NumpadPrintable[code];\n if (ss3Char !== undefined) {\n key.sequence = ss3Char;\n if (key.name >= \"0\" && key.name <= \"9\") {\n key.number = true;\n }\n }\n } else {\n key.name = \"\";\n }\n } else if (str === `${ESC}[3~`) {\n key.name = \"delete\";\n key.meta = false;\n key.code = \"[3~\";\n }\n }\n }\n\n return key;\n};\n","/**\n * Mouse event parser for X10 and SGR mouse sequences.\n * Parses terminal mouse escape sequences into RawMouseEvent objects.\n */\n\nexport type MouseEventType =\n | \"down\"\n | \"up\"\n | \"move\"\n | \"drag\"\n | \"drag-end\"\n | \"drop\"\n | \"over\"\n | \"out\"\n | \"scroll\";\n\nexport interface ScrollInfo {\n direction: \"up\" | \"down\" | \"left\" | \"right\";\n delta: number;\n}\n\nexport interface RawMouseEvent {\n type: MouseEventType;\n button: number;\n x: number;\n y: number;\n modifiers: { shift: boolean; alt: boolean; ctrl: boolean };\n scroll?: ScrollInfo;\n}\n\ntype ParsedMouseSequence = {\n event: RawMouseEvent;\n consumed: number;\n};\n\nexport class MouseParser {\n private mouseButtonsPressed = new Set<number>();\n\n private static readonly SCROLL_DIRECTIONS: Record<number, \"up\" | \"down\" | \"left\" | \"right\"> = {\n 0: \"up\",\n 1: \"down\",\n 2: \"left\",\n 3: \"right\",\n };\n\n public reset(): void {\n this.mouseButtonsPressed.clear();\n }\n\n private decodeInput(data: Uint8Array): string {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString(\"latin1\");\n }\n\n public parseMouseEvent(data: Uint8Array): RawMouseEvent | null {\n const str = this.decodeInput(data);\n const parsed = this.parseMouseSequenceAt(str, 0);\n return parsed?.event ?? null;\n }\n\n public parseAllMouseEvents(data: Uint8Array): RawMouseEvent[] {\n const str = this.decodeInput(data);\n const events: RawMouseEvent[] = [];\n let offset = 0;\n\n while (offset < str.length) {\n const parsed = this.parseMouseSequenceAt(str, offset);\n if (!parsed) {\n break;\n }\n\n events.push(parsed.event);\n offset += parsed.consumed;\n }\n\n return events;\n }\n\n private parseMouseSequenceAt(str: string, offset: number): ParsedMouseSequence | null {\n if (!str.startsWith(\"\\x1b[\", offset)) return null;\n const introducer = str[offset + 2];\n\n if (introducer === \"<\") {\n return this.parseSgrSequence(str, offset);\n }\n\n if (introducer === \"M\") {\n return this.parseBasicSequence(str, offset);\n }\n\n return null;\n }\n\n private parseSgrSequence(str: string, offset: number): ParsedMouseSequence | null {\n let index = offset + 3;\n const values: [number, number, number] = [0, 0, 0];\n let part = 0;\n let hasDigit = false;\n\n while (index < str.length) {\n const char = str[index];\n const charCode = str.charCodeAt(index);\n\n if (charCode >= 48 && charCode <= 57) {\n hasDigit = true;\n const currentVal = values[part] ?? 0;\n values[part] = currentVal * 10 + (charCode - 48);\n index++;\n continue;\n }\n\n switch (char) {\n case \";\": {\n if (!hasDigit || part >= 2) return null;\n part++;\n hasDigit = false;\n index++;\n break;\n }\n case \"M\":\n case \"m\": {\n if (!hasDigit || part !== 2) return null;\n\n return {\n event: this.decodeSgrEvent(values[0], values[1], values[2], char),\n consumed: index - offset + 1,\n };\n }\n default:\n return null;\n }\n }\n\n return null;\n }\n\n private parseBasicSequence(str: string, offset: number): ParsedMouseSequence | null {\n if (offset + 6 > str.length) return null;\n\n const buttonByte = str.charCodeAt(offset + 3) - 32;\n const x = str.charCodeAt(offset + 4) - 33;\n const y = str.charCodeAt(offset + 5) - 33;\n\n return {\n event: this.decodeBasicEvent(buttonByte, x, y),\n consumed: 6,\n };\n }\n\n private decodeSgrEvent(\n rawButtonCode: number,\n wireX: number,\n wireY: number,\n pressRelease: \"M\" | \"m\",\n ): RawMouseEvent {\n const button = rawButtonCode & 3;\n const isScroll = (rawButtonCode & 64) !== 0;\n\n const isMotion = (rawButtonCode & 32) !== 0;\n const modifiers = {\n shift: (rawButtonCode & 4) !== 0,\n alt: (rawButtonCode & 8) !== 0,\n ctrl: (rawButtonCode & 16) !== 0,\n };\n\n let type: MouseEventType;\n let scrollInfo: ScrollInfo | undefined;\n\n if (isMotion) {\n const isDragging = this.mouseButtonsPressed.size > 0;\n\n if (button === 3) {\n type = \"move\";\n } else if (isDragging) {\n type = \"drag\";\n } else {\n type = \"move\";\n }\n } else if (isScroll && pressRelease === \"M\") {\n type = \"scroll\";\n const direction = MouseParser.SCROLL_DIRECTIONS[button];\n scrollInfo = direction\n ? {\n direction,\n delta: 1,\n }\n : undefined;\n } else {\n type = pressRelease === \"M\" ? \"down\" : \"up\";\n\n if (type === \"down\" && button !== 3) {\n this.mouseButtonsPressed.add(button);\n } else if (type === \"up\") {\n this.mouseButtonsPressed.clear();\n }\n }\n\n return {\n type,\n button: button === 3 ? 0 : button,\n x: wireX - 1,\n y: wireY - 1,\n modifiers,\n ...(scrollInfo ? { scroll: scrollInfo } : {}),\n };\n }\n\n private decodeBasicEvent(buttonByte: number, x: number, y: number): RawMouseEvent {\n const button = buttonByte & 3;\n const isScroll = (buttonByte & 64) !== 0;\n const isMotion = (buttonByte & 32) !== 0;\n\n const modifiers = {\n shift: (buttonByte & 4) !== 0,\n alt: (buttonByte & 8) !== 0,\n ctrl: (buttonByte & 16) !== 0,\n };\n\n let type: MouseEventType;\n let actualButton: number;\n let scrollInfo: ScrollInfo | undefined;\n\n if (isMotion) {\n type = \"move\";\n actualButton = button === 3 ? -1 : button;\n } else if (isScroll) {\n type = \"scroll\";\n actualButton = 0;\n const direction = MouseParser.SCROLL_DIRECTIONS[button];\n scrollInfo = direction\n ? {\n direction,\n delta: 1,\n }\n : undefined;\n } else {\n type = button === 3 ? \"up\" : \"down\";\n actualButton = button === 3 ? 0 : button;\n }\n\n return {\n type,\n button: actualButton,\n x,\n y,\n modifiers,\n ...(scrollInfo ? { scroll: scrollInfo } : {}),\n };\n }\n}\n","/**\n * Central keyboard event handler with priority-based dispatch.\n * Global handlers run before renderable handlers for proper event propagation.\n */\n\nimport { EventEmitter } from \"node:events\";\nimport type { KeyEventType, ParsedKey } from \"./parseKeypress\";\n\ntype EventHandler = (...args: unknown[]) => void;\n\nexport class KeyEvent implements ParsedKey {\n name: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n option: boolean;\n sequence: string;\n number: boolean;\n raw: string;\n eventType: KeyEventType;\n source: \"raw\" | \"kitty\";\n code?: string;\n super?: boolean;\n hyper?: boolean;\n capsLock?: boolean;\n numLock?: boolean;\n baseCode?: number;\n repeated?: boolean;\n\n private _defaultPrevented = false;\n private _propagationStopped = false;\n\n constructor(key: ParsedKey) {\n this.name = key.name;\n this.ctrl = key.ctrl;\n this.meta = key.meta;\n this.shift = key.shift;\n this.option = key.option;\n this.sequence = key.sequence;\n this.number = key.number;\n this.raw = key.raw;\n this.eventType = key.eventType;\n this.source = key.source;\n if (key.code !== undefined) this.code = key.code;\n if (key.super !== undefined) this.super = key.super;\n if (key.hyper !== undefined) this.hyper = key.hyper;\n if (key.capsLock !== undefined) this.capsLock = key.capsLock;\n if (key.numLock !== undefined) this.numLock = key.numLock;\n if (key.baseCode !== undefined) this.baseCode = key.baseCode;\n if (key.repeated !== undefined) this.repeated = key.repeated;\n }\n\n /** Alias for `option` — backward-compatible with RawKeyEvent.alt. */\n get alt(): boolean {\n return this.option;\n }\n\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n get propagationStopped(): boolean {\n return this._propagationStopped;\n }\n\n preventDefault(): void {\n this._defaultPrevented = true;\n }\n\n stopPropagation(): void {\n this._propagationStopped = true;\n }\n}\n\n/**\n * Metadata attached to a {@link PasteEvent}. Used by consumers to decide\n * whether to insert, filter, or transform pasted content (e.g. skip binary\n * paste into a text field).\n */\nexport interface PasteMetadata {\n /** MIME type if the terminal reported one (e.g. `text/plain`). */\n mimeType?: string;\n /** Coarse kind of the pasted payload. */\n kind?: \"text\" | \"binary\" | \"unknown\";\n}\n\nexport class PasteEvent {\n type = \"paste\" as const;\n bytes: Uint8Array;\n /** Optional metadata attached to the paste event (e.g. bracketed-paste info). */\n metadata?: PasteMetadata;\n private _defaultPrevented = false;\n private _propagationStopped = false;\n\n constructor(bytes: Uint8Array, metadata?: PasteMetadata) {\n this.bytes = bytes;\n this.metadata = metadata;\n }\n\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n get propagationStopped(): boolean {\n return this._propagationStopped;\n }\n\n preventDefault(): void {\n this._defaultPrevented = true;\n }\n\n stopPropagation(): void {\n this._propagationStopped = true;\n }\n}\n\nexport type KeyHandlerEventMap = {\n keypress: [KeyEvent];\n keyrelease: [KeyEvent];\n paste: [PasteEvent];\n};\n\nexport class KeyHandler extends EventEmitter<KeyHandlerEventMap> {\n public processParsedKey(parsedKey: ParsedKey): boolean {\n try {\n switch (parsedKey.eventType) {\n case \"press\":\n this.emit(\"keypress\", new KeyEvent(parsedKey));\n break;\n case \"release\":\n this.emit(\"keyrelease\", new KeyEvent(parsedKey));\n break;\n default:\n this.emit(\"keypress\", new KeyEvent(parsedKey));\n break;\n }\n } catch (error) {\n console.error(\"[KeyHandler] Error processing parsed key:\", error);\n return true;\n }\n\n return true;\n }\n\n public processPaste(bytes: Uint8Array, metadata?: PasteMetadata): void {\n try {\n this.emit(\"paste\", new PasteEvent(bytes, metadata));\n } catch (error) {\n console.error(\"[KeyHandler] Error processing paste:\", error);\n }\n }\n}\n\n/**\n * This class is used internally by the renderer to ensure global handlers\n * can preventDefault before renderable handlers process events.\n *\n * NOTE: `emit` is overridden to route every emission through `emitWithPriority`,\n * so that global listeners always run before renderable listeners and can\n * `preventDefault()` / `stopPropagation()` to short-circuit them. Previously\n * this override was missing, which meant `processParsedKey`'s direct\n * `this.emit(\"keypress\", …)` bypassed priority dispatch entirely.\n */\nexport class InternalKeyHandler extends KeyHandler {\n private renderableHandlers: Map<keyof KeyHandlerEventMap, Set<EventHandler>> = new Map();\n\n /**\n * Override `emit` so that all emissions for the three domain event types go\n * through `emitWithPriority` (global listeners first, then renderable\n * listeners, with propagation / defaultPrevented checks in between).\n * Unknown event names fall through to the base `EventEmitter.emit` so that\n * Node's internal events (e.g. `newListener`, `removeListener`) are not\n * broken.\n */\n public emit(event: string | symbol, ...args: unknown[]): boolean {\n if (event === \"keypress\" || event === \"keyrelease\" || event === \"paste\") {\n return this.emitWithPriority(\n event as keyof KeyHandlerEventMap,\n // biome-ignore lint/suspicious/noExplicitAny: priority dispatch cast\n ...(args as any),\n );\n }\n return super.emit(event, ...args);\n }\n\n public emitWithPriority<K extends keyof KeyHandlerEventMap>(\n event: K,\n ...args: KeyHandlerEventMap[K]\n ): boolean {\n let hasGlobalListeners = false;\n\n const globalListeners = this.listeners(event as never);\n if (globalListeners.length > 0) {\n hasGlobalListeners = true;\n\n for (const listener of globalListeners) {\n try {\n (listener as EventHandler)(...args);\n } catch (error) {\n console.error(`[KeyHandler] Error in global ${event} handler:`, error);\n }\n\n if (event === \"keypress\" || event === \"keyrelease\" || event === \"paste\") {\n const keyEvent = args[0];\n if (keyEvent.propagationStopped) {\n return hasGlobalListeners;\n }\n }\n }\n }\n\n const renderableSet = this.renderableHandlers.get(event);\n const renderableHandlers = renderableSet && renderableSet.size > 0 ? [...renderableSet] : [];\n let hasRenderableListeners = false;\n\n if (renderableSet && renderableSet.size > 0) {\n hasRenderableListeners = true;\n\n if (event === \"keypress\" || event === \"keyrelease\" || event === \"paste\") {\n const keyEvent = args[0];\n if (keyEvent.defaultPrevented) return hasGlobalListeners || hasRenderableListeners;\n if (keyEvent.propagationStopped) return hasGlobalListeners || hasRenderableListeners;\n }\n\n for (const handler of renderableHandlers) {\n try {\n (handler as EventHandler)(...args);\n } catch (error) {\n console.error(`[KeyHandler] Error in renderable ${event} handler:`, error);\n }\n\n if (event === \"keypress\" || event === \"keyrelease\" || event === \"paste\") {\n const keyEvent = args[0];\n if (keyEvent.propagationStopped) {\n return hasGlobalListeners || hasRenderableListeners;\n }\n }\n }\n }\n\n return hasGlobalListeners || hasRenderableListeners;\n }\n\n public onInternal<K extends keyof KeyHandlerEventMap>(\n event: K,\n handler: (...args: KeyHandlerEventMap[K]) => void,\n ): void {\n if (!this.renderableHandlers.has(event)) {\n this.renderableHandlers.set(event, new Set());\n }\n this.renderableHandlers.get(event)?.add(handler as EventHandler);\n }\n\n public offInternal<K extends keyof KeyHandlerEventMap>(\n event: K,\n handler: (...args: KeyHandlerEventMap[K]) => void,\n ): void {\n const handlers = this.renderableHandlers.get(event);\n if (handlers) {\n handlers.delete(handler as EventHandler);\n }\n }\n}\n","/**\n * Renderable-level keybinding utilities.\n *\n * Generic, framework-agnostic keybinding maps for renderables (Select,\n * TabSelect, etc.). The pattern is:\n *\n * 1. Define a set of default {@link KeyBinding}s mapping key presses to\n * renderable actions.\n * 2. Merge user-provided bindings over the defaults (user wins on key\n * collisions) with {@link mergeKeyBindings}.\n * 3. Build a lookup map with {@link buildKeyBindingsMap}, optionally\n * applying {@link KeyAliasMap} aliases (e.g. `enter` -> `return`).\n * 4. Resolve a parsed key event to an action with\n * {@link getKeyBindingAction}.\n *\n * `baseCode` (Kitty keyboard protocol) lets a binding match the physical\n * base-layout key even when the event arrives with an alternate-layout\n * character.\n */\n\nexport interface KeyBindingLike {\n name: string;\n ctrl?: boolean;\n shift?: boolean;\n meta?: boolean;\n super?: boolean;\n}\n\nexport interface KeyBinding<Action extends string = string> extends KeyBindingLike {\n action: Action;\n}\n\n/** The subset of {@link KeyEvent} used to resolve a keybinding. */\nexport type KeyBindingLookup = {\n name: string;\n ctrl?: boolean;\n shift?: boolean;\n meta?: boolean;\n super?: boolean;\n /** Kitty base-layout codepoint (e.g. 99 == \"c\"). */\n baseCode?: number;\n};\n\n/** Maps a normalized key name to another (e.g. `enter` -> `return`). */\nexport type KeyAliasMap = Record<string, string>;\n\nexport const defaultKeyAliases: KeyAliasMap = {\n enter: \"return\",\n esc: \"escape\",\n kp0: \"0\",\n kp1: \"1\",\n kp2: \"2\",\n kp3: \"3\",\n kp4: \"4\",\n kp5: \"5\",\n kp6: \"6\",\n kp7: \"7\",\n kp8: \"8\",\n kp9: \"9\",\n kpdecimal: \".\",\n kpdivide: \"/\",\n kpmultiply: \"*\",\n kpminus: \"-\",\n kpplus: \"+\",\n kpenter: \"enter\",\n kpequal: \"=\",\n kpseparator: \",\",\n kpleft: \"left\",\n kpright: \"right\",\n kpup: \"up\",\n kpdown: \"down\",\n kppageup: \"pageup\",\n kppagedown: \"pagedown\",\n kphome: \"home\",\n kpend: \"end\",\n kpinsert: \"insert\",\n kpdelete: \"delete\",\n};\n\nexport function mergeKeyAliases(defaults: KeyAliasMap, custom: KeyAliasMap): KeyAliasMap {\n return { ...defaults, ...custom };\n}\n\n/**\n * Merge custom bindings over defaults. When a custom binding targets the same\n * key/modifier combination as a default, the custom binding wins.\n */\nexport function mergeKeyBindings<Action extends string>(\n defaults: KeyBinding<Action>[],\n custom: KeyBinding<Action>[],\n): KeyBinding<Action>[] {\n const map = new Map<string, KeyBinding<Action>>();\n for (const binding of defaults) {\n const key = getKeyBindingKey(binding);\n map.set(key, binding);\n }\n for (const binding of custom) {\n const key = getKeyBindingKey(binding);\n map.set(key, binding);\n }\n return Array.from(map.values());\n}\n\nexport function getKeyBindingKey(binding: KeyBindingLike): string {\n return `${binding.name}:${binding.ctrl ? 1 : 0}:${binding.shift ? 1 : 0}:${binding.meta ? 1 : 0}:${binding.super ? 1 : 0}`;\n}\n\n// `baseCode` is Kitty's \"base layout codepoint\": the character for the same\n// physical key on the keyboard's base layout. Example: an event may arrive as\n// `name: \"ㅓ\", baseCode: 106`, where `106` is Unicode `j`. We normalize that\n// numeric codepoint to the key names we store in key maps so Ctrl+ㅓ can still\n// match a Ctrl+J binding.\nfunction getBaseCodeKeyName(baseCode: number | undefined): string | undefined {\n if (baseCode === undefined || baseCode < 32 || baseCode === 127) {\n return undefined;\n }\n\n try {\n const name = String.fromCodePoint(baseCode);\n\n if (name.length === 1 && name >= \"A\" && name <= \"Z\") {\n return name.toLowerCase();\n }\n\n return name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Return every lookup key that can represent this event. We try the parsed\n * name first, then the base-layout key when Kitty provides one. That keeps\n * direct character bindings precise and still lets physical-layout shortcuts\n * resolve.\n */\nexport function getKeyBindingKeys(binding: KeyBindingLookup): string[] {\n const names = new Set([binding.name]);\n const baseCodeName = getBaseCodeKeyName(binding.baseCode);\n\n if (baseCodeName) {\n names.add(baseCodeName);\n }\n\n return [...names].map((name) => getKeyBindingKey({ ...binding, name }));\n}\n\nexport function getKeyBindingAction<Action extends string>(\n map: Map<string, Action>,\n binding: KeyBindingLookup,\n): Action | undefined {\n for (const key of getKeyBindingKeys(binding)) {\n const action = map.get(key);\n\n if (action !== undefined) {\n return action;\n }\n }\n\n return undefined;\n}\n\nexport function matchesKeyBinding(binding: KeyBindingLookup, match: KeyBindingLike): boolean {\n const matchKey = getKeyBindingKey(match);\n\n return getKeyBindingKeys(binding).includes(matchKey);\n}\n\nexport function buildKeyBindingsMap<Action extends string>(\n bindings: KeyBinding<Action>[],\n aliasMap?: KeyAliasMap,\n): Map<string, Action> {\n const map = new Map<string, Action>();\n const aliases = aliasMap || {};\n\n for (const binding of bindings) {\n const key = getKeyBindingKey(binding);\n map.set(key, binding.action);\n }\n\n // Add aliased versions of all bindings\n for (const binding of bindings) {\n const normalizedName = aliases[binding.name] || binding.name;\n if (normalizedName !== binding.name) {\n const aliasedKey = getKeyBindingKey({ ...binding, name: normalizedName });\n map.set(aliasedKey, binding.action);\n }\n }\n\n return map;\n}\n\n/**\n * Converts a key binding to a human-readable string representation.\n * @example keyBindingToString({ name: \"c\", ctrl: true }) // \"ctrl+c\"\n */\nexport function keyBindingToString<Action extends string>(binding: KeyBinding<Action>): string {\n const parts: string[] = [];\n\n if (binding.ctrl) parts.push(\"ctrl\");\n if (binding.shift) parts.push(\"shift\");\n if (binding.meta) parts.push(\"meta\");\n if (binding.super) parts.push(\"super\");\n\n parts.push(binding.name);\n\n return parts.join(\"+\");\n}\n","// Byte-level stdin parser that turns raw terminal input into typed StdinEvents.\n//\n// This replaces a two-phase token -> decode pipeline with a single state machine\n// that produces fully typed events (key, mouse, paste, response) directly from\n// bytes. The parser owns all byte framing and protocol recognition. It does NOT\n// own event dispatch — that belongs to KeyHandler and the renderer.\n\nimport { Buffer } from \"node:buffer\";\nimport { type Clock, SystemClock, type TimerHandle } from \"./clock\";\nimport { parseKeypress } from \"./parseKeypress\";\nimport type { ParsedKey } from \"./parseKeypress\";\nimport { MouseParser, type RawMouseEvent } from \"./parseMouse\";\n\nexport { SystemClock, type Clock, type TimerHandle } from \"./clock\";\n\nexport type StdinResponseProtocol = \"csi\" | \"cpr\" | \"osc\" | \"dcs\" | \"apc\" | \"unknown\";\n\nexport type PasteMetadata = Record<string, never>;\n\n// The four event types the parser produces. Everything stdin sends becomes\n// exactly one of these.\nexport type StdinEvent =\n | {\n type: \"key\";\n raw: string;\n key: ParsedKey;\n }\n | {\n type: \"mouse\";\n raw: string;\n encoding: \"sgr\" | \"x10\";\n event: RawMouseEvent;\n }\n | {\n type: \"paste\";\n bytes: Uint8Array;\n metadata?: PasteMetadata;\n }\n | {\n type: \"response\";\n protocol: StdinResponseProtocol;\n sequence: string;\n };\n\nexport interface StdinParserProtocolContext {\n kittyKeyboardEnabled: boolean;\n privateCapabilityRepliesActive: boolean;\n pixelResolutionQueryActive: boolean;\n explicitWidthCprActive: boolean;\n startupCursorCprActive: boolean;\n}\n\nexport interface StdinParserOptions {\n timeoutMs?: number;\n maxPendingBytes?: number;\n armTimeouts?: boolean;\n onTimeoutFlush?: () => void;\n useKittyKeyboard?: boolean;\n protocolContext?: Partial<StdinParserProtocolContext>;\n clock?: Clock;\n}\n\n// State machine tags for the byte scanner.\ntype ParserState =\n | { tag: \"ground\" }\n | { tag: \"utf8\"; expected: number; seen: number }\n | { tag: \"esc\" }\n | { tag: \"ss3\" }\n | { tag: \"csi\" }\n | { tag: \"csi_sgr_mouse\"; part: number; hasDigit: boolean }\n | { tag: \"csi_sgr_mouse_deferred\"; part: number; hasDigit: boolean }\n | {\n tag: \"csi_parametric\";\n semicolons: number;\n segments: number;\n hasDigit: boolean;\n firstParamValue: number | null;\n }\n | {\n tag: \"csi_parametric_deferred\";\n semicolons: number;\n segments: number;\n hasDigit: boolean;\n firstParamValue: number | null;\n }\n | {\n tag: \"csi_parametric_ignored\";\n semicolons: number;\n segments: number;\n hasDigit: boolean;\n firstParamValue: number | null;\n }\n | { tag: \"csi_private_reply\"; semicolons: number; hasDigit: boolean; sawDollar: boolean }\n | { tag: \"csi_private_reply_deferred\"; semicolons: number; hasDigit: boolean; sawDollar: boolean }\n | { tag: \"osc\"; sawEsc: boolean }\n | { tag: \"dcs\"; sawEsc: boolean }\n | { tag: \"apc\"; sawEsc: boolean }\n | { tag: \"esc_recovery\" }\n | { tag: \"esc_less_mouse\" }\n | { tag: \"esc_less_x10_mouse\" };\n\ninterface PasteCollector {\n tail: Uint8Array;\n parts: Uint8Array[];\n totalLength: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 20;\nconst DEFAULT_MAX_PENDING_BYTES = 64 * 1024;\nconst INITIAL_PENDING_CAPACITY = 256;\nconst ESC = 0x1b;\nconst BEL = 0x07;\nconst BRACKETED_PASTE_START = Buffer.from(\"\\x1b[200~\");\nconst BRACKETED_PASTE_END = Buffer.from(\"\\x1b[201~\");\nconst EMPTY_BYTES = new Uint8Array(0);\nconst KEY_DECODER = new TextDecoder();\nconst DEFAULT_PROTOCOL_CONTEXT: StdinParserProtocolContext = {\n kittyKeyboardEnabled: false,\n privateCapabilityRepliesActive: false,\n pixelResolutionQueryActive: false,\n explicitWidthCprActive: false,\n startupCursorCprActive: false,\n};\n\nconst RXVT_DOLLAR_CSI_RE = new RegExp(`^${ESC}\\\\[\\\\d+\\\\$$`);\nconst SYSTEM_CLOCK = new SystemClock();\n\nclass ByteQueue {\n private buf: Uint8Array;\n private start = 0;\n private end = 0;\n\n constructor(capacity = INITIAL_PENDING_CAPACITY) {\n this.buf = new Uint8Array(capacity);\n }\n\n get length(): number {\n return this.end - this.start;\n }\n\n get capacity(): number {\n return this.buf.length;\n }\n\n view(): Uint8Array {\n return this.buf.subarray(this.start, this.end);\n }\n\n take(): Uint8Array {\n const chunk = this.view();\n this.start = 0;\n this.end = 0;\n return chunk;\n }\n\n append(chunk: Uint8Array): void {\n if (chunk.length === 0) {\n return;\n }\n\n this.ensureCapacity(this.length + chunk.length);\n this.buf.set(chunk, this.end);\n this.end += chunk.length;\n }\n\n consume(count: number): void {\n if (count <= 0) {\n return;\n }\n\n if (count >= this.length) {\n this.start = 0;\n this.end = 0;\n return;\n }\n\n this.start += count;\n if (this.start >= this.buf.length / 2) {\n this.buf.copyWithin(0, this.start, this.end);\n this.end -= this.start;\n this.start = 0;\n }\n }\n\n clear(): void {\n this.start = 0;\n this.end = 0;\n }\n\n reset(capacity = INITIAL_PENDING_CAPACITY): void {\n this.buf = new Uint8Array(capacity);\n this.start = 0;\n this.end = 0;\n }\n\n private ensureCapacity(requiredLength: number): void {\n const currentLength = this.length;\n if (requiredLength <= this.buf.length) {\n const availableAtEnd = this.buf.length - this.end;\n if (availableAtEnd >= requiredLength - currentLength) {\n return;\n }\n\n this.buf.copyWithin(0, this.start, this.end);\n this.end = currentLength;\n this.start = 0;\n if (requiredLength <= this.buf.length) {\n return;\n }\n }\n\n let nextCapacity = this.buf.length;\n while (nextCapacity < requiredLength) {\n nextCapacity *= 2;\n }\n\n const next = new Uint8Array(nextCapacity);\n next.set(this.view(), 0);\n this.buf = next;\n this.start = 0;\n this.end = currentLength;\n }\n}\n\nfunction normalizePositiveOption(value: number | undefined, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n return fallback;\n }\n return Math.floor(value);\n}\n\nfunction utf8SequenceLength(first: number): number {\n if (first < 0x80) return 1;\n if (first >= 0xc2 && first <= 0xdf) return 2;\n if (first >= 0xe0 && first <= 0xef) return 3;\n if (first >= 0xf0 && first <= 0xf4) return 4;\n return 0;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) return false;\n }\n return true;\n}\n\nfunction isMouseSgrSequence(sequence: Uint8Array): boolean {\n if (sequence.length < 7) return false;\n if (sequence[0] !== ESC || sequence[1] !== 0x5b || sequence[2] !== 0x3c) return false;\n\n const final = sequence[sequence.length - 1];\n if (final !== 0x4d && final !== 0x6d) return false;\n\n let part = 0;\n let hasDigit = false;\n for (let index = 3; index < sequence.length - 1; index += 1) {\n const byte = sequence[index];\n if (byte === undefined) return false;\n\n if (byte >= 0x30 && byte <= 0x39) {\n hasDigit = true;\n continue;\n }\n if (byte === 0x3b && hasDigit && part < 2) {\n part += 1;\n hasDigit = false;\n continue;\n }\n return false;\n }\n return part === 2 && hasDigit;\n}\n\nfunction isAsciiDigit(byte: number): boolean {\n return byte >= 0x30 && byte <= 0x39;\n}\n\ninterface ParametricCsiLike {\n semicolons: number;\n segments: number;\n hasDigit: boolean;\n firstParamValue: number | null;\n}\n\ninterface PrivateReplyCsiLike {\n semicolons: number;\n hasDigit: boolean;\n sawDollar: boolean;\n}\n\nfunction parsePositiveDecimalPrefix(\n sequence: Uint8Array,\n start: number,\n endExclusive: number,\n): number | null {\n if (start >= endExclusive) return null;\n\n let value = 0;\n let sawDigit = false;\n for (let index = start; index < endExclusive; index += 1) {\n const byte = sequence[index];\n if (byte === undefined || !isAsciiDigit(byte)) return null;\n sawDigit = true;\n value = value * 10 + (byte - 0x30);\n }\n\n return sawDigit ? value : null;\n}\n\nfunction parseKittyFirstFieldCodepoint(\n sequence: Uint8Array,\n start: number,\n endExclusive: number,\n): number | null {\n if (start >= endExclusive) return null;\n\n let firstColon = -1;\n for (let index = start; index < endExclusive; index += 1) {\n if (sequence[index] === 0x3a) {\n firstColon = index;\n break;\n }\n }\n\n if (firstColon === -1) return null;\n\n const codepoint = parsePositiveDecimalPrefix(sequence, start, firstColon);\n if (codepoint === null) return null;\n\n for (let index = firstColon + 1; index < endExclusive; index += 1) {\n const byte = sequence[index];\n if (byte !== 0x3a && byte !== undefined && !isAsciiDigit(byte)) return null;\n }\n\n return codepoint;\n}\n\nfunction canStillBeKittyU(state: ParametricCsiLike): boolean {\n return state.semicolons >= 1;\n}\n\nfunction canStillBeKittySpecial(state: ParametricCsiLike): boolean {\n return state.semicolons === 1 && state.segments > 1;\n}\n\nfunction canStillBeExplicitWidthCpr(state: ParametricCsiLike): boolean {\n return state.firstParamValue === 1 && state.semicolons === 1;\n}\n\nfunction canStillBeStartupCursorCpr(state: ParametricCsiLike): boolean {\n return state.semicolons === 1;\n}\n\nfunction canStillBeStartupCursorCprPrefix(state: ParametricCsiLike): boolean {\n return state.segments === 1 && state.semicolons <= 1;\n}\n\nfunction canStillBePixelResolution(state: ParametricCsiLike): boolean {\n return state.firstParamValue === 4 && state.semicolons === 2;\n}\n\nfunction canDeferParametricCsi(\n state: ParametricCsiLike,\n context: StdinParserProtocolContext,\n): boolean {\n return (\n (context.kittyKeyboardEnabled && (canStillBeKittyU(state) || canStillBeKittySpecial(state))) ||\n (context.explicitWidthCprActive && canStillBeExplicitWidthCpr(state)) ||\n (context.startupCursorCprActive && canStillBeStartupCursorCpr(state)) ||\n (context.pixelResolutionQueryActive && canStillBePixelResolution(state))\n );\n}\n\nfunction canCompleteDeferredParametricCsi(\n state: ParametricCsiLike,\n byte: number,\n context: StdinParserProtocolContext,\n): boolean {\n if (context.kittyKeyboardEnabled) {\n if (state.hasDigit && byte === 0x75) return true;\n if (\n state.hasDigit &&\n state.semicolons === 1 &&\n state.segments > 1 &&\n (byte === 0x7e || (byte >= 0x41 && byte <= 0x5a))\n ) {\n return true;\n }\n }\n\n if (\n context.explicitWidthCprActive &&\n state.hasDigit &&\n state.firstParamValue === 1 &&\n state.semicolons === 1 &&\n byte === 0x52\n ) {\n return true;\n }\n\n if (context.startupCursorCprActive && state.hasDigit && state.semicolons === 1 && byte === 0x52) {\n return true;\n }\n\n if (\n context.pixelResolutionQueryActive &&\n state.hasDigit &&\n state.firstParamValue === 4 &&\n state.semicolons === 2 &&\n byte === 0x74\n ) {\n return true;\n }\n\n return false;\n}\n\nfunction classifyParametricCsiProtocol(\n state: ParametricCsiLike,\n finalByte: number,\n): StdinResponseProtocol {\n if (finalByte === 0x52 && state.semicolons === 1 && state.segments === 1 && state.hasDigit) {\n return \"cpr\";\n }\n return \"csi\";\n}\n\nfunction canDeferPrivateReplyCsi(context: StdinParserProtocolContext): boolean {\n return context.privateCapabilityRepliesActive;\n}\n\nfunction canCompleteDeferredPrivateReplyCsi(\n state: PrivateReplyCsiLike,\n byte: number,\n context: StdinParserProtocolContext,\n): boolean {\n if (!context.privateCapabilityRepliesActive) return false;\n if (state.sawDollar) return state.hasDigit && byte === 0x79;\n if (byte === 0x63) return state.hasDigit || state.semicolons > 0;\n if (byte === 0x6e) return state.hasDigit;\n return state.hasDigit && byte === 0x75;\n}\n\nfunction withEscPrefix(bytes: Uint8Array): Uint8Array {\n const prefixed = new Uint8Array(bytes.length + 1);\n prefixed[0] = ESC;\n prefixed.set(bytes, 1);\n return prefixed;\n}\n\nfunction indexOfBytes(haystack: Uint8Array, needle: Uint8Array): number {\n if (needle.length === 0) return 0;\n const limit = haystack.length - needle.length;\n for (let offset = 0; offset <= limit; offset += 1) {\n let matched = true;\n for (let index = 0; index < needle.length; index += 1) {\n if (haystack[offset + index] !== needle[index]) {\n matched = false;\n break;\n }\n }\n if (matched) return offset;\n }\n return -1;\n}\n\nfunction decodeLatin1(bytes: Uint8Array): string {\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"latin1\");\n}\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n return KEY_DECODER.decode(bytes);\n}\n\nfunction createPasteCollector(): PasteCollector {\n return {\n tail: EMPTY_BYTES,\n parts: [],\n totalLength: 0,\n };\n}\n\nfunction joinPasteBytes(parts: Uint8Array[], totalLength: number): Uint8Array {\n if (totalLength === 0) return EMPTY_BYTES;\n if (parts.length === 1 && parts[0]) return parts[0];\n const bytes = new Uint8Array(totalLength);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.length;\n }\n return bytes;\n}\n\nexport class StdinParser {\n private readonly pending = new ByteQueue(INITIAL_PENDING_CAPACITY);\n private readonly events: StdinEvent[] = [];\n private readonly timeoutMs: number;\n private readonly maxPendingBytes: number;\n private readonly armTimeouts: boolean;\n private readonly onTimeoutFlush: (() => void) | null;\n private readonly useKittyKeyboard: boolean;\n private readonly mouseParser = new MouseParser();\n private readonly clock: Clock;\n private protocolContext: StdinParserProtocolContext;\n private timeoutId: TimerHandle | null = null;\n private destroyed = false;\n private pendingSinceMs: number | null = null;\n private forceFlush = false;\n private justFlushedEsc = false;\n private state: ParserState = { tag: \"ground\" };\n private cursor = 0;\n private unitStart = 0;\n private paste: PasteCollector | null = null;\n\n constructor(options: StdinParserOptions = {}) {\n this.timeoutMs = normalizePositiveOption(options.timeoutMs, DEFAULT_TIMEOUT_MS);\n this.maxPendingBytes = normalizePositiveOption(\n options.maxPendingBytes,\n DEFAULT_MAX_PENDING_BYTES,\n );\n this.armTimeouts = options.armTimeouts ?? true;\n this.onTimeoutFlush = options.onTimeoutFlush ?? null;\n this.useKittyKeyboard = options.useKittyKeyboard ?? true;\n this.clock = options.clock ?? SYSTEM_CLOCK;\n this.protocolContext = {\n ...DEFAULT_PROTOCOL_CONTEXT,\n kittyKeyboardEnabled: options.protocolContext?.kittyKeyboardEnabled ?? false,\n privateCapabilityRepliesActive:\n options.protocolContext?.privateCapabilityRepliesActive ?? false,\n pixelResolutionQueryActive: options.protocolContext?.pixelResolutionQueryActive ?? false,\n explicitWidthCprActive: options.protocolContext?.explicitWidthCprActive ?? false,\n startupCursorCprActive: options.protocolContext?.startupCursorCprActive ?? false,\n };\n }\n\n public get bufferCapacity(): number {\n return this.pending.capacity;\n }\n\n public updateProtocolContext(patch: Partial<StdinParserProtocolContext>): void {\n this.ensureAlive();\n this.protocolContext = { ...this.protocolContext, ...patch };\n this.reconcileDeferredStateWithProtocolContext();\n this.reconcileTimeoutState();\n }\n\n private getAbortableStartupCursorCprState(): Extract<\n ParserState,\n { tag: \"csi_parametric_ignored\" }\n > | null {\n if (this.pending.length === 0) return null;\n\n switch (this.state.tag) {\n case \"csi\": {\n const bytes = this.pending.view();\n const firstParamStart = this.unitStart + 2;\n if (this.cursor < firstParamStart) return null;\n\n let firstParamValue: number | null = null;\n for (let index = firstParamStart; index < this.cursor; index += 1) {\n const byte = bytes[index];\n if (byte === undefined || !isAsciiDigit(byte)) return null;\n firstParamValue = (firstParamValue ?? 0) * 10 + (byte - 0x30);\n }\n\n return {\n tag: \"csi_parametric_ignored\",\n semicolons: 0,\n segments: 1,\n hasDigit: this.cursor > firstParamStart,\n firstParamValue,\n };\n }\n case \"csi_parametric\":\n case \"csi_parametric_deferred\":\n if (\n !canStillBeStartupCursorCprPrefix(this.state) ||\n (this.protocolContext.explicitWidthCprActive && canStillBeExplicitWidthCpr(this.state))\n ) {\n return null;\n }\n return {\n tag: \"csi_parametric_ignored\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: this.state.hasDigit,\n firstParamValue: this.state.firstParamValue,\n };\n }\n return null;\n }\n\n public abortPendingStartupCursorCpr(): void {\n this.ensureAlive();\n const nextState = this.getAbortableStartupCursorCprState();\n if (!nextState) return;\n\n this.state = nextState;\n if (this.pendingSinceMs === null) {\n this.markPending();\n }\n this.forceFlush = false;\n this.reconcileTimeoutState();\n }\n\n public push(data: Uint8Array): void {\n this.ensureAlive();\n if (data.length === 0) {\n this.emitKeyOrResponse(\"unknown\", \"\");\n return;\n }\n\n let remainder = data;\n while (remainder.length > 0) {\n if (this.paste) {\n remainder = this.consumePasteBytes(remainder);\n continue;\n }\n\n const immediatePasteStartIndex =\n this.state.tag === \"ground\" && this.pending.length === 0\n ? indexOfBytes(remainder, BRACKETED_PASTE_START)\n : -1;\n const appendEnd =\n immediatePasteStartIndex === -1\n ? remainder.length\n : immediatePasteStartIndex + BRACKETED_PASTE_START.length;\n\n this.pending.append(remainder.subarray(0, appendEnd));\n remainder = remainder.subarray(appendEnd);\n this.scanPending();\n\n if (this.paste && this.pending.length > 0) {\n remainder = this.consumePasteBytes(this.takePendingBytes());\n continue;\n }\n\n if (!this.paste && this.pending.length > this.maxPendingBytes) {\n this.flushPendingOverflow();\n this.scanPending();\n\n if (this.paste && this.pending.length > 0) {\n remainder = this.consumePasteBytes(this.takePendingBytes());\n }\n }\n }\n this.reconcileTimeoutState();\n }\n\n public read(): StdinEvent | null {\n this.ensureAlive();\n if (this.events.length === 0 && this.forceFlush) {\n this.scanPending();\n this.reconcileTimeoutState();\n }\n return this.events.shift() ?? null;\n }\n\n public drain(onEvent: (event: StdinEvent) => void): void {\n this.ensureAlive();\n while (true) {\n if (this.destroyed) return;\n const event = this.read();\n if (!event) return;\n onEvent(event);\n }\n }\n\n public flushTimeout(nowMsValue: number = this.clock.now()): void {\n this.ensureAlive();\n if (\n this.pendingSinceMs !== null &&\n (nowMsValue < this.pendingSinceMs || nowMsValue - this.pendingSinceMs < this.timeoutMs)\n ) {\n return;\n }\n this.tryForceFlush();\n }\n\n private tryForceFlush(): void {\n if (this.paste || this.pendingSinceMs === null || this.pending.length === 0) return;\n this.forceFlush = true;\n }\n\n public reset(): void {\n if (this.destroyed) return;\n this.clearTimeout();\n this.resetState();\n }\n\n public resetMouseState(): void {\n this.ensureAlive();\n this.mouseParser.reset();\n }\n\n public destroy(): void {\n if (this.destroyed) return;\n this.clearTimeout();\n this.destroyed = true;\n this.resetState();\n }\n\n private ensureAlive(): void {\n if (this.destroyed) throw new Error(\"StdinParser has been destroyed\");\n }\n\n private scanPending(): void {\n while (!this.paste) {\n const bytes = this.pending.view();\n if (this.state.tag === \"ground\" && this.cursor >= bytes.length) {\n this.pending.clear();\n this.cursor = 0;\n this.unitStart = 0;\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n const byte = this.cursor < bytes.length ? (bytes[this.cursor] ?? -1) : -1;\n switch (this.state.tag) {\n case \"ground\": {\n this.unitStart = this.cursor;\n\n if (this.justFlushedEsc) {\n if (byte === 0x5b) {\n this.justFlushedEsc = false;\n this.cursor += 1;\n this.state = { tag: \"esc_recovery\" };\n continue;\n }\n this.justFlushedEsc = false;\n }\n\n if (byte === ESC) {\n this.cursor += 1;\n this.state = { tag: \"esc\" };\n continue;\n }\n\n if (byte < 0x80) {\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.cursor, this.cursor + 1)),\n );\n this.consumePrefix(this.cursor + 1);\n continue;\n }\n\n const expected = utf8SequenceLength(byte);\n if (expected === 0) {\n if (!this.forceFlush && this.cursor + 1 === bytes.length) {\n this.markPending();\n return;\n }\n this.emitLegacyHighByte(byte);\n this.consumePrefix(this.cursor + 1);\n continue;\n }\n\n this.cursor += 1;\n this.state = { tag: \"utf8\", expected, seen: 1 };\n continue;\n }\n\n case \"utf8\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitLegacyHighByte(bytes[this.unitStart] ?? 0);\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.unitStart + 1);\n continue;\n }\n\n if ((byte & 0xc0) !== 0x80) {\n this.emitLegacyHighByte(bytes[this.unitStart] ?? 0);\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.unitStart + 1);\n continue;\n }\n\n const nextSeen = this.state.seen + 1;\n this.cursor += 1;\n if (nextSeen < this.state.expected) {\n this.state = { tag: \"utf8\", expected: this.state.expected, seen: nextSeen };\n continue;\n }\n\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"esc\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n const flushedLoneEsc =\n this.cursor === this.unitStart + 1 && bytes[this.unitStart] === ESC;\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.justFlushedEsc = flushedLoneEsc;\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n switch (byte) {\n case 0x5b:\n this.cursor += 1;\n this.state = { tag: \"csi\" };\n continue;\n case 0x4f:\n this.cursor += 1;\n this.state = { tag: \"ss3\" };\n continue;\n case 0x5d:\n this.cursor += 1;\n this.state = { tag: \"osc\", sawEsc: false };\n continue;\n case 0x50:\n this.cursor += 1;\n this.state = { tag: \"dcs\", sawEsc: false };\n continue;\n case 0x5f:\n this.cursor += 1;\n this.state = { tag: \"apc\", sawEsc: false };\n continue;\n case ESC:\n this.cursor += 1;\n continue;\n default:\n this.cursor += 1;\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n }\n\n case \"ss3\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n this.cursor += 1;\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"esc_recovery\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === 0x3c) {\n this.cursor += 1;\n this.state = { tag: \"esc_less_mouse\" };\n continue;\n }\n\n if (byte === 0x4d) {\n this.cursor += 1;\n this.state = { tag: \"esc_less_x10_mouse\" };\n continue;\n }\n\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.unitStart + 1)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.unitStart + 1);\n continue;\n }\n\n case \"csi\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === 0x4d && this.cursor === this.unitStart + 2) {\n const end = this.cursor + 4;\n if (bytes.length < end) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, bytes.length));\n this.state = { tag: \"ground\" };\n this.consumePrefix(bytes.length);\n continue;\n }\n this.emitMouse(bytes.subarray(this.unitStart, end), \"x10\");\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n if (byte === 0x24) {\n const candidateEnd = this.cursor + 1;\n const candidate = decodeUtf8(bytes.subarray(this.unitStart, candidateEnd));\n if (RXVT_DOLLAR_CSI_RE.test(candidate)) {\n this.emitKeyOrResponse(\"csi\", candidate);\n this.state = { tag: \"ground\" };\n this.consumePrefix(candidateEnd);\n continue;\n }\n if (!this.forceFlush && candidateEnd >= bytes.length) {\n this.markPending();\n return;\n }\n }\n\n if (byte === 0x3c && this.cursor === this.unitStart + 2) {\n this.cursor += 1;\n this.state = { tag: \"csi_sgr_mouse\", part: 0, hasDigit: false };\n continue;\n }\n\n if (byte === 0x5b && this.cursor === this.unitStart + 2) {\n this.cursor += 1;\n continue;\n }\n\n if (byte === 0x3f && this.cursor === this.unitStart + 2) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: 0,\n hasDigit: false,\n sawDollar: false,\n };\n continue;\n }\n\n if (byte === 0x3b) {\n const firstParamStart = this.unitStart + 2;\n const firstParamEnd = this.cursor;\n let firstParamValue = parsePositiveDecimalPrefix(bytes, firstParamStart, firstParamEnd);\n\n if (firstParamValue === null && this.protocolContext.kittyKeyboardEnabled) {\n firstParamValue = parseKittyFirstFieldCodepoint(\n bytes,\n firstParamStart,\n firstParamEnd,\n );\n }\n\n if (firstParamValue !== null) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric\",\n semicolons: 1,\n segments: 1,\n hasDigit: false,\n firstParamValue,\n };\n continue;\n }\n }\n\n if (byte >= 0x40 && byte <= 0x7e) {\n const end = this.cursor + 1;\n const rawBytes = bytes.subarray(this.unitStart, end);\n\n if (bytesEqual(rawBytes, BRACKETED_PASTE_START)) {\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n this.paste = createPasteCollector();\n continue;\n }\n\n if (isMouseSgrSequence(rawBytes)) {\n this.emitMouse(rawBytes, \"sgr\");\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.emitKeyOrResponse(\"csi\", decodeUtf8(rawBytes));\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.cursor += 1;\n continue;\n }\n\n case \"csi_sgr_mouse\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.state = {\n tag: \"csi_sgr_mouse_deferred\",\n part: this.state.part,\n hasDigit: this.state.hasDigit,\n };\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte)) {\n this.cursor += 1;\n this.state = { tag: \"csi_sgr_mouse\", part: this.state.part, hasDigit: true };\n continue;\n }\n\n if (byte === 0x3b && this.state.hasDigit && this.state.part < 2) {\n this.cursor += 1;\n this.state = { tag: \"csi_sgr_mouse\", part: this.state.part + 1, hasDigit: false };\n continue;\n }\n\n if (byte >= 0x40 && byte <= 0x7e) {\n const end = this.cursor + 1;\n const rawBytes = bytes.subarray(this.unitStart, end);\n if (isMouseSgrSequence(rawBytes)) {\n this.emitMouse(rawBytes, \"sgr\");\n } else {\n this.emitKeyOrResponse(\"csi\", decodeUtf8(rawBytes));\n }\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.state = { tag: \"csi\" };\n continue;\n }\n\n case \"csi_sgr_mouse_deferred\": {\n if (this.cursor >= bytes.length) {\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte) || byte === 0x3b || byte === 0x4d || byte === 0x6d) {\n this.state = {\n tag: \"csi_sgr_mouse\",\n part: this.state.part,\n hasDigit: this.state.hasDigit,\n };\n continue;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"csi_parametric\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n\n if (canDeferParametricCsi(this.state, this.protocolContext)) {\n this.state = {\n tag: \"csi_parametric_deferred\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: this.state.hasDigit,\n firstParamValue: this.state.firstParamValue,\n };\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte)) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: true,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n if (byte === 0x3a && this.state.hasDigit && this.state.segments < 3) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric\",\n semicolons: this.state.semicolons,\n segments: this.state.segments + 1,\n hasDigit: false,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n if (byte === 0x3b && this.state.semicolons < 2) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric\",\n semicolons: this.state.semicolons + 1,\n segments: 1,\n hasDigit: false,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n if (byte >= 0x40 && byte <= 0x7e) {\n const end = this.cursor + 1;\n const protocol = classifyParametricCsiProtocol(this.state, byte);\n this.emitKeyOrResponse(protocol, decodeUtf8(bytes.subarray(this.unitStart, end)));\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.state = { tag: \"csi\" };\n continue;\n }\n\n case \"csi_parametric_deferred\": {\n if (this.cursor >= bytes.length) {\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte) || byte === 0x3a || byte === 0x3b) {\n this.state = {\n tag: \"csi_parametric\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: this.state.hasDigit,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n if (canCompleteDeferredParametricCsi(this.state, byte, this.protocolContext)) {\n this.state = {\n tag: \"csi_parametric\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: this.state.hasDigit,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"csi_parametric_ignored\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte)) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric_ignored\",\n semicolons: this.state.semicolons,\n segments: this.state.segments,\n hasDigit: true,\n firstParamValue:\n this.state.semicolons === 0\n ? (this.state.firstParamValue ?? 0) * 10 + (byte - 0x30)\n : this.state.firstParamValue,\n };\n continue;\n }\n\n if (byte === 0x3b && this.state.semicolons === 0 && this.state.hasDigit) {\n if (this.protocolContext.explicitWidthCprActive && this.state.firstParamValue === 1) {\n this.state = { tag: \"csi\" };\n continue;\n }\n\n this.cursor += 1;\n this.state = {\n tag: \"csi_parametric_ignored\",\n semicolons: 1,\n segments: 1,\n hasDigit: false,\n firstParamValue: this.state.firstParamValue,\n };\n continue;\n }\n\n if (byte === 0x52 && this.state.semicolons === 1 && this.state.hasDigit) {\n const end = this.cursor + 1;\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n if (this.state.semicolons === 0) {\n this.state = { tag: \"csi\" };\n continue;\n }\n\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"csi_private_reply\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n\n if (canDeferPrivateReplyCsi(this.protocolContext)) {\n this.state = {\n tag: \"csi_private_reply_deferred\",\n semicolons: this.state.semicolons,\n hasDigit: this.state.hasDigit,\n sawDollar: this.state.sawDollar,\n };\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte)) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: this.state.semicolons,\n hasDigit: true,\n sawDollar: this.state.sawDollar,\n };\n continue;\n }\n\n if (byte === 0x3b) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: this.state.semicolons + 1,\n hasDigit: false,\n sawDollar: false,\n };\n continue;\n }\n\n if (byte === 0x24 && this.state.hasDigit && !this.state.sawDollar) {\n this.cursor += 1;\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: this.state.semicolons,\n hasDigit: true,\n sawDollar: true,\n };\n continue;\n }\n\n if (byte >= 0x40 && byte <= 0x7e) {\n const end = this.cursor + 1;\n this.emitOpaqueResponse(\"csi\", bytes.subarray(this.unitStart, end));\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.state = { tag: \"csi\" };\n continue;\n }\n\n case \"csi_private_reply_deferred\": {\n if (this.cursor >= bytes.length) {\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return;\n }\n\n if (byte === ESC) {\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (isAsciiDigit(byte) || byte === 0x3b || byte === 0x24) {\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: this.state.semicolons,\n hasDigit: this.state.hasDigit,\n sawDollar: this.state.sawDollar,\n };\n continue;\n }\n\n if (canCompleteDeferredPrivateReplyCsi(this.state, byte, this.protocolContext)) {\n this.state = {\n tag: \"csi_private_reply\",\n semicolons: this.state.semicolons,\n hasDigit: this.state.hasDigit,\n sawDollar: this.state.sawDollar,\n };\n continue;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n case \"osc\":\n case \"dcs\":\n case \"apc\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, this.cursor));\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === ESC) {\n this.cursor += 1;\n this.state = { tag: this.state.tag, sawEsc: true };\n continue;\n }\n\n if (this.state.sawEsc && byte === 0x5c) {\n const end = this.cursor + 1;\n this.emitOpaqueResponse(this.state.tag, bytes.subarray(this.unitStart, end));\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n if (this.state.tag === \"osc\" && byte === BEL) {\n const end = this.cursor + 1;\n this.emitOpaqueResponse(\"osc\", bytes.subarray(this.unitStart, end));\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n\n this.cursor += 1;\n this.state = { tag: this.state.tag, sawEsc: false };\n continue;\n }\n\n case \"esc_less_mouse\": {\n if (this.cursor >= bytes.length) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.cursor)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.cursor);\n continue;\n }\n\n if (byte === 0x4d || byte === 0x6d) {\n const end = this.cursor + 1;\n const fullBytes = withEscPrefix(bytes.subarray(this.unitStart, end));\n if (isMouseSgrSequence(fullBytes)) {\n this.emitMouse(fullBytes, \"sgr\");\n this.state = { tag: \"ground\" };\n this.consumePrefix(end);\n continue;\n }\n }\n\n this.emitKeyOrResponse(\n \"unknown\",\n decodeUtf8(bytes.subarray(this.unitStart, this.unitStart + 1)),\n );\n this.state = { tag: \"ground\" };\n this.consumePrefix(this.unitStart + 1);\n continue;\n }\n\n case \"esc_less_x10_mouse\": {\n const expectedEnd = this.unitStart + 4;\n if (bytes.length < expectedEnd) {\n if (!this.forceFlush) {\n this.markPending();\n return;\n }\n this.emitOpaqueResponse(\"unknown\", bytes.subarray(this.unitStart, bytes.length));\n this.state = { tag: \"ground\" };\n this.consumePrefix(bytes.length);\n continue;\n }\n\n this.emitMouse(withEscPrefix(bytes.subarray(this.unitStart, expectedEnd)), \"x10\");\n this.state = { tag: \"ground\" };\n this.consumePrefix(expectedEnd);\n continue;\n }\n }\n }\n }\n\n private consumePasteBytes(bytes: Uint8Array): Uint8Array {\n if (!this.paste) return bytes;\n\n const endIndex = indexOfBytes(bytes, BRACKETED_PASTE_END);\n if (endIndex !== -1) {\n const endLimit = endIndex + BRACKETED_PASTE_END.length;\n const bodyBytes = bytes.subarray(0, endIndex);\n\n this.paste.parts.push(bodyBytes);\n this.paste.totalLength += bodyBytes.length;\n\n this.events.push({\n type: \"paste\",\n bytes: joinPasteBytes(this.paste.parts, this.paste.totalLength),\n });\n\n this.paste = null;\n this.state = { tag: \"ground\" };\n return bytes.subarray(endLimit);\n }\n\n this.paste.parts.push(bytes);\n this.paste.totalLength += bytes.length;\n return EMPTY_BYTES;\n }\n\n private takePendingBytes(): Uint8Array {\n const bytes = this.pending.take();\n this.cursor = 0;\n this.unitStart = 0;\n this.pendingSinceMs = null;\n this.forceFlush = false;\n return bytes;\n }\n\n private flushPendingOverflow(): void {\n if (this.pending.length === 0) return;\n const bytes = this.takePendingBytes();\n this.emitOpaqueResponse(\"unknown\", bytes);\n }\n\n private emitLegacyHighByte(byte: number): void {\n const str = String.fromCharCode(byte);\n this.emitKeyOrResponse(\"unknown\", str);\n }\n\n private emitKeyOrResponse(protocol: StdinResponseProtocol, sequence: string): void {\n if (sequence === \"\") return;\n\n // \"unknown\" protocol: always attempt key parsing (original behaviour).\n if (protocol === \"unknown\") {\n const key = parseKeypress(sequence, { useKittyKeyboard: this.useKittyKeyboard });\n if (!key) {\n this.events.push({ type: \"response\", protocol: \"unknown\", sequence });\n return;\n }\n this.events.push({ type: \"key\", raw: sequence, key });\n return;\n }\n\n // \"csi\" protocol: covers plain CSI sequences such as arrow keys, F-keys,\n // Home/End/PageUp/PageDown, and modifier combos (e.g. \\x1b[1;5A).\n // Try key parsing first; only fall back to a response event when the\n // sequence is an unrecognised terminal capability reply (empty key name).\n if (protocol === \"csi\") {\n const key = parseKeypress(sequence, { useKittyKeyboard: this.useKittyKeyboard });\n if (key && key.name !== \"\") {\n this.events.push({ type: \"key\", raw: sequence, key });\n return;\n }\n // Unrecognised CSI: treat as a terminal response (capability reply etc.)\n this.events.push({ type: \"response\", protocol, sequence });\n return;\n }\n\n // All other protocols (cpr, osc, dcs, apc) are terminal responses.\n this.events.push({ type: \"response\", protocol, sequence });\n }\n\n private emitOpaqueResponse(protocol: StdinResponseProtocol, bytes: Uint8Array): void {\n this.events.push({ type: \"response\", protocol, sequence: decodeLatin1(bytes) });\n }\n\n private emitMouse(bytes: Uint8Array, encoding: \"sgr\" | \"x10\"): void {\n const event = this.mouseParser.parseMouseEvent(bytes);\n if (!event) return;\n this.events.push({\n type: \"mouse\",\n raw: decodeLatin1(bytes),\n encoding,\n event,\n });\n }\n\n private consumePrefix(endExclusive: number): void {\n this.pending.consume(endExclusive);\n this.cursor = 0;\n this.unitStart = 0;\n this.pendingSinceMs = null;\n this.forceFlush = false;\n }\n\n private markPending(): void {\n if (this.pendingSinceMs === null) {\n this.pendingSinceMs = this.clock.now();\n }\n }\n\n private resetState(): void {\n this.pending.reset();\n this.events.length = 0;\n this.pendingSinceMs = null;\n this.forceFlush = false;\n this.justFlushedEsc = false;\n this.state = { tag: \"ground\" };\n this.cursor = 0;\n this.unitStart = 0;\n this.paste = null;\n this.mouseParser.reset();\n }\n\n private reconcileDeferredStateWithProtocolContext(): void {\n if (this.state.tag === \"csi_parametric_deferred\") {\n if (!canDeferParametricCsi(this.state, this.protocolContext)) {\n this.forceFlush = true;\n }\n } else if (this.state.tag === \"csi_private_reply_deferred\") {\n if (!canDeferPrivateReplyCsi(this.protocolContext)) {\n this.forceFlush = true;\n }\n }\n }\n\n private reconcileTimeoutState(): void {\n if (!this.armTimeouts) return;\n\n const hasPendingTimeableData =\n this.pendingSinceMs !== null && !this.forceFlush && !this.paste && this.pending.length > 0;\n\n if (!hasPendingTimeableData) {\n this.clearTimeout();\n return;\n }\n\n if (this.timeoutId !== null) return;\n\n this.timeoutId = this.clock.setTimeout(() => {\n this.timeoutId = null;\n if (this.destroyed) return;\n this.tryForceFlush();\n if (this.onTimeoutFlush) {\n this.onTimeoutFlush();\n }\n }, this.timeoutMs);\n }\n\n private clearTimeout(): void {\n if (this.timeoutId !== null) {\n this.clock.clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n}\n","import { EventEmitter } from \"node:events\";\nimport { KeyEvent, PasteEvent } from \"./keyHandler\";\nimport type { RawMouseEvent } from \"./parseMouse\";\nimport { type StdinEvent, StdinParser } from \"./stdinParser\";\n\n/**\n * Events emitted by {@link KeyInput}. Mirrors the four kinds of `StdinEvent`\n * produced by the parser so that nothing read from stdin is silently dropped.\n *\n * Historical bug: `KeyInput.drain` previously handled only `type === \"key\"`\n * and discarded every `mouse` / `paste` / `response` event, which made mouse\n * input, bracketed paste, and terminal-capability replies unreachable from\n * the renderer.\n */\ntype KeyInputEvents = {\n keypress: [KeyEvent];\n keyrelease: [KeyEvent];\n mouse: [RawMouseEvent, string];\n paste: [PasteEvent];\n response: [string, string];\n};\n\nexport type { KeyInputEvents };\n\nexport class KeyInput extends EventEmitter<KeyInputEvents> {\n private stdinParser: StdinParser;\n private rawMode = false;\n private readonly onDataBound: (data: Buffer) => void;\n\n constructor() {\n super();\n this.stdinParser = new StdinParser({\n useKittyKeyboard: false,\n onTimeoutFlush: () => {\n this.drain();\n },\n });\n this.onDataBound = this.onData.bind(this);\n }\n\n start(): void {\n const stdin = process.stdin;\n if (stdin.setRawMode && !this.rawMode) {\n stdin.setRawMode(true);\n this.rawMode = true;\n }\n stdin.resume();\n stdin.on(\"data\", this.onDataBound);\n }\n\n stop(): void {\n process.stdin.off(\"data\", this.onDataBound);\n if (this.rawMode && process.stdin.setRawMode) {\n process.stdin.setRawMode(false);\n this.rawMode = false;\n }\n process.stdin.pause();\n this.stdinParser.reset();\n }\n\n private onData(data: Buffer): void {\n this.stdinParser.push(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n this.drain();\n }\n\n private drain(): void {\n this.stdinParser.drain((event: StdinEvent) => {\n switch (event.type) {\n case \"key\": {\n const key = new KeyEvent(event.key);\n if (event.key.eventType === \"release\") {\n this.emit(\"keyrelease\", key);\n } else {\n // Both \"press\" and \"repeat\" (normalized by the parser) surface as\n // a `keypress` event.\n this.emit(\"keypress\", key);\n }\n break;\n }\n case \"mouse\": {\n this.emit(\"mouse\", event.event, event.raw);\n break;\n }\n case \"paste\": {\n this.emit(\"paste\", new PasteEvent(event.bytes));\n break;\n }\n case \"response\": {\n this.emit(\"response\", event.protocol, event.sequence);\n break;\n }\n }\n });\n }\n}\n","/**\n * RGBA color class with static factory methods.\n */\n\n// Named CSS terminal colors\nconst NAMED_COLORS: Record<string, { r: number; g: number; b: number; a: number }> = {\n black: { r: 0, g: 0, b: 0, a: 255 },\n red: { r: 205, g: 49, b: 49, a: 255 },\n green: { r: 13, g: 188, b: 121, a: 255 },\n yellow: { r: 229, g: 229, b: 16, a: 255 },\n blue: { r: 36, g: 114, b: 200, a: 255 },\n magenta: { r: 188, g: 63, b: 188, a: 255 },\n cyan: { r: 17, g: 168, b: 205, a: 255 },\n white: { r: 229, g: 229, b: 229, a: 255 },\n brightblack: { r: 102, g: 102, b: 102, a: 255 },\n brightred: { r: 241, g: 76, b: 76, a: 255 },\n brightgreen: { r: 35, g: 209, b: 139, a: 255 },\n brightyellow: { r: 245, g: 245, b: 67, a: 255 },\n brightblue: { r: 59, g: 142, b: 234, a: 255 },\n brightmagenta: { r: 214, g: 112, b: 214, a: 255 },\n brightcyan: { r: 41, g: 184, b: 219, a: 255 },\n brightwhite: { r: 229, g: 229, b: 229, a: 255 },\n transparent: { r: 0, g: 0, b: 0, a: 0 },\n orange: { r: 255, g: 165, b: 0, a: 255 },\n gray: { r: 128, g: 128, b: 128, a: 255 },\n grey: { r: 128, g: 128, b: 128, a: 255 },\n darkgray: { r: 64, g: 64, b: 64, a: 255 },\n darkgrey: { r: 64, g: 64, b: 64, a: 255 },\n lightgray: { r: 192, g: 192, b: 192, a: 255 },\n lightgrey: { r: 192, g: 192, b: 192, a: 255 },\n pink: { r: 255, g: 192, b: 203, a: 255 },\n purple: { r: 128, g: 0, b: 128, a: 255 },\n violet: { r: 238, g: 130, b: 238, a: 255 },\n brown: { r: 165, g: 42, b: 42, a: 255 },\n gold: { r: 255, g: 215, b: 0, a: 255 },\n lime: { r: 0, g: 255, b: 0, a: 255 },\n navy: { r: 0, g: 0, b: 128, a: 255 },\n teal: { r: 0, g: 128, b: 128, a: 255 },\n silver: { r: 192, g: 192, b: 192, a: 255 },\n maroon: { r: 128, g: 0, b: 0, a: 255 },\n olive: { r: 128, g: 128, b: 0, a: 255 },\n aqua: { r: 0, g: 255, b: 255, a: 255 },\n fuchsia: { r: 255, g: 0, b: 255, a: 255 },\n coral: { r: 255, g: 127, b: 80, a: 255 },\n salmon: { r: 250, g: 128, b: 114, a: 255 },\n tomato: { r: 255, g: 99, b: 71, a: 255 },\n skyblue: { r: 135, g: 206, b: 235, a: 255 },\n turquoise: { r: 64, g: 224, b: 208, a: 255 },\n indigo: { r: 75, g: 0, b: 130, a: 255 },\n crimson: { r: 220, g: 20, b: 60, a: 255 },\n limegreen: { r: 50, g: 205, b: 50, a: 255 },\n forestgreen: { r: 34, g: 139, b: 34, a: 255 },\n darkorange: { r: 255, g: 140, b: 0, a: 255 },\n};\n\n/**\n * RGBA color type with static factory methods.\n * r, g, b, a are in 0-255 range.\n */\nexport type RGBA = {\n r: number;\n g: number;\n b: number;\n a: number;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace RGBA {\n /** Create RGBA from 0-255 integer components. */\n export function fromInts(r: number, g: number, b: number, a = 255): RGBA {\n return {\n r: Math.max(0, Math.min(255, Math.round(r))),\n g: Math.max(0, Math.min(255, Math.round(g))),\n b: Math.max(0, Math.min(255, Math.round(b))),\n a: Math.max(0, Math.min(255, Math.round(a))),\n };\n }\n\n /** Create RGBA from 0.0–1.0 float components. */\n export function fromValues(r: number, g: number, b: number, a = 1): RGBA {\n return fromInts(r * 255, g * 255, b * 255, a * 255);\n }\n\n /** Parse a CSS hex color string (#rgb, #rrggbb, #rrggbbaa). */\n export function fromHex(hex: string): RGBA {\n const h = hex.replace(\"#\", \"\");\n const p = (s: string) => Number.parseInt(s, 16) || 0;\n if (h.length === 3) {\n const r = h[0] ?? \"0\";\n const g = h[1] ?? \"0\";\n const b = h[2] ?? \"0\";\n return fromInts(p(r + r), p(g + g), p(b + b));\n }\n if (h.length === 6) {\n return fromInts(p(h.slice(0, 2)), p(h.slice(2, 4)), p(h.slice(4, 6)));\n }\n if (h.length === 8) {\n return fromInts(p(h.slice(0, 2)), p(h.slice(2, 4)), p(h.slice(4, 6)), p(h.slice(6, 8)));\n }\n return fromInts(0, 0, 0);\n }\n\n /** Transparent black. */\n export const transparent: RGBA = { r: 0, g: 0, b: 0, a: 0 };\n\n /** Convert to a #rrggbb hex string (ignores alpha). */\n export function toHex(rgba: RGBA): string {\n const hex = (n: number) =>\n Math.max(0, Math.min(255, Math.round(n)))\n .toString(16)\n .padStart(2, \"0\");\n return `#${hex(rgba.r)}${hex(rgba.g)}${hex(rgba.b)}`;\n }\n\n /** Convert to a #rrggbbaa hex string. */\n export function toHexAlpha(rgba: RGBA): string {\n const hex = (n: number) =>\n Math.max(0, Math.min(255, Math.round(n)))\n .toString(16)\n .padStart(2, \"0\");\n return `#${hex(rgba.r)}${hex(rgba.g)}${hex(rgba.b)}${hex(rgba.a)}`;\n }\n\n /** Convert to a CSS rgba() string. */\n export function toCSS(rgba: RGBA): string {\n const a = (rgba.a / 255).toFixed(3);\n return `rgba(${rgba.r},${rgba.g},${rgba.b},${a})`;\n }\n\n /** Get ANSI RGB components as \"r;g;b\" string. */\n export function toAnsiColor(rgba: RGBA): string {\n return `${rgba.r};${rgba.g};${rgba.b}`;\n }\n\n /** Check if RGBA is transparent (a === 0). */\n export function isTransparent(rgba: RGBA): boolean {\n return rgba.a === 0;\n }\n\n /** Check equality. */\n export function equals(a: RGBA, b: RGBA): boolean {\n return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;\n }\n\n /** Blend src over dst using normal alpha compositing. */\n export function blend(dst: RGBA, src: RGBA): RGBA {\n if (src.a === 255) return src;\n if (src.a === 0) return dst;\n const alpha = src.a / 255;\n const invAlpha = 1 - alpha;\n return fromInts(\n src.r * alpha + dst.r * invAlpha,\n src.g * alpha + dst.g * invAlpha,\n src.b * alpha + dst.b * invAlpha,\n 255,\n );\n }\n}\n\n/** A color input: hex string, named color string, or RGBA object. */\nexport type ColorInput = string | RGBA | null | undefined;\n\n/**\n * Parse any color input to RGBA.\n * Supports: hex strings (#rgb, #rrggbb, #rrggbbaa), named colors,\n * rgb()/rgba() strings, and RGBA objects.\n */\nexport function parseColor(input: ColorInput): RGBA {\n if (!input) return RGBA.transparent;\n if (typeof input === \"object\") return input;\n\n const s = input.trim();\n if (!s || s === \"transparent\") return RGBA.transparent;\n\n // Named color\n const named = NAMED_COLORS[s.toLowerCase()];\n if (named) return named;\n\n // Hex\n if (s.startsWith(\"#\")) return RGBA.fromHex(s);\n\n // rgb(r,g,b) or rgba(r,g,b,a)\n const rgbMatch = s.match(/^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/i);\n if (rgbMatch) {\n const r = Number.parseInt(rgbMatch[1] ?? \"0\", 10);\n const g = Number.parseInt(rgbMatch[2] ?? \"0\", 10);\n const b = Number.parseInt(rgbMatch[3] ?? \"0\", 10);\n const a = rgbMatch[4] !== undefined ? Math.round(Number.parseFloat(rgbMatch[4]) * 255) : 255;\n return RGBA.fromInts(r, g, b, a);\n }\n\n // Fallback: white\n return RGBA.fromInts(255, 255, 255);\n}\n\n/** Convert RGBA to a CSS color string suitable for the engine. */\nexport function rgbaToEngineColor(rgba: RGBA): string {\n if (rgba.a === 0) return \"transparent\";\n if (rgba.a === 255) return RGBA.toHex(rgba);\n return RGBA.toHexAlpha(rgba);\n}\n","/**\n * Styled text system for BetterTUI.\n * Provides a template literal tag `t` and style helpers for building\n * rich text with colors, bold, italic, and other attributes.\n */\n\nimport { type ColorInput, type RGBA, parseColor } from \"./rgba\";\n\n/** TextAttributes bitmask constants. */\nexport const TextAttributes = {\n NONE: 0,\n BOLD: 1,\n DIM: 2,\n ITALIC: 4,\n UNDERLINE: 8,\n BLINK: 16,\n INVERSE: 32,\n HIDDEN: 64,\n STRIKETHROUGH: 128,\n} as const;\n\nexport type TextAttributeFlag = (typeof TextAttributes)[keyof typeof TextAttributes];\n\n/** A single styled text chunk. */\nexport interface TextChunk {\n __isChunk: true;\n text: string;\n fg?: RGBA;\n bg?: RGBA;\n attributes?: number;\n link?: { url: string };\n}\n\nconst BrandedStyledText: unique symbol = Symbol.for(\"@bettertui/core/StyledText\");\n\n/** A rich text object made of styled chunks. */\nexport class StyledText {\n [BrandedStyledText] = true;\n public chunks: TextChunk[];\n\n constructor(chunks: TextChunk[]) {\n this.chunks = chunks;\n }\n}\n\n/** Type guard for StyledText. */\nexport function isStyledText(obj: unknown): obj is StyledText {\n return !!(obj as Record<symbol, unknown>)?.[BrandedStyledText];\n}\n\n/** Convert a plain string to a StyledText with one chunk. */\nexport function stringToStyledText(content: string): StyledText {\n return new StyledText([{ __isChunk: true, text: content }]);\n}\n\n/** A value that can be used in styled text. */\nexport type StylableInput = string | number | boolean | TextChunk;\n\ninterface StyleAttrs {\n fg?: ColorInput;\n bg?: ColorInput;\n attributes?: number;\n}\n\nfunction applyStyle(input: StylableInput, attrs: StyleAttrs): TextChunk {\n const fg = attrs.fg !== undefined ? parseColor(attrs.fg) : undefined;\n const bg = attrs.bg !== undefined ? parseColor(attrs.bg) : undefined;\n const newAttrs = attrs.attributes ?? 0;\n\n if (typeof input === \"object\" && \"__isChunk\" in (input as object)) {\n const existing = input as TextChunk;\n return {\n __isChunk: true,\n text: existing.text,\n fg: fg !== undefined ? fg : existing.fg,\n bg: bg !== undefined ? bg : existing.bg,\n attributes: newAttrs ? (existing.attributes ?? 0) | newAttrs : existing.attributes,\n link: existing.link,\n };\n }\n\n return {\n __isChunk: true,\n text: String(input),\n fg,\n bg,\n attributes: newAttrs || undefined,\n };\n}\n\n/**\n * Template literal tag for building styled text.\n *\n * @example\n * t`${bold(red(\"Error:\"))} Connection failed`\n */\nexport function t(strings: TemplateStringsArray, ...values: StylableInput[]): StyledText {\n const chunks: TextChunk[] = [];\n for (let i = 0; i < strings.length; i++) {\n const raw = strings[i];\n if (raw) chunks.push({ __isChunk: true, text: raw });\n const val = values[i];\n if (val !== undefined) {\n if (typeof val === \"object\" && \"__isChunk\" in (val as object)) {\n chunks.push(val as TextChunk);\n } else {\n chunks.push({ __isChunk: true, text: String(val) });\n }\n }\n }\n return new StyledText(chunks);\n}\n\n// ── Style attribute helpers ───────────────────────────────────────────────────\n\nexport const bold = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.BOLD });\nexport const italic = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.ITALIC });\nexport const underline = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.UNDERLINE });\nexport const strikethrough = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.STRIKETHROUGH });\nexport const dim = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.DIM });\nexport const reverse = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.INVERSE });\nexport const blink = (input: StylableInput): TextChunk =>\n applyStyle(input, { attributes: TextAttributes.BLINK });\n\n// ── Named foreground color helpers ───────────────────────────────────────────\n\nexport const black = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"black\" });\nexport const red = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"red\" });\nexport const green = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"green\" });\nexport const yellow = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"yellow\" });\nexport const blue = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"blue\" });\nexport const magenta = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"magenta\" });\nexport const cyan = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"cyan\" });\nexport const white = (input: StylableInput): TextChunk => applyStyle(input, { fg: \"white\" });\n\n// Bright variants\nexport const brightBlack = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightblack\" });\nexport const brightRed = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightred\" });\nexport const brightGreen = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightgreen\" });\nexport const brightYellow = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightyellow\" });\nexport const brightBlue = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightblue\" });\nexport const brightMagenta = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightmagenta\" });\nexport const brightCyan = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightcyan\" });\nexport const brightWhite = (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: \"brightwhite\" });\n\n// ── Named background color helpers ───────────────────────────────────────────\n\nexport const bgBlack = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"black\" });\nexport const bgRed = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"red\" });\nexport const bgGreen = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"green\" });\nexport const bgYellow = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"yellow\" });\nexport const bgBlue = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"blue\" });\nexport const bgMagenta = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"magenta\" });\nexport const bgCyan = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"cyan\" });\nexport const bgWhite = (input: StylableInput): TextChunk => applyStyle(input, { bg: \"white\" });\n\n// ── Curried custom-color helpers ──────────────────────────────────────────────\n\n/** Set foreground color. `fg(\"#ff0000\")(\"text\")` */\nexport const fg =\n (color: ColorInput) =>\n (input: StylableInput): TextChunk =>\n applyStyle(input, { fg: color });\n\n/** Set background color. `bg(\"#ff0000\")(\"text\")` */\nexport const bg =\n (color: ColorInput) =>\n (input: StylableInput): TextChunk =>\n applyStyle(input, { bg: color });\n\n/** Create a hyperlink. `link(\"https://example.com\")(\"click here\")` */\nexport const link =\n (url: string) =>\n (input: StylableInput): TextChunk => {\n const base =\n typeof input === \"object\" && \"__isChunk\" in (input as object)\n ? (input as TextChunk)\n : ({ __isChunk: true, text: String(input) } as TextChunk);\n return { ...base, link: { url } };\n };\n\n// ── ANSI conversion ───────────────────────────────────────────────────────────\n\n/** Convert a StyledText or string to an ANSI escape-code string. */\nexport function styledTextToAnsi(styledText: StyledText | string): string {\n if (typeof styledText === \"string\") return styledText;\n let result = \"\";\n for (const chunk of styledText.chunks) {\n let prefix = \"\";\n const suffix_parts: string[] = [];\n\n if (chunk.fg && chunk.fg.a > 0)\n prefix += `\\x1b[38;2;${chunk.fg.r};${chunk.fg.g};${chunk.fg.b}m`;\n if (chunk.bg && chunk.bg.a > 0)\n prefix += `\\x1b[48;2;${chunk.bg.r};${chunk.bg.g};${chunk.bg.b}m`;\n\n const attrs = chunk.attributes ?? 0;\n if (attrs & TextAttributes.BOLD) prefix += \"\\x1b[1m\";\n if (attrs & TextAttributes.DIM) prefix += \"\\x1b[2m\";\n if (attrs & TextAttributes.ITALIC) prefix += \"\\x1b[3m\";\n if (attrs & TextAttributes.UNDERLINE) prefix += \"\\x1b[4m\";\n if (attrs & TextAttributes.BLINK) prefix += \"\\x1b[5m\";\n if (attrs & TextAttributes.INVERSE) prefix += \"\\x1b[7m\";\n if (attrs & TextAttributes.HIDDEN) prefix += \"\\x1b[8m\";\n if (attrs & TextAttributes.STRIKETHROUGH) prefix += \"\\x1b[9m\";\n\n if (chunk.link?.url) {\n prefix += `\\x1b]8;;${chunk.link.url}\\x1b\\\\`;\n suffix_parts.push(\"\\x1b]8;;\\x1b\\\\\");\n }\n\n if (prefix) suffix_parts.push(\"\\x1b[0m\");\n\n result += prefix + chunk.text + suffix_parts.join(\"\");\n }\n return result;\n}\n\n/** Get the visible (non-ANSI) character width of a string. */\nexport function visibleWidth(str: string): number {\n // Strip ANSI codes then count wide chars as 2\n // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require ESC character\n const stripped = str.replace(/\\x1b\\[[^m]*m|\\x1b\\][^\\x07\\x1b]*[\\x07\\x1b\\\\]/g, \"\");\n let width = 0;\n for (const ch of stripped) {\n const cp = ch.codePointAt(0) ?? 0;\n // Basic wide character detection (CJK ranges)\n if (\n (cp >= 0x1100 && cp <= 0x115f) ||\n cp === 0x2329 ||\n cp === 0x232a ||\n (cp >= 0x2e80 && cp <= 0x303e) ||\n (cp >= 0x3040 && cp <= 0xa4cf) ||\n (cp >= 0xa960 && cp <= 0xa97f) ||\n (cp >= 0xac00 && cp <= 0xd7a3) ||\n (cp >= 0xf900 && cp <= 0xfaff) ||\n (cp >= 0xfe10 && cp <= 0xfe19) ||\n (cp >= 0xfe30 && cp <= 0xfe6f) ||\n (cp >= 0xff01 && cp <= 0xff60) ||\n (cp >= 0xffe0 && cp <= 0xffe6) ||\n (cp >= 0x1b000 && cp <= 0x1b001) ||\n (cp >= 0x1f004 && cp <= 0x1f0cf) ||\n (cp >= 0x1f200 && cp <= 0x1f251) ||\n (cp >= 0x1f300 && cp <= 0x1f9ff)\n ) {\n width += 2;\n } else {\n width += 1;\n }\n }\n return width;\n}\n","/**\n * Event enums for BetterTUI renderables and renderer.\n */\n\n/** Events emitted by the CliRenderer. */\nexport enum CliRenderEvents {\n RESIZE = \"resize\",\n FRAME = \"frame\",\n FOCUS = \"focus\",\n BLUR = \"blur\",\n FOCUSED_RENDERABLE = \"focused_renderable\",\n FOCUSED_EDITOR = \"focused_editor\",\n THEME_MODE = \"theme_mode\",\n PALETTE = \"palette\",\n CAPABILITIES = \"capabilities\",\n SELECTION = \"selection\",\n DEBUG_OVERLAY_TOGGLE = \"debugOverlay:toggle\",\n DESTROY = \"destroy\",\n MEMORY_SNAPSHOT = \"memory:snapshot\",\n}\n\n/** Events emitted by all Renderable instances. */\nexport enum RenderableEvents {\n FOCUSED = \"focused\",\n BLURRED = \"blurred\",\n DESTROYED = \"destroyed\",\n}\n\n/** Events emitted by Input. */\nexport enum InputEvents {\n INPUT = \"input\",\n CHANGE = \"change\",\n ENTER = \"enter\",\n}\n\n/** Events emitted by Select. */\nexport enum SelectEvents {\n SELECTION_CHANGED = \"selection_changed\",\n ITEM_SELECTED = \"item_selected\",\n}\n\n/** Events emitted by TabSelect. */\nexport enum TabSelectEvents {\n SELECTION_CHANGED = \"selection_changed\",\n ITEM_SELECTED = \"item_selected\",\n}\n\n/** Events emitted by Slider. */\nexport enum SliderEvents {\n CHANGE = \"change\",\n}\n\n/** Layout-related events. */\nexport enum LayoutEvents {\n LAYOUT_CHANGED = \"layout-changed\",\n RESIZED = \"resized\",\n}\n","const singletonCacheSymbol = Symbol.for(\"@bettertui/core/singleton\");\n\n/**\n * Ensures a value is initialized once per process,\n * persists across hot reloads, and is type-safe.\n */\nexport function singleton<T>(key: string, factory: () => T): T {\n // biome-ignore lint/suspicious/noExplicitAny: globalThis symbol cache bag\n const g = globalThis as any;\n if (!g[singletonCacheSymbol]) {\n g[singletonCacheSymbol] = {};\n }\n const bag = g[singletonCacheSymbol];\n if (!(key in bag)) {\n bag[key] = factory();\n }\n return bag[key] as T;\n}\n\nexport function getSingleton<T>(key: string): T | undefined {\n // biome-ignore lint/suspicious/noExplicitAny: globalThis symbol cache bag\n const g = globalThis as any;\n const bag = g[singletonCacheSymbol];\n return bag?.[key] as T | undefined;\n}\n\nexport function destroySingleton(key: string): void {\n // biome-ignore lint/suspicious/noExplicitAny: globalThis symbol cache bag\n const g = globalThis as any;\n const bag = g[singletonCacheSymbol];\n if (bag && key in bag) {\n delete bag[key];\n }\n}\n\nexport function hasSingleton(key: string): boolean {\n // biome-ignore lint/suspicious/noExplicitAny: globalThis symbol cache bag\n const g = globalThis as any;\n const bag = g[singletonCacheSymbol];\n return Boolean(bag && key in bag);\n}\n","import { singleton } from \"./singleton\";\n\n/**\n * Environment variable configuration for BetterTUI.\n */\nexport interface EnvVarConfig {\n name: string;\n description: string;\n default?: string | boolean | number;\n type?: \"string\" | \"boolean\" | \"number\";\n}\n\nexport const envRegistry: Record<string, EnvVarConfig> = singleton(\"env-registry\", () => ({}));\n\n/**\n * Register an environment variable with type coercion and documentation metadata.\n */\nexport function registerEnvVar(config: EnvVarConfig): void {\n const existing = envRegistry[config.name];\n if (existing) {\n if (\n existing.description !== config.description ||\n existing.type !== config.type ||\n existing.default !== config.default\n ) {\n throw new Error(\n `Environment variable \"${config.name}\" is already registered with different configuration. ` +\n `Existing: ${JSON.stringify(existing)}, New: ${JSON.stringify(config)}`,\n );\n }\n return;\n }\n envRegistry[config.name] = config;\n}\n\n/** Get a registered env var config by name. */\nexport function getEnvVarConfig(name: string): EnvVarConfig | undefined {\n return envRegistry[name];\n}\n\n/** Get all registered env var configs. */\nexport function getAllEnvVarConfigs(): EnvVarConfig[] {\n return Object.values(envRegistry);\n}\n\nfunction normalizeBoolean(value: string): boolean {\n const lowerValue = value.toLowerCase();\n return [\"true\", \"1\", \"on\", \"yes\"].includes(lowerValue);\n}\n\nfunction parseEnvValue(config: EnvVarConfig): string | boolean | number {\n const envValue = process.env[config.name];\n\n if (envValue === undefined && config.default !== undefined) {\n return config.default;\n }\n\n if (envValue === undefined) {\n throw new Error(\n `Required environment variable ${config.name} is not set. ${config.description}`,\n );\n }\n\n switch (config.type) {\n case \"boolean\":\n return typeof envValue === \"boolean\" ? envValue : normalizeBoolean(envValue);\n case \"number\": {\n const numValue = Number(envValue);\n if (Number.isNaN(numValue)) {\n throw new Error(\n `Environment variable ${config.name} must be a valid number, got: ${envValue}`,\n );\n }\n return numValue;\n }\n default:\n return envValue;\n }\n}\n\nclass EnvStore {\n private parsedValues: Map<string, string | boolean | number> = new Map();\n\n get(key: string): unknown {\n if (this.parsedValues.has(key)) {\n return this.parsedValues.get(key);\n }\n\n if (!(key in envRegistry)) {\n // Fallback for un-registered process.env lookup\n return process.env[key];\n }\n\n try {\n const value = parseEnvValue(envRegistry[key]);\n this.parsedValues.set(key, value);\n return value;\n } catch (error) {\n throw new Error(\n `Failed to parse env var ${key}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n has(key: string): boolean {\n return key in envRegistry || (typeof process !== \"undefined\" && key in process.env);\n }\n\n clearCache(): void {\n this.parsedValues.clear();\n }\n}\n\nconst envStore = singleton(\"env-store\", () => new EnvStore());\n\nexport function clearEnvCache(): void {\n envStore.clearCache();\n}\n\nexport function generateEnvMarkdown(): string {\n const configs = Object.values(envRegistry);\n\n if (configs.length === 0) {\n return \"# Environment Variables\\n\\nNo environment variables registered.\\n\";\n }\n\n let markdown = \"# Environment Variables\\n\\n\";\n\n for (const config of configs) {\n markdown += `## ${config.name}\\n\\n`;\n markdown += `${config.description}\\n\\n`;\n markdown += `**Type:** \\`${config.type || \"string\"}\\` \\n`;\n\n if (config.default !== undefined) {\n const defaultValue =\n typeof config.default === \"string\" ? `\"${config.default}\"` : String(config.default);\n markdown += `**Default:** \\`${defaultValue}\\`\\n`;\n } else {\n markdown += \"**Default:** *Required*\\n\";\n }\n\n markdown += \"\\n\";\n }\n\n return markdown;\n}\n\nexport function generateEnvColored(): string {\n const configs = Object.values(envRegistry);\n\n if (configs.length === 0) {\n return \"\\x1b[1;36mEnvironment Variables\\x1b[0m\\n\\nNo environment variables registered.\\n\";\n }\n\n let output = \"\\x1b[1;36mBetterTUI Environment Variables\\x1b[0m\\n\\n\";\n\n for (const config of configs) {\n output += `\\x1b[1;33m${config.name}\\x1b[0m\\n`;\n output += `${config.description}\\n`;\n output += `\\x1b[32mType:\\x1b[0m \\x1b[36m${config.type || \"string\"}\\x1b[0m\\n`;\n\n if (config.default !== undefined) {\n const defaultValue =\n typeof config.default === \"string\" ? `\"${config.default}\"` : String(config.default);\n output += `\\x1b[32mDefault:\\x1b[0m \\x1b[35m${defaultValue}\\x1b[0m\\n`;\n } else {\n output += \"\\x1b[32mDefault:\\x1b[0m \\x1b[31mRequired\\x1b[0m\\n\";\n }\n\n output += \"\\n\";\n }\n\n return output;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: env proxy typed dynamically\nexport const env = new Proxy({} as Record<string, any>, {\n get(_target, prop: string) {\n if (typeof prop !== \"string\") {\n return undefined;\n }\n return envStore.get(prop);\n },\n\n has(_target, prop: string) {\n return envStore.has(prop);\n },\n\n ownKeys() {\n return Object.keys(envRegistry);\n },\n\n getOwnPropertyDescriptor(_target, prop: string) {\n if (envStore.has(prop)) {\n return {\n enumerable: true,\n configurable: true,\n get: () => envStore.get(prop),\n };\n }\n return undefined;\n },\n});\n\n// Register standard BetterTUI environment variables\nregisterEnvVar({\n name: \"BTUI_DEBUG\",\n description: \"Enable debug mode, event logging, and DevTools inspector in BetterTUI.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_SHOW_STATS\",\n description: \"Show performance and FPS debug overlay at startup.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_USE_CONSOLE\",\n description: \"Enable global console.* capture for the built-in terminal console overlay.\",\n type: \"boolean\",\n default: true,\n});\n\nregisterEnvVar({\n name: \"SHOW_CONSOLE\",\n description: \"Open the built-in terminal console overlay at startup.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_DUMP_CAPTURES\",\n description: \"Dump captured stdout and console logs on process exit.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_NO_NATIVE_RENDER\",\n description: \"Skip native Rust frame renderer and run JS-only fallback loop.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_FORCE_UNICODE\",\n description: \"Force Mode 2026 Unicode support in terminal capability detection.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_FORCE_WCWIDTH\",\n description: \"Force standard wcwidth for character width calculations.\",\n type: \"boolean\",\n default: false,\n});\n\nregisterEnvVar({\n name: \"BTUI_FORCE_EXPLICIT_WIDTH\",\n description:\n \"Force explicit character width detection mode (set 'false' or '0' for older terminals).\",\n type: \"string\",\n default: \"\",\n});\n\nregisterEnvVar({\n name: \"BTUI_LOG_LEVEL\",\n description: \"Default log level for BetterTUI diagnostics (debug, info, warn, error, trace).\",\n type: \"string\",\n default: \"debug\",\n});\n","/**\n * Timeline animation system.\n * Provides a GSAP-like API for building animation sequences.\n */\n\nexport interface TweenConfig {\n [key: string]: unknown;\n}\n\nexport interface TimelineOptions {\n looping?: boolean;\n speed?: number;\n onComplete?: () => void;\n}\n\n/**\n * A simple animation timeline.\n * Tracks progress from 0 to 1 over a duration, with looping support.\n */\nexport class Timeline {\n private readonly _duration: number;\n private readonly _looping: boolean;\n private _position = 0;\n private _isPlaying = false;\n private _speed: number;\n private _onComplete: (() => void) | undefined;\n private _tweens: Array<{\n targets: unknown;\n props: TweenConfig;\n offset: number;\n duration: number;\n }> = [];\n private _children: Timeline[] = [];\n\n constructor(duration = 1, options: TimelineOptions = {}) {\n this._duration = duration;\n this._looping = options.looping ?? false;\n this._speed = options.speed ?? 1;\n this._onComplete = options.onComplete;\n }\n\n get position(): number {\n return this._position;\n }\n\n set position(v: number) {\n this._position = Math.max(0, Math.min(1, v));\n }\n\n get isPlaying(): boolean {\n return this._isPlaying;\n }\n\n get duration(): number {\n return this._duration;\n }\n\n get speed(): number {\n return this._speed;\n }\n\n set speed(v: number) {\n this._speed = v;\n for (const child of this._children) {\n child.speed = v;\n }\n }\n\n get looping(): boolean {\n return this._looping;\n }\n\n /** Start or resume playback. */\n play(): void {\n this._isPlaying = true;\n for (const child of this._children) {\n child.play();\n }\n }\n\n /** Pause playback. */\n pause(): void {\n this._isPlaying = false;\n for (const child of this._children) {\n child.pause();\n }\n }\n\n /** Reset to beginning and stop. */\n stop(): void {\n this._isPlaying = false;\n this._position = 0;\n for (const child of this._children) {\n child.stop();\n }\n }\n\n /** Reset to beginning and play. */\n restart(): void {\n this._position = 0;\n this._isPlaying = true;\n for (const child of this._children) {\n child.restart();\n }\n }\n\n /** Toggle play/pause. */\n toggle(): void {\n if (this._isPlaying) {\n this.pause();\n } else {\n this.play();\n }\n }\n\n /**\n * Add a tween to the timeline (GSAP-like API).\n * @param targets - The target objects to animate\n * @param props - The properties to tween and their target values\n * @param offset - Time offset in seconds (or \"+=N\" for relative)\n */\n add(targets: unknown, props: TweenConfig, offset?: number): this {\n this._tweens.push({\n targets,\n props,\n offset: offset ?? 0,\n duration: (props.duration as number) ?? this._duration,\n });\n return this;\n }\n\n /** Add a child timeline. */\n addChild(child: Timeline): this {\n this._children.push(child);\n return this;\n }\n\n /**\n * Update the timeline by deltaTime milliseconds.\n * Returns whether the timeline is still active.\n */\n update(deltaTimeMs: number): boolean {\n if (!this._isPlaying) return this._isPlaying;\n\n const deltaProgress = ((deltaTimeMs / 1000) * this._speed) / this._duration;\n this._position += deltaProgress;\n\n if (this._position >= 1) {\n if (this._looping) {\n this._position %= 1;\n } else {\n this._position = 1;\n this._isPlaying = false;\n this._onComplete?.();\n }\n }\n\n for (const child of this._children) {\n child.update(deltaTimeMs);\n }\n\n return this._isPlaying;\n }\n\n /**\n * Get the current value of a property at the current position.\n * For simple linear interpolation between 0 and target value.\n */\n getValue<T = number>(prop: string): T {\n // Find tween for this prop\n for (const tween of this._tweens) {\n if (typeof tween.props === \"object\" && prop in (tween.props as object)) {\n const target = (tween.props as Record<string, unknown>)[prop] as number;\n const from = 0;\n const progress = Math.max(0, Math.min(1, this._position));\n return (from + (target - from) * progress) as T;\n }\n }\n return 0 as T;\n }\n\n /** Seek to a specific position (0-1). */\n seek(position: number): void {\n this._position = Math.max(0, Math.min(1, position));\n }\n\n /** Get the time in seconds at the current position. */\n get currentTime(): number {\n return this._position * this._duration;\n }\n}\n\n/** Create a new Timeline instance. */\nexport function createTimeline(duration?: number, options?: TimelineOptions): Timeline {\n return new Timeline(duration ?? 1, options ?? {});\n}\n","/**\n * Box — the primary container widget.\n * Wraps an engine \"Box\" node with layout, styling, and event support.\n */\n\nimport { EventEmitter } from \"node:events\";\nimport type { LayoutConstraints } from \"@bettertui/shared\";\nimport { RenderableEvents } from \"../lib/renderableEvents\";\nimport { type ColorInput, type RGBA, parseColor, rgbaToEngineColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\n\nexport type BorderSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type BorderStyleKind = \"single\" | \"double\" | \"round\" | \"thick\" | \"dashed\" | \"ascii\" | \"none\";\n\n// Border character sets\nconst BORDER_CHARS: Record<BorderStyleKind, string[]> = {\n single: [\"┌\", \"─\", \"┐\", \"│\", \"└\", \"─\", \"┘\", \"│\"],\n double: [\"╔\", \"═\", \"╗\", \"║\", \"╚\", \"═\", \"╝\", \"║\"],\n round: [\"╭\", \"─\", \"╮\", \"│\", \"╰\", \"─\", \"╯\", \"│\"],\n thick: [\"┏\", \"━\", \"┓\", \"┃\", \"┗\", \"━\", \"┛\", \"┃\"],\n dashed: [\"╌\", \"╌\", \"╌\", \"┆\", \"╌\", \"╌\", \"╌\", \"┆\"],\n ascii: [\"+\", \"-\", \"+\", \"|\", \"+\", \"-\", \"+\", \"|\"],\n none: [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"],\n};\n\nexport interface BoxOptions {\n id?: string;\n // biome-ignore lint/suspicious/noExplicitAny: allow component options prop\n options?: any;\n width?: number | string;\n height?: number | string;\n minWidth?: number | string;\n maxWidth?: number | string;\n minHeight?: number | string;\n maxHeight?: number | string;\n position?: \"relative\" | \"absolute\";\n top?: number | string;\n right?: number | string;\n bottom?: number | string;\n left?: number | string;\n zIndex?: number;\n flexDirection?: \"row\" | \"column\" | \"row-reverse\" | \"column-reverse\";\n flexGrow?: number;\n flexShrink?: number;\n flexBasis?: number | string;\n flexWrap?: \"nowrap\" | \"wrap\";\n alignItems?: \"flex-start\" | \"center\" | \"flex-end\" | \"stretch\" | \"baseline\";\n alignSelf?: \"flex-start\" | \"center\" | \"flex-end\" | \"stretch\" | \"baseline\";\n justifyContent?:\n | \"flex-start\"\n | \"center\"\n | \"flex-end\"\n | \"space-between\"\n | \"space-around\"\n | \"space-evenly\";\n overflow?: \"visible\" | \"hidden\" | \"scroll\";\n gap?: number;\n rowGap?: number;\n columnGap?: number;\n padding?: number;\n paddingX?: number;\n paddingY?: number;\n paddingTop?: number;\n paddingRight?: number;\n paddingBottom?: number;\n paddingLeft?: number;\n margin?: number;\n marginX?: number;\n marginY?: number;\n marginTop?: number;\n marginRight?: number;\n marginBottom?: number;\n marginLeft?: number;\n backgroundColor?: ColorInput;\n borderStyle?: BorderStyleKind;\n border?: boolean | BorderSide[];\n borderColor?: ColorInput;\n focusedBorderColor?: ColorInput;\n title?: string;\n titleColor?: ColorInput;\n titleAlignment?: \"left\" | \"center\" | \"right\";\n bottomTitle?: string;\n bottomTitleAlignment?: \"left\" | \"center\" | \"right\";\n opacity?: number;\n visible?: boolean;\n buffered?: boolean;\n focusable?: boolean;\n onMouseDown?: (event: unknown) => void;\n onMouseUp?: (event: unknown) => void;\n onMouseMove?: (event: unknown) => void;\n onMouseDrag?: (event: unknown) => void;\n onMouseDragEnd?: (event: unknown) => void;\n onMouseDrop?: (event: unknown) => void;\n onMouseOver?: (event: unknown) => void;\n onMouseOut?: (event: unknown) => void;\n onMouseScroll?: (event: unknown) => void;\n onMouse?: (event: unknown) => void;\n onKeyDown?: (key: unknown) => void;\n onClick?: (event: unknown) => void;\n onSizeChange?: () => void;\n /**\n * Called after each render frame with a buffer handle.\n * Bound to the Box instance (`this` = the renderable).\n * Use this for custom per-frame drawing on top of the box.\n */\n renderAfter?: (this: Box, buffer: unknown, deltaTime?: number) => void;\n}\n\nlet _boxCounter = 0;\n\n/** Minimal stub buffer passed to renderAfter callbacks. */\nfunction createStubBuffer(box: Box): unknown {\n const bg = new Uint16Array(0);\n const fg = new Uint16Array(0);\n const char = new Uint32Array(0);\n const attributes = new Uint32Array(0);\n return {\n get width() {\n return typeof box.width === \"number\" ? box.width : 0;\n },\n get height() {\n return typeof box.height === \"number\" ? box.height : 0;\n },\n buffers: { bg, fg, char, attributes },\n setCell() {},\n drawText() {},\n fillRect() {},\n colorMatrix() {},\n pushScissorRect() {},\n popScissorRect() {},\n pushOpacity() {},\n popOpacity() {},\n clear() {},\n };\n}\n\nexport class Box extends EventEmitter {\n protected readonly _renderer: CliRenderer;\n protected _nodeId: number;\n protected readonly _id: string;\n protected _focused = false;\n protected _visible: boolean;\n protected _isDestroyed = false;\n protected _opacity: number;\n protected _backgroundColor: RGBA | null = null;\n protected _borderStyle: BorderStyleKind;\n protected _border: boolean | BorderSide[];\n protected _borderColor: RGBA;\n protected _focusedBorderColor: RGBA;\n protected _focusable: boolean;\n protected _title: string | undefined;\n protected _titleColor: RGBA | undefined;\n protected _titleAlignment: \"left\" | \"center\" | \"right\";\n protected _children: Map<string, Box> = new Map();\n protected _childList: Box[] = [];\n protected _parent: Box | null = null;\n protected _options: BoxOptions;\n private _renderAfterCallback: ((dt: number) => void) | null = null;\n\n constructor(renderer: CliRenderer, options: BoxOptions = {}, existingNodeId?: number) {\n super();\n _boxCounter++;\n this._id = options.id ?? `box-${_boxCounter}`;\n this._renderer = renderer;\n this._options = options;\n this._nodeId = existingNodeId ?? renderer.createNode(\"Box\");\n this._visible = options.visible !== false;\n this._opacity = options.opacity ?? 1;\n this._focusable = options.focusable ?? false;\n this._borderStyle = options.borderStyle ?? \"single\";\n this._border = options.border ?? false;\n this._borderColor = parseColor(options.borderColor ?? \"#ffffff\");\n this._focusedBorderColor = parseColor(options.focusedBorderColor ?? \"#00aaff\");\n this._title = options.title;\n this._titleColor = options.titleColor ? parseColor(options.titleColor) : undefined;\n this._titleAlignment = options.titleAlignment ?? \"left\";\n\n if (options.backgroundColor) {\n this._backgroundColor = parseColor(options.backgroundColor);\n }\n\n this._applyLayout(options);\n this._applyStyle();\n\n // Register renderAfter frame callback if provided\n if (options.renderAfter) {\n const buf = createStubBuffer(this);\n this._renderAfterCallback = (dt: number) => {\n if (!this._isDestroyed && options.renderAfter) {\n options.renderAfter.call(this, buf, dt);\n }\n };\n renderer.setFrameCallback(this._renderAfterCallback);\n }\n }\n\n get id(): string {\n return this._id;\n }\n get nodeId(): number {\n return this._nodeId;\n }\n get focused(): boolean {\n return this._focused;\n }\n get visible(): boolean {\n return this._visible;\n }\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n get opacity(): number {\n return this._opacity;\n }\n get backgroundColor(): RGBA | null {\n return this._backgroundColor;\n }\n get borderStyle(): BorderStyleKind {\n return this._borderStyle;\n }\n get border(): boolean | BorderSide[] {\n return this._border;\n }\n get renderer(): CliRenderer {\n return this._renderer;\n }\n get boxOptions(): BoxOptions {\n return this._options;\n }\n get parent(): Box | null {\n return this._parent;\n }\n\n getEstimatedHeight(): number {\n if (typeof this._options.height === \"number\") {\n return this._options.height;\n }\n let h = 0;\n if (this._options.border) h += 2;\n if (typeof this._options.marginTop === \"number\") h += this._options.marginTop;\n if (typeof this._options.marginBottom === \"number\") h += this._options.marginBottom;\n if (typeof this._options.paddingTop === \"number\") h += this._options.paddingTop;\n if (typeof this._options.paddingBottom === \"number\") h += this._options.paddingBottom;\n if (typeof this._options.padding === \"number\") h += this._options.padding * 2;\n if (typeof this._options.margin === \"number\") h += this._options.margin * 2;\n\n if (this._childList.length === 0) {\n return Math.max(1, h + 1);\n }\n\n let childrenHeight = 0;\n for (const child of this._childList) {\n const ch = child.getEstimatedHeight();\n if (this._options.flexDirection === \"row\") {\n childrenHeight = Math.max(childrenHeight, ch);\n } else {\n childrenHeight += ch;\n }\n }\n return Math.max(1, h + childrenHeight);\n }\n\n /** Computed layout width (from options; not the engine-resolved value). */\n get width(): number | string | undefined {\n return this._options.width;\n }\n /** Computed layout height (from options; not the engine-resolved value). */\n get height(): number | string | undefined {\n return this._options.height;\n }\n /** Screen X position (approximate; engine is the source of truth). */\n get x(): number {\n return typeof this._options.left === \"number\" ? this._options.left : 0;\n }\n /** Screen Y position (approximate; engine is the source of truth). */\n get y(): number {\n return typeof this._options.top === \"number\" ? this._options.top : 0;\n }\n get screenX(): number {\n return this.x;\n }\n get screenY(): number {\n return this.y;\n }\n\n set visible(value: boolean) {\n if (this._visible !== value) {\n this._visible = value;\n this._applyLayout(this._options);\n this._applyStyle();\n }\n }\n\n set opacity(value: number) {\n this._opacity = Math.max(0, Math.min(1, value));\n this._applyStyle();\n }\n\n set backgroundColor(color: ColorInput) {\n this._backgroundColor = parseColor(color);\n this._applyStyle();\n }\n\n set borderColor(color: ColorInput) {\n this._borderColor = parseColor(color);\n this._applyStyle();\n }\n\n set borderStyle(style: BorderStyleKind) {\n this._borderStyle = style;\n this._applyStyle();\n }\n\n set border(value: boolean | BorderSide[]) {\n this._border = value;\n this._options.border = value;\n this._applyLayout(this._options);\n this._applyStyle();\n }\n\n set title(value: string | undefined) {\n this._title = value;\n this._applyStyle();\n }\n\n set focusedBorderColor(color: ColorInput) {\n this._focusedBorderColor = parseColor(color);\n this._applyStyle();\n }\n\n set width(value: number | string) {\n this._options.width = value;\n this._applyLayout(this._options);\n }\n\n set height(value: number | string) {\n this._options.height = value;\n this._applyLayout(this._options);\n }\n\n set flexDirection(value: BoxOptions[\"flexDirection\"]) {\n this._options.flexDirection = value;\n this._applyLayout(this._options);\n }\n\n set flexGrow(value: number) {\n this._options.flexGrow = value;\n this._applyLayout(this._options);\n }\n\n set flexBasis(value: number | string) {\n this._options.flexBasis = value;\n this._applyLayout(this._options);\n }\n\n set marginBottom(value: number) {\n this._options.marginBottom = value;\n this._applyLayout(this._options);\n }\n\n set marginTop(value: number) {\n this._options.marginTop = value;\n this._applyLayout(this._options);\n }\n\n set marginLeft(value: number) {\n this._options.marginLeft = value;\n this._applyLayout(this._options);\n }\n\n set marginRight(value: number) {\n this._options.marginRight = value;\n this._applyLayout(this._options);\n }\n\n set zIndex(value: number) {\n this._options.zIndex = value;\n this._applyLayout(this._options);\n }\n\n add(child: Box, index?: number): void {\n if (this._isDestroyed) return;\n child._parent = this;\n this._children.set(child.id, child);\n if (index !== undefined) {\n this._childList.splice(index, 0, child);\n } else {\n this._childList.push(child);\n }\n this._renderer.appendChild(this._nodeId, child._nodeId);\n }\n\n remove(child: Box): void {\n if (this._isDestroyed) return;\n child._parent = null;\n this._children.delete(child.id);\n const idx = this._childList.indexOf(child);\n if (idx !== -1) this._childList.splice(idx, 1);\n this._renderer.removeNode(child._nodeId);\n }\n\n getRenderable(id: string): Box | undefined {\n if (this._id === id) return this;\n for (const child of this._childList) {\n const found = child.getRenderable(id);\n if (found) return found;\n }\n return undefined;\n }\n\n getChildren(): Box[] {\n return [...this._childList];\n }\n\n // ── Focus management ──────────────────────────────────────────────────────────\n\n focus(): void {\n if (this._isDestroyed) return;\n this._focused = true;\n this.emit(RenderableEvents.FOCUSED, this);\n this._applyStyle();\n }\n\n blur(): void {\n if (this._isDestroyed) return;\n this._focused = false;\n this.emit(RenderableEvents.BLURRED, this);\n this._applyStyle();\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._isDestroyed = true;\n this.emit(RenderableEvents.DESTROYED, this);\n this.removeAllListeners();\n if (this._renderAfterCallback) {\n this._renderer.removeFrameCallback(this._renderAfterCallback);\n this._renderAfterCallback = null;\n }\n try {\n this._renderer.removeNode(this._nodeId);\n } catch {\n // ignore - may already be removed\n }\n this._children.clear();\n this._childList = [];\n }\n\n destroyRecursively(): void {\n for (const child of [...this._childList]) {\n child.destroyRecursively();\n }\n this.destroy();\n }\n\n // ── Layout setters ───────────────────────────────────────────────────────────\n\n setLayout(layout: Partial<BoxOptions>): void {\n Object.assign(this._options, layout);\n this._applyLayout(this._options);\n }\n\n setPosition(pos: {\n top?: number | string;\n left?: number | string;\n right?: number | string;\n bottom?: number | string;\n }): void {\n const layout: LayoutConstraints = {};\n if (pos.top !== undefined) layout.top = pos.top as number;\n if (pos.left !== undefined) layout.left = pos.left as number;\n if (pos.right !== undefined) layout.right = pos.right as number;\n if (pos.bottom !== undefined) layout.bottom = pos.bottom as number;\n this._renderer.setNodeLayout(this._nodeId, layout);\n }\n\n // ── Internal helpers ──────────────────────────────────────────────────────────\n\n protected _applyLayout(options: Partial<BoxOptions>): void {\n const layout: LayoutConstraints = {};\n\n if (options.width !== undefined) layout.width = options.width;\n if (options.height !== undefined) layout.height = options.height;\n if (options.minWidth !== undefined) layout.minWidth = options.minWidth;\n if (options.maxWidth !== undefined) layout.maxWidth = options.maxWidth;\n if (options.minHeight !== undefined) layout.minHeight = options.minHeight;\n if (options.maxHeight !== undefined) layout.maxHeight = options.maxHeight;\n if (options.position !== undefined) layout.position = options.position;\n if (options.top !== undefined) layout.top = options.top as number;\n if (options.right !== undefined) layout.right = options.right as number;\n if (options.bottom !== undefined) layout.bottom = options.bottom as number;\n if (options.left !== undefined) layout.left = options.left as number;\n if (options.zIndex !== undefined) layout.zIndex = options.zIndex;\n if (options.flexDirection !== undefined) layout.flexDirection = options.flexDirection;\n if (options.flexGrow !== undefined) layout.flexGrow = options.flexGrow;\n if (options.flexShrink !== undefined) layout.flexShrink = options.flexShrink;\n if (options.flexWrap !== undefined) layout.flexWrap = options.flexWrap;\n if (options.alignItems !== undefined) layout.alignItems = options.alignItems;\n if (options.alignSelf !== undefined) layout.alignSelf = options.alignSelf;\n if (options.justifyContent !== undefined) layout.justifyContent = options.justifyContent;\n if (options.overflow !== undefined) layout.overflow = options.overflow;\n\n // Gap\n if (\n options.gap !== undefined &&\n options.rowGap === undefined &&\n options.columnGap === undefined\n ) {\n layout.gap = options.gap;\n } else if (options.rowGap !== undefined || options.columnGap !== undefined) {\n layout.gap = { row: options.rowGap, column: options.columnGap };\n }\n\n // Padding (resolve shorthand)\n const pt = options.paddingTop ?? options.paddingY ?? options.padding;\n const pr = options.paddingRight ?? options.paddingX ?? options.padding;\n const pb = options.paddingBottom ?? options.paddingY ?? options.padding;\n const pl = options.paddingLeft ?? options.paddingX ?? options.padding;\n if (pt !== undefined) layout.paddingTop = pt;\n if (pr !== undefined) layout.paddingRight = pr;\n if (pb !== undefined) layout.paddingBottom = pb;\n if (pl !== undefined) layout.paddingLeft = pl;\n\n // Margin\n const mt = options.marginTop ?? options.marginY ?? options.margin;\n const mr = options.marginRight ?? options.marginX ?? options.margin;\n const mb = options.marginBottom ?? options.marginY ?? options.margin;\n const ml = options.marginLeft ?? options.marginX ?? options.margin;\n if (mt !== undefined) layout.marginTop = mt;\n if (mr !== undefined) layout.marginRight = mr;\n if (mb !== undefined) layout.marginBottom = mb;\n if (ml !== undefined) layout.marginLeft = ml;\n\n if (!this._visible) layout.display = \"none\";\n\n // Border layout contribution: reserve space for border cells so the\n // engine's box-sizing accounts for the border width.\n const borderVal = this._options.border;\n if (borderVal === true) {\n layout.borderTop = 1;\n layout.borderRight = 1;\n layout.borderBottom = 1;\n layout.borderLeft = 1;\n } else if (Array.isArray(borderVal) && borderVal.length > 0) {\n layout.borderTop = borderVal.includes(\"top\") ? 1 : 0;\n layout.borderRight = borderVal.includes(\"right\") ? 1 : 0;\n layout.borderBottom = borderVal.includes(\"bottom\") ? 1 : 0;\n layout.borderLeft = borderVal.includes(\"left\") ? 1 : 0;\n }\n\n this._renderer.setNodeLayout(this._nodeId, layout);\n }\n\n protected _applyStyle(): void {\n const bgColor = this._focused && this._border ? this._backgroundColor : this._backgroundColor;\n\n const styleJson: Record<string, unknown> = {};\n if (bgColor && bgColor.a > 0) {\n styleJson.bg = rgbaToEngineColor(bgColor);\n }\n\n // Border via engine style (extra fields beyond TypeScript Style type)\n const hasBorder =\n this._border === true || (Array.isArray(this._border) && this._border.length > 0);\n if (hasBorder) {\n const borderColor = this._focused ? this._focusedBorderColor : this._borderColor;\n styleJson.border = this._borderStyle;\n styleJson.border_color = rgbaToEngineColor(borderColor);\n if (this._title) {\n styleJson.title = this._title;\n styleJson.title_align = this._titleAlignment ?? \"left\";\n if (this._titleColor) {\n styleJson.title_color = rgbaToEngineColor(this._titleColor);\n }\n }\n }\n\n // Opacity\n if (this._opacity < 1) {\n styleJson.opacity = this._opacity;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: engine accepts extended style fields beyond the TypeScript Style interface\n this._renderer.setNodeStyle(this._nodeId, styleJson as any);\n }\n}\n\n/**\n * Root — the scene root, wrapping the engine's root node.\n * Created automatically by CliRenderer and exposed as `renderer.root`.\n */\nexport class Root extends Box {\n constructor(renderer: CliRenderer) {\n super(\n renderer,\n { flexDirection: \"column\", width: \"100%\", height: \"100%\" },\n renderer.rootNodeId,\n );\n }\n\n destroy(): void {\n // Root can never be destroyed\n }\n}\n\nexport { BORDER_CHARS };\n","import type { KeyEvent } from \"../lib/keyHandler\";\nimport { InputEvents, RenderableEvents } from \"../lib/renderableEvents\";\nimport { type ColorInput, type RGBA, parseColor, rgbaToEngineColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\nexport interface InputOptions extends BoxOptions {\n value?: string;\n placeholder?: string;\n placeholderColor?: ColorInput;\n textColor?: ColorInput;\n focusedTextColor?: ColorInput;\n cursorColor?: ColorInput;\n backgroundColor?: ColorInput;\n focusedBackgroundColor?: ColorInput;\n maxLength?: number;\n minLength?: number;\n showCursor?: boolean;\n password?: boolean;\n}\n\nexport type InputRenderableOptions = InputOptions;\n\nlet _inputCounter = 0;\n\nexport class Input extends Box {\n private _value: string;\n private _placeholder: string;\n private _placeholderColor: RGBA;\n private _textColor: RGBA;\n private _focusedTextColor: RGBA;\n private _cursorColor: RGBA;\n private _focusedBackgroundColor: RGBA | null = null;\n private _maxLength: number;\n private _minLength: number;\n private _showCursor: boolean;\n private _password: boolean;\n private _cursorPos: number;\n private _lastCommittedValue: string;\n private _textNodeId: number;\n private readonly _keyHandler: (key: KeyEvent) => void;\n\n constructor(renderer: CliRenderer, options: InputOptions = {}) {\n _inputCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `input-${_inputCounter}`,\n focusable: true,\n });\n\n this._value = (options.value ?? \"\").substring(0, options.maxLength ?? 1000);\n this._placeholder = options.placeholder ?? \"\";\n this._placeholderColor = parseColor(options.placeholderColor ?? \"#666666\");\n this._textColor = parseColor(options.textColor ?? \"#ffffff\");\n this._focusedTextColor = parseColor(options.focusedTextColor ?? \"#ffffff\");\n this._cursorColor = parseColor(options.cursorColor ?? \"#ffff00\");\n this._maxLength = options.maxLength ?? 1000;\n this._minLength = options.minLength ?? 0;\n this._showCursor = options.showCursor !== false;\n this._password = options.password ?? false;\n this._cursorPos = this._value.length;\n this._lastCommittedValue = this._value;\n\n if (options.focusedBackgroundColor) {\n this._focusedBackgroundColor = parseColor(options.focusedBackgroundColor);\n }\n\n this._textNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._textNodeId);\n\n this._keyHandler = this._handleKey.bind(this);\n this._render();\n }\n\n // ── Getters/Setters ───────────────────────────────────────────────────────────\n\n get value(): string {\n return this._value;\n }\n\n set value(v: string) {\n const newVal = v.replace(/[\\n\\r]/g, \"\").substring(0, this._maxLength);\n if (this._value !== newVal) {\n this._value = newVal;\n this._cursorPos = Math.min(this._cursorPos, newVal.length);\n this._render();\n this.emit(InputEvents.INPUT, newVal);\n }\n }\n\n get plainText(): string {\n return this._value;\n }\n\n get cursorOffset(): number {\n return this._cursorPos;\n }\n\n set cursorOffset(pos: number) {\n this._cursorPos = Math.max(0, Math.min(pos, this._value.length));\n this._render();\n }\n\n set textColor(color: ColorInput) {\n this._textColor = parseColor(color);\n this._render();\n }\n\n set focusedTextColor(color: ColorInput) {\n this._focusedTextColor = parseColor(color);\n if (this._focused) this._render();\n }\n\n set placeholder(value: string) {\n this._placeholder = value;\n this._render();\n }\n\n set placeholderColor(color: ColorInput) {\n this._placeholderColor = parseColor(color);\n this._render();\n }\n\n set cursorColor(color: ColorInput) {\n this._cursorColor = parseColor(color);\n if (this._focused) this._render();\n }\n\n set showCursor(value: boolean) {\n this._showCursor = value;\n this._render();\n }\n\n // ── Focus ─────────────────────────────────────────────────────────────────────\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n this._lastCommittedValue = this._value;\n if (this._focusedBackgroundColor) {\n this._renderer.setNodeStyle(this._nodeId, {\n bg: rgbaToEngineColor(this._focusedBackgroundColor),\n });\n }\n this._render();\n this.emit(RenderableEvents.FOCUSED, this);\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n const current = this._value;\n if (current !== this._lastCommittedValue) {\n this._lastCommittedValue = current;\n this.emit(InputEvents.CHANGE, current);\n }\n this._focused = false;\n if (this._focusedBackgroundColor && this._backgroundColor) {\n this._renderer.setNodeStyle(this._nodeId, {\n bg: rgbaToEngineColor(this._backgroundColor),\n });\n } else if (this._focusedBackgroundColor) {\n this._renderer.setNodeStyle(this._nodeId, { bg: \"transparent\" });\n }\n this._render();\n this.emit(RenderableEvents.BLURRED, this);\n }\n\n // ── Key handling ──────────────────────────────────────────────────────────────\n\n private _handleKey(key: KeyEvent): void {\n if (!this._focused || this._isDestroyed) return;\n\n if (key.name === \"return\" || key.name === \"linefeed\" || key.name === \"enter\") {\n this._submit();\n return;\n }\n\n if (key.name === \"left\") {\n this._cursorPos = Math.max(0, this._cursorPos - 1);\n this._render();\n return;\n }\n\n if (key.name === \"right\") {\n this._cursorPos = Math.min(this._value.length, this._cursorPos + 1);\n this._render();\n return;\n }\n\n if (key.name === \"home\" || (key.ctrl && key.name === \"a\")) {\n this._cursorPos = 0;\n this._render();\n return;\n }\n\n if (key.name === \"end\" || (key.ctrl && key.name === \"e\")) {\n this._cursorPos = this._value.length;\n this._render();\n return;\n }\n\n if (key.name === \"backspace\" || (key.name === \"delete\" && !key.ctrl)) {\n if (key.name === \"backspace\" && this._cursorPos > 0) {\n this._value =\n this._value.slice(0, this._cursorPos - 1) + this._value.slice(this._cursorPos);\n this._cursorPos--;\n this._render();\n this.emit(InputEvents.INPUT, this._value);\n } else if (key.name === \"delete\" && this._cursorPos < this._value.length) {\n this._value =\n this._value.slice(0, this._cursorPos) + this._value.slice(this._cursorPos + 1);\n this._render();\n this.emit(InputEvents.INPUT, this._value);\n }\n return;\n }\n\n // Ctrl+K: delete to end of line\n if (key.ctrl && key.name === \"k\") {\n this._value = this._value.slice(0, this._cursorPos);\n this._render();\n this.emit(InputEvents.INPUT, this._value);\n return;\n }\n\n // Ctrl+U: delete to start of line\n if (key.ctrl && key.name === \"u\") {\n this._value = this._value.slice(this._cursorPos);\n this._cursorPos = 0;\n this._render();\n this.emit(InputEvents.INPUT, this._value);\n return;\n }\n\n // Regular character input (ignore control sequences)\n if (key.sequence && !key.ctrl && !key.alt && !key.meta) {\n const char = key.sequence;\n if (char.length === 1 && char.charCodeAt(0) >= 32) {\n if (this._value.length < this._maxLength) {\n this._value =\n this._value.slice(0, this._cursorPos) + char + this._value.slice(this._cursorPos);\n this._cursorPos++;\n this._render();\n this.emit(InputEvents.INPUT, this._value);\n }\n }\n }\n }\n\n private _submit(): void {\n if (this._value.length < this._minLength) return;\n const current = this._value;\n if (current !== this._lastCommittedValue) {\n this._lastCommittedValue = current;\n this.emit(InputEvents.CHANGE, current);\n }\n this.emit(InputEvents.ENTER, current);\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n\n let display: string;\n\n if (this._value === \"\") {\n const ph = this._placeholder !== \"\" ? this._placeholder : \" \";\n const pc = `${this._placeholderColor.r};${this._placeholderColor.g};${this._placeholderColor.b}`;\n\n if (this._focused && this._showCursor) {\n const before = ph.slice(0, this._cursorPos);\n const cursorChar = ph[this._cursorPos] ?? \" \";\n const after = ph.slice(this._cursorPos + 1);\n const cc = `${this._cursorColor.r};${this._cursorColor.g};${this._cursorColor.b}`;\n display =\n `\\x1b[38;2;${pc}m${before}` +\n `\\x1b[38;2;${cc}m\\x1b[7m${cursorChar}\\x1b[0m` +\n `\\x1b[38;2;${pc}m${after}\\x1b[0m`;\n } else {\n display = `\\x1b[38;2;${pc}m${ph}\\x1b[0m`;\n }\n } else {\n const displayValue = this._password ? \"•\".repeat(this._value.length) : this._value;\n const textColor = this._focused ? this._focusedTextColor : this._textColor;\n\n if (this._focused && this._showCursor) {\n const before = displayValue.slice(0, this._cursorPos);\n const cursorChar = displayValue[this._cursorPos] ?? \" \";\n const after = displayValue.slice(this._cursorPos + 1);\n const tc = `${textColor.r};${textColor.g};${textColor.b}`;\n const cc = `${this._cursorColor.r};${this._cursorColor.g};${this._cursorColor.b}`;\n display =\n `\\x1b[38;2;${tc}m${before}` +\n `\\x1b[38;2;${cc}m\\x1b[7m${cursorChar}\\x1b[0m` +\n `\\x1b[38;2;${tc}m${after}\\x1b[0m`;\n } else {\n const tc = `${textColor.r};${textColor.g};${textColor.b}`;\n display = `\\x1b[38;2;${tc}m${displayValue}\\x1b[0m`;\n }\n }\n\n this._renderer.setText(this._textNodeId, display);\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n try {\n this._renderer.removeNode(this._textNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n}\n\nexport { InputEvents };\n","/**\n * Select — a keyboard-navigable list selector.\n *\n * Renders a scrollable option list with selection highlighting, optional\n * descriptions and a scroll indicator. Navigation is driven by a\n * configurable keybinding map (defaults + user overrides + aliases), mirroring\n * the OpenTUI Select pattern: `handleKeyPress` resolves a key event to an\n * action and returns whether it was consumed.\n */\n\nimport type { KeyEvent } from \"../lib/keyHandler\";\nimport { RenderableEvents, SelectEvents } from \"../lib/renderableEvents\";\nimport {\n type KeyAliasMap,\n type KeyBinding,\n buildKeyBindingsMap,\n defaultKeyAliases,\n getKeyBindingAction,\n mergeKeyAliases,\n mergeKeyBindings,\n} from \"../lib/renderableKeyBindings\";\nimport { type ColorInput, type RGBA, parseColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\nexport interface SelectOption {\n name: string;\n description: string;\n value?: unknown;\n}\n\n/** Selectable actions resolved from key events. */\nexport type SelectAction =\n | \"move-up\"\n | \"move-down\"\n | \"move-up-fast\"\n | \"move-down-fast\"\n | \"move-up-page\"\n | \"move-down-page\"\n | \"move-to-start\"\n | \"move-to-end\"\n | \"select-current\";\n\nexport type SelectKeyBinding = KeyBinding<SelectAction>;\n\nconst defaultSelectKeybindings: SelectKeyBinding[] = [\n { name: \"up\", action: \"move-up\" },\n { name: \"k\", action: \"move-up\" },\n { name: \"down\", action: \"move-down\" },\n { name: \"j\", action: \"move-down\" },\n { name: \"up\", shift: true, action: \"move-up-fast\" },\n { name: \"down\", shift: true, action: \"move-down-fast\" },\n { name: \"pageup\", action: \"move-up-page\" },\n { name: \"pagedown\", action: \"move-down-page\" },\n { name: \"home\", action: \"move-to-start\" },\n { name: \"end\", action: \"move-to-end\" },\n { name: \"return\", action: \"select-current\" },\n { name: \"linefeed\", action: \"select-current\" },\n { name: \"enter\", action: \"select-current\" },\n];\n\nexport interface SelectOptions extends BoxOptions {\n options?: SelectOption[];\n selectedIndex?: number;\n backgroundColor?: ColorInput;\n textColor?: ColorInput;\n focusedBackgroundColor?: ColorInput;\n focusedTextColor?: ColorInput;\n selectedBackgroundColor?: ColorInput;\n selectedTextColor?: ColorInput;\n descriptionColor?: ColorInput;\n selectedDescriptionColor?: ColorInput;\n showScrollIndicator?: boolean;\n showDescription?: boolean;\n showSelectionIndicator?: boolean;\n selectionIndicator?: string;\n unselectedIndicator?: string;\n wrapSelection?: boolean;\n fastScrollStep?: number;\n itemSpacing?: number;\n keyBindings?: SelectKeyBinding[];\n keyAliasMap?: KeyAliasMap;\n}\n\nexport type SelectRenderableOptions = SelectOptions;\n\nlet _selectCounter = 0;\n\nexport class Select extends Box {\n private _selectOptions: SelectOption[];\n private _selectedIndex: number;\n private _scrollOffset: number;\n private _textColor: RGBA;\n private _focusedTextColor: RGBA;\n private _selectedBgColor: RGBA;\n private _selectedTextColor: RGBA;\n private _descriptionColor: RGBA;\n private _selectedDescriptionColor: RGBA;\n private _focusedBgColor: RGBA | null = null;\n private _showScrollIndicator: boolean;\n private _showDescription: boolean;\n private _showSelectionIndicator: boolean;\n private _selectionIndicator: string;\n private _unselectedIndicator: string;\n private _wrapSelection: boolean;\n private _fastScrollStep: number;\n private _itemSpacing: number;\n private _keyBindings: SelectKeyBinding[];\n private _keyAliasMap: KeyAliasMap;\n private _keyBindingsMap: Map<string, SelectAction>;\n private _contentNodeId: number;\n private readonly _keyHandler: (key: KeyEvent) => void;\n\n protected _defaultOptions = {\n textColor: \"#e2e8f0\",\n focusedTextColor: \"#f7fafc\",\n selectedBackgroundColor: \"#3b82f6\",\n selectedTextColor: \"#ffffff\",\n descriptionColor: \"#94a3b8\",\n selectedDescriptionColor: \"#cbd5e1\",\n showScrollIndicator: false,\n showDescription: true,\n showSelectionIndicator: true,\n selectionIndicator: \"❯ \",\n unselectedIndicator: \" \",\n wrapSelection: false,\n fastScrollStep: 5,\n itemSpacing: 0,\n } satisfies Partial<SelectOptions>;\n\n constructor(renderer: CliRenderer, options: SelectOptions = {}) {\n _selectCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `select-${_selectCounter}`,\n focusable: true,\n overflow: \"hidden\",\n });\n\n this._selectOptions = options.options ?? [];\n this._selectedIndex = this._resolveInitialIndex(options.selectedIndex ?? 0);\n this._scrollOffset = 0;\n this._textColor = parseColor(options.textColor ?? this._defaultOptions.textColor);\n this._focusedTextColor = parseColor(\n options.focusedTextColor ?? this._defaultOptions.focusedTextColor,\n );\n this._selectedBgColor = parseColor(\n options.selectedBackgroundColor ?? this._defaultOptions.selectedBackgroundColor,\n );\n this._selectedTextColor = parseColor(\n options.selectedTextColor ?? this._defaultOptions.selectedTextColor,\n );\n this._descriptionColor = parseColor(\n options.descriptionColor ?? this._defaultOptions.descriptionColor,\n );\n this._selectedDescriptionColor = parseColor(\n options.selectedDescriptionColor ?? this._defaultOptions.selectedDescriptionColor,\n );\n this._showScrollIndicator =\n options.showScrollIndicator ?? this._defaultOptions.showScrollIndicator;\n this._showDescription = options.showDescription ?? this._defaultOptions.showDescription;\n this._showSelectionIndicator =\n options.showSelectionIndicator ?? this._defaultOptions.showSelectionIndicator;\n this._selectionIndicator =\n options.selectionIndicator ?? this._defaultOptions.selectionIndicator;\n this._unselectedIndicator =\n options.unselectedIndicator ?? this._defaultOptions.unselectedIndicator;\n this._wrapSelection = options.wrapSelection ?? this._defaultOptions.wrapSelection;\n this._fastScrollStep = options.fastScrollStep ?? this._defaultOptions.fastScrollStep;\n this._itemSpacing = options.itemSpacing ?? this._defaultOptions.itemSpacing;\n\n if (options.focusedBackgroundColor) {\n this._focusedBgColor = parseColor(options.focusedBackgroundColor);\n }\n\n this._keyAliasMap = mergeKeyAliases(defaultKeyAliases, options.keyAliasMap ?? {});\n this._keyBindings = options.keyBindings ?? [];\n this._keyBindingsMap = buildKeyBindingsMap(\n mergeKeyBindings(defaultSelectKeybindings, this._keyBindings),\n this._keyAliasMap,\n );\n\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n\n this._keyHandler = (key: KeyEvent) => {\n if (!this._focused || this._isDestroyed) return;\n if (this.handleKeyPress(key)) {\n key.stopPropagation();\n }\n };\n this._render();\n }\n\n // ── Getters/Setters ───────────────────────────────────────────────────────────\n\n get options(): SelectOption[] {\n return this._selectOptions;\n }\n\n set options(opts: SelectOption[]) {\n this._selectOptions = opts;\n if (opts.length === 0) {\n this._selectedIndex = 0;\n } else {\n const clamped = Math.min(this._selectedIndex, opts.length - 1);\n this._selectedIndex = this._skipNonSelectable(clamped, 1);\n }\n this._scrollOffset = 0;\n this._updateScroll();\n this._render();\n }\n\n get selectedIndex(): number {\n return this._selectedIndex;\n }\n\n set selectedIndex(idx: number) {\n if (this._selectOptions.length === 0) return;\n const clamped = this._clampIndex(idx);\n const validIndex = this._skipNonSelectable(clamped, idx >= this._selectedIndex ? 1 : -1);\n if (validIndex !== this._selectedIndex) {\n this._selectedIndex = validIndex;\n this._updateScroll();\n this._render();\n }\n }\n\n get showScrollIndicator(): boolean {\n return this._showScrollIndicator;\n }\n\n set showScrollIndicator(v: boolean) {\n if (this._showScrollIndicator !== v) {\n this._showScrollIndicator = v;\n this._render();\n }\n }\n\n get showDescription(): boolean {\n return this._showDescription;\n }\n\n set showDescription(v: boolean) {\n if (this._showDescription !== v) {\n this._showDescription = v;\n this._updateScroll();\n this._render();\n }\n }\n\n get wrapSelection(): boolean {\n return this._wrapSelection;\n }\n\n set wrapSelection(v: boolean) {\n if (this._wrapSelection !== v) {\n this._wrapSelection = v;\n this._render();\n }\n }\n\n get showSelectionIndicator(): boolean {\n return this._showSelectionIndicator;\n }\n\n set showSelectionIndicator(v: boolean) {\n if (this._showSelectionIndicator !== v) {\n this._showSelectionIndicator = v;\n this._render();\n }\n }\n\n get selectionIndicator(): string {\n return this._selectionIndicator;\n }\n\n set selectionIndicator(v: string) {\n if (this._selectionIndicator !== v) {\n this._selectionIndicator = v;\n this._render();\n }\n }\n\n get unselectedIndicator(): string {\n return this._unselectedIndicator;\n }\n\n set unselectedIndicator(v: string) {\n if (this._unselectedIndicator !== v) {\n this._unselectedIndicator = v;\n this._render();\n }\n }\n\n get fastScrollStep(): number {\n return this._fastScrollStep;\n }\n\n set fastScrollStep(v: number) {\n this._fastScrollStep = Math.max(1, Math.floor(v));\n }\n\n get focusedBackgroundColor(): RGBA | null {\n return this._focusedBgColor;\n }\n\n set focusedBackgroundColor(color: ColorInput) {\n this._focusedBgColor = parseColor(color);\n this._render();\n }\n\n set selectedBackgroundColor(color: ColorInput) {\n this._selectedBgColor = parseColor(color);\n this._render();\n }\n\n set textColor(color: ColorInput) {\n this._textColor = parseColor(color);\n this._render();\n }\n\n set selectedTextColor(color: ColorInput) {\n this._selectedTextColor = parseColor(color);\n this._render();\n }\n\n set focusedTextColor(color: ColorInput) {\n this._focusedTextColor = parseColor(color);\n this._render();\n }\n\n set descriptionColor(color: ColorInput) {\n this._descriptionColor = parseColor(color);\n this._render();\n }\n\n set selectedDescriptionColor(color: ColorInput) {\n this._selectedDescriptionColor = parseColor(color);\n this._render();\n }\n\n set keyBindings(bindings: SelectKeyBinding[]) {\n this._keyBindings = bindings;\n this._keyBindingsMap = buildKeyBindingsMap(\n mergeKeyBindings(defaultSelectKeybindings, bindings),\n this._keyAliasMap,\n );\n }\n\n set keyAliasMap(aliases: KeyAliasMap) {\n this._keyAliasMap = mergeKeyAliases(defaultKeyAliases, aliases);\n this._keyBindingsMap = buildKeyBindingsMap(\n mergeKeyBindings(defaultSelectKeybindings, this._keyBindings),\n this._keyAliasMap,\n );\n }\n\n // ── Methods ───────────────────────────────────────────────────────────────────\n\n getSelectedOption(): SelectOption | undefined {\n return this._selectOptions[this._selectedIndex];\n }\n\n getSelectedIndex(): number {\n return this._selectedIndex;\n }\n\n /** Programmatically move the selection; emits SELECTION_CHANGED on change. */\n setSelectedIndex(index: number): void {\n if (this._selectOptions.length === 0) return;\n const clamped = this._clampIndex(index);\n const validIndex = this._skipNonSelectable(clamped, index >= this._selectedIndex ? 1 : -1);\n if (validIndex !== this._selectedIndex) {\n this._selectedIndex = validIndex;\n this._updateScroll();\n this._render();\n const opt = this.getSelectedOption();\n if (opt) this.emit(SelectEvents.SELECTION_CHANGED, this._selectedIndex, opt);\n }\n }\n\n selectCurrent(): void {\n const opt = this.getSelectedOption();\n if (opt) {\n this.emit(SelectEvents.ITEM_SELECTED, this._selectedIndex, opt);\n }\n }\n\n moveUp(steps = 1): void {\n const prev = this._selectedIndex;\n let next = this._selectedIndex - steps;\n if (this._selectOptions.length === 0) return;\n if (this._wrapSelection) {\n next = this._wrapIndex(next);\n } else {\n next = Math.max(0, next);\n }\n next = this._skipNonSelectable(next, -1);\n if (next !== prev) {\n this._selectedIndex = next;\n this._updateScroll();\n this._render();\n const opt = this.getSelectedOption();\n if (opt) this.emit(SelectEvents.SELECTION_CHANGED, next, opt);\n }\n }\n\n moveDown(steps = 1): void {\n const prev = this._selectedIndex;\n let next = this._selectedIndex + steps;\n if (this._selectOptions.length === 0) return;\n if (this._wrapSelection) {\n next = this._wrapIndex(next);\n } else {\n next = Math.min(this._selectOptions.length - 1, next);\n }\n next = this._skipNonSelectable(next, 1);\n if (next !== prev) {\n this._selectedIndex = next;\n this._updateScroll();\n this._render();\n const opt = this.getSelectedOption();\n if (opt) this.emit(SelectEvents.SELECTION_CHANGED, next, opt);\n }\n }\n\n /**\n * Resolve a key event against the keybinding map and dispatch the action.\n * Returns `true` when the key was consumed.\n */\n handleKeyPress(key: KeyEvent): boolean {\n if (this._isDestroyed) return false;\n const action = getKeyBindingAction(this._keyBindingsMap, key);\n if (!action) return false;\n\n switch (action) {\n case \"move-up\":\n this.moveUp(1);\n break;\n case \"move-down\":\n this.moveDown(1);\n break;\n case \"move-up-fast\":\n this.moveUp(this._fastScrollStep);\n break;\n case \"move-down-fast\":\n this.moveDown(this._fastScrollStep);\n break;\n case \"move-up-page\":\n this.moveUp(this._fastScrollStep * 2);\n break;\n case \"move-down-page\":\n this.moveDown(this._fastScrollStep * 2);\n break;\n case \"move-to-start\":\n this.setSelectedIndex(0);\n break;\n case \"move-to-end\":\n this.setSelectedIndex(this._selectOptions.length - 1);\n break;\n case \"select-current\":\n this.selectCurrent();\n break;\n }\n\n return true;\n }\n\n // ── Focus ─────────────────────────────────────────────────────────────────────\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n this._render();\n this.emit(RenderableEvents.FOCUSED, this);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n this._focused = false;\n this._render();\n this.emit(RenderableEvents.BLURRED, this);\n }\n\n // ── Rendering ─────────────────────────────────────────────────────────────────\n\n private _resolveInitialIndex(requested: number): number {\n if (this._selectOptions.length === 0) return 0;\n const clamped = this._clampIndex(requested);\n return this._skipNonSelectable(clamped, 1, clamped);\n }\n\n private _clampIndex(idx: number): number {\n return Math.max(0, Math.min(this._selectOptions.length - 1, idx));\n }\n\n private _wrapIndex(idx: number): number {\n const len = this._selectOptions.length;\n if (len === 0) return 0;\n return ((idx % len) + len) % len;\n }\n\n private _isNonSelectable(index: number): boolean {\n const opt = this._selectOptions[index];\n if (!opt) return true;\n const kind = (opt.value as { kind?: string } | undefined)?.kind;\n return kind === \"spacer\" || kind === \"category\";\n }\n\n private _skipNonSelectable(index: number, direction: 1 | -1, fallback?: number): number {\n const len = this._selectOptions.length;\n const stayPut = fallback ?? this._selectedIndex;\n if (len === 0) return stayPut;\n let i = index;\n let attempts = 0;\n while (this._isNonSelectable(i) && attempts < len) {\n if (this._wrapSelection) {\n i = this._wrapIndex(i + direction);\n } else {\n i += direction;\n if (i < 0 || i >= len) {\n return stayPut;\n }\n }\n attempts++;\n }\n return attempts >= len ? stayPut : i;\n }\n\n /** Number of rendered rows a single option occupies. */\n private _linesPerItem(index: number): number {\n const opt = this._selectOptions[index];\n if (!opt) return 1;\n const kind = (opt.value as { kind?: string } | undefined)?.kind;\n if (kind === \"spacer\" || kind === \"category\") return 1;\n return (this._showDescription && opt.description ? 2 : 1) + this._itemSpacing;\n }\n\n private _updateScroll(): void {\n if (this._selectOptions.length === 0) return;\n\n const viewHeight = this._getViewHeight();\n this._selectedIndex = Math.max(\n 0,\n Math.min(this._selectOptions.length - 1, this._selectedIndex),\n );\n this._selectedIndex = this._skipNonSelectable(this._selectedIndex, 1);\n\n if (this._selectedIndex < this._scrollOffset) {\n let targetOffset = this._selectedIndex;\n while (targetOffset > 0 && this._isNonSelectable(targetOffset - 1)) {\n targetOffset--;\n }\n this._scrollOffset = targetOffset;\n return;\n }\n\n let linesUsed = 0;\n for (let i = this._scrollOffset; i <= this._selectedIndex; i++) {\n linesUsed += this._linesPerItem(i);\n }\n\n while (linesUsed > viewHeight && this._scrollOffset < this._selectedIndex) {\n linesUsed -= this._linesPerItem(this._scrollOffset);\n this._scrollOffset++;\n }\n }\n\n private _getViewHeight(): number {\n const h = this._options.height;\n if (typeof h === \"number\") return h;\n\n let available = this._renderer.viewportHeight;\n\n if (this._options.border) {\n available -= 2;\n }\n if (typeof this._options.marginTop === \"number\") available -= this._options.marginTop;\n if (typeof this._options.marginBottom === \"number\") available -= this._options.marginBottom;\n\n let current: Box | null = this._parent;\n while (current) {\n const opts = current.boxOptions;\n if (typeof opts.height === \"number\") {\n available = Math.min(available, opts.height);\n }\n\n if (opts.border) {\n available -= 2;\n }\n\n if (typeof opts.padding === \"number\") {\n available -= opts.padding * 2;\n } else {\n if (typeof opts.paddingTop === \"number\") available -= opts.paddingTop;\n if (typeof opts.paddingBottom === \"number\") available -= opts.paddingBottom;\n }\n\n if (typeof opts.margin === \"number\") {\n available -= opts.margin * 2;\n } else {\n if (typeof opts.marginTop === \"number\") available -= opts.marginTop;\n if (typeof opts.marginBottom === \"number\") available -= opts.marginBottom;\n }\n\n const dir = opts.flexDirection ?? \"column\";\n if (dir === \"column\") {\n for (const child of current.getChildren()) {\n if (child === this || child.getRenderable(this.id)) continue;\n if (!child.boxOptions.flexGrow) {\n available -= child.getEstimatedHeight();\n }\n }\n }\n\n current = current.parent;\n }\n\n return Math.max(3, available);\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n\n const viewHeight = this._getViewHeight();\n const totalItems = this._selectOptions.length;\n\n let totalContentLines = 0;\n for (let i = 0; i < totalItems; i++) {\n totalContentLines += this._linesPerItem(i);\n }\n\n this._scrollOffset = Math.max(0, Math.min(this._scrollOffset, Math.max(0, totalItems - 1)));\n\n const rawLines: {\n text: string;\n bg?: string;\n fg: string;\n isCategory?: boolean;\n }[] = [];\n let currIdx = this._scrollOffset;\n\n while (currIdx < totalItems && rawLines.length < viewHeight) {\n const opt = this._selectOptions[currIdx];\n if (!opt) {\n currIdx++;\n continue;\n }\n\n const kind = (opt.value as { kind?: string } | undefined)?.kind;\n if (kind === \"spacer\") {\n rawLines.push({\n text: \"\",\n fg: \"0;0;0\",\n bg: this._focused && this._focusedBgColor ? this._ansi(this._focusedBgColor) : undefined,\n });\n currIdx++;\n continue;\n }\n\n if (kind === \"category\") {\n const catColor = `${this._textColor.r};${this._textColor.g};${this._textColor.b}`;\n rawLines.push({\n text: opt.name,\n fg: catColor,\n isCategory: true,\n bg: this._focused && this._focusedBgColor ? this._ansi(this._focusedBgColor) : undefined,\n });\n currIdx++;\n continue;\n }\n\n const isSelected = currIdx === this._selectedIndex;\n const textColor = isSelected\n ? this._selectedTextColor\n : this._focused\n ? this._focusedTextColor\n : this._textColor;\n\n const tc = `${textColor.r};${textColor.g};${textColor.b}`;\n const indicator = this._showSelectionIndicator\n ? isSelected\n ? this._selectionIndicator\n : this._unselectedIndicator\n : \"\";\n\n const bg = isSelected\n ? this._ansi(this._selectedBgColor)\n : this._focused && this._focusedBgColor\n ? this._ansi(this._focusedBgColor)\n : undefined;\n\n rawLines.push({ text: indicator + opt.name, bg, fg: tc });\n\n if (this._showDescription && opt.description && rawLines.length < viewHeight) {\n const descColor = isSelected ? this._selectedDescriptionColor : this._descriptionColor;\n const dc = `${descColor.r};${descColor.g};${descColor.b}`;\n const trimmedDesc = opt.description.trimEnd();\n if (trimmedDesc) {\n const descIndent = this._showSelectionIndicator\n ? \" \".repeat(Select.displayWidth(indicator))\n : \"\";\n rawLines.push({ text: `${descIndent}${trimmedDesc}`, bg, fg: dc });\n }\n }\n\n for (let s = 0; s < this._itemSpacing && rawLines.length < viewHeight; s++) {\n rawLines.push({ text: \"\", bg, fg: \"0;0;0\" });\n }\n\n currIdx++;\n }\n\n const hasScrollbar = this._showScrollIndicator && totalContentLines > viewHeight;\n const rowWidth = Math.max(40, this._renderer.terminalWidth - 4);\n const contentWidth = hasScrollbar ? rowWidth - 1 : rowWidth;\n\n const trackHeight = viewHeight;\n const visibleRatio = Math.min(1, viewHeight / Math.max(1, totalContentLines));\n const thumbSize = Math.max(1, Math.round(visibleRatio * trackHeight));\n const maxThumbPos = Math.max(0, trackHeight - thumbSize);\n\n let linesBeforeScrollOffset = 0;\n for (let i = 0; i < this._scrollOffset; i++) {\n linesBeforeScrollOffset += this._linesPerItem(i);\n }\n\n const maxScrollableLines = Math.max(1, totalContentLines - viewHeight);\n const scrollRatio = Math.min(1, Math.max(0, linesBeforeScrollOffset / maxScrollableLines));\n const thumbPos = Math.min(maxThumbPos, Math.round(scrollRatio * maxThumbPos));\n\n const lines: string[] = [];\n\n for (let lineIdx = 0; lineIdx < viewHeight; lineIdx++) {\n const item = rawLines[lineIdx];\n let lineText = \"\";\n\n if (item) {\n if (item.isCategory) {\n if (item.bg) {\n lineText = `\\x1b[48;2;${item.bg}m\\x1b[1;38;2;${item.fg}m${item.text.padEnd(contentWidth)}\\x1b[0m`;\n } else {\n lineText = `\\x1b[1;38;2;${item.fg}m${item.text.padEnd(contentWidth)}\\x1b[0m`;\n }\n } else if (item.bg) {\n lineText = `\\x1b[48;2;${item.bg}m\\x1b[38;2;${item.fg}m${item.text.padEnd(contentWidth)}\\x1b[0m`;\n } else {\n lineText = `\\x1b[38;2;${item.fg}m${item.text.padEnd(contentWidth)}\\x1b[0m`;\n }\n } else {\n lineText = \"\".padEnd(contentWidth);\n }\n\n if (hasScrollbar) {\n const isThumb = lineIdx >= thumbPos && lineIdx < thumbPos + thumbSize;\n if (isThumb) {\n const thumbFg = `${this._descriptionColor.r};${this._descriptionColor.g};${this._descriptionColor.b}`;\n lineText += `\\x1b[38;2;${thumbFg}m█\\x1b[0m`;\n } else {\n lineText += \" \";\n }\n }\n\n lines.push(lineText);\n }\n\n this._renderer.setText(this._contentNodeId, lines.join(\"\\n\"));\n }\n\n private _ansi(color: RGBA): string {\n return `${color.r};${color.g};${color.b}`;\n }\n\n private static displayWidth(text: string): number {\n let width = 0;\n for (const char of text) {\n const cp = char.codePointAt(0);\n if (cp === undefined) continue;\n if (\n (cp >= 0x1100 && cp <= 0x115f) ||\n (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||\n (cp >= 0xac00 && cp <= 0xd7a3) ||\n (cp >= 0xf900 && cp <= 0xfaff) ||\n (cp >= 0xfe10 && cp <= 0xfe19) ||\n (cp >= 0xfe30 && cp <= 0xfe6f) ||\n (cp >= 0xff01 && cp <= 0xff60) ||\n (cp >= 0xffe0 && cp <= 0xffe6) ||\n (cp >= 0x20000 && cp <= 0x2fffd) ||\n (cp >= 0x30000 && cp <= 0x3fffd)\n ) {\n width += 2;\n } else {\n width += 1;\n }\n }\n return width;\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n}\n\nexport { SelectEvents };\n","","","","","","","","import block from \"./fonts/block.json\" with { type: \"json\" };\nimport grid from \"./fonts/grid.json\" with { type: \"json\" };\nimport huge from \"./fonts/huge.json\" with { type: \"json\" };\nimport pallet from \"./fonts/pallet.json\" with { type: \"json\" };\nimport shade from \"./fonts/shade.json\" with { type: \"json\" };\nimport slick from \"./fonts/slick.json\" with { type: \"json\" };\nimport tiny from \"./fonts/tiny.json\" with { type: \"json\" };\nimport { type ColorInput, parseColor } from \"./rgba\";\n\nexport type ASCIIFontName =\n | \"tiny\"\n | \"block\"\n | \"shade\"\n | \"slick\"\n | \"huge\"\n | \"grid\"\n | \"pallet\"\n | string;\n\ntype FontSegment = {\n text: string;\n colorIndex: number;\n};\n\ntype FontDefinition = {\n name: string;\n lines: number;\n letterspace_size: number;\n letterspace: string[];\n colors?: number;\n chars: Record<string, string[]>;\n};\n\ntype ParsedFontDefinition = {\n name: string;\n lines: number;\n letterspace_size: number;\n letterspace: string[];\n colors: number;\n chars: Record<string, FontSegment[][]>;\n};\n\nexport const fonts: Record<string, FontDefinition> = {\n tiny: tiny as unknown as FontDefinition,\n block: block as unknown as FontDefinition,\n shade: shade as unknown as FontDefinition,\n slick: slick as unknown as FontDefinition,\n huge: huge as unknown as FontDefinition,\n grid: grid as unknown as FontDefinition,\n pallet: pallet as unknown as FontDefinition,\n};\n\nconst parsedFonts: Record<string, ParsedFontDefinition> = {};\n\nfunction parseColorTags(text: string): FontSegment[] {\n const segments: FontSegment[] = [];\n const colorTagRegex = /<c(\\d+)>(.*?)<\\/c\\d+>/g;\n let lastIndex = 0;\n\n for (const match of text.matchAll(colorTagRegex)) {\n const matchIndex = match.index ?? 0;\n if (matchIndex > lastIndex) {\n const plainText = text.slice(lastIndex, matchIndex);\n if (plainText) {\n segments.push({ text: plainText, colorIndex: 0 });\n }\n }\n\n const colorStr = match[1];\n const taggedText = match[2] ?? \"\";\n const colorIndex = colorStr ? Number.parseInt(colorStr, 10) - 1 : 0;\n segments.push({ text: taggedText, colorIndex: Math.max(0, colorIndex) });\n\n lastIndex = matchIndex + match[0].length;\n }\n\n if (lastIndex < text.length) {\n const remainingText = text.slice(lastIndex);\n if (remainingText) {\n segments.push({ text: remainingText, colorIndex: 0 });\n }\n }\n\n return segments;\n}\n\nfunction getParsedFont(fontKey: string): ParsedFontDefinition | null {\n const key = fontKey.toLowerCase();\n const fontDef = fonts[key];\n if (!fontDef) return null;\n\n let parsed = parsedFonts[key];\n if (!parsed) {\n const parsedChars: Record<string, FontSegment[][]> = {};\n\n for (const [char, lines] of Object.entries(fontDef.chars)) {\n parsedChars[char] = lines.map((line) => parseColorTags(line));\n }\n\n parsed = {\n ...fontDef,\n colors: fontDef.colors || 1,\n chars: parsedChars,\n };\n parsedFonts[key] = parsed;\n }\n\n return parsed;\n}\n\nexport function measureFontText(text: string, font = \"tiny\"): { width: number; height: number } {\n const fontDef = getParsedFont(font);\n if (!fontDef) {\n return { width: text.length, height: 1 };\n }\n\n let currentX = 0;\n\n for (let i = 0; i < text.length; i++) {\n const char = text[i]?.toUpperCase() ?? \"\";\n const charDef = fontDef.chars[char];\n\n if (!charDef) {\n const spaceChar = fontDef.chars[\" \"];\n if (spaceChar?.[0]) {\n let spaceWidth = 0;\n for (const segment of spaceChar[0]) {\n spaceWidth += segment.text.length;\n }\n currentX += spaceWidth;\n } else {\n currentX += 1;\n }\n } else {\n let charWidth = 0;\n if (charDef[0]) {\n for (const segment of charDef[0]) {\n charWidth += segment.text.length;\n }\n }\n currentX += charWidth;\n }\n\n if (i < text.length - 1) {\n currentX += fontDef.letterspace_size;\n }\n }\n\n return {\n width: currentX,\n height: fontDef.lines,\n };\n}\n\nexport function renderFontToText(\n text: string,\n font = \"tiny\",\n color?: ColorInput | ColorInput[],\n): string {\n const fontDef = getParsedFont(font);\n if (!fontDef) return text;\n\n const colors = Array.isArray(color) ? color : [color ?? \"#FFFFFF\"];\n const parsedColors = colors.map((c) => parseColor(c));\n\n const lineOutputs: string[] = Array.from({ length: fontDef.lines }, () => \"\");\n\n for (let i = 0; i < text.length; i++) {\n const char = text[i]?.toUpperCase() ?? \"\";\n const charDef = fontDef.chars[char];\n\n if (!charDef) {\n const spaceChar = fontDef.chars[\" \"];\n let spaceWidth = 0;\n if (spaceChar?.[0]) {\n for (const segment of spaceChar[0]) {\n spaceWidth += segment.text.length;\n }\n } else {\n spaceWidth = 1;\n }\n for (let l = 0; l < fontDef.lines; l++) {\n lineOutputs[l] += \" \".repeat(spaceWidth);\n }\n } else {\n for (let l = 0; l < fontDef.lines; l++) {\n const segments = charDef[l] ?? [];\n for (const segment of segments) {\n const c = parsedColors[segment.colorIndex] ??\n parsedColors[0] ?? {\n r: 255,\n g: 255,\n b: 255,\n a: 255,\n };\n lineOutputs[l] += `\\x1b[38;2;${c.r};${c.g};${c.b}m${segment.text}\\x1b[0m`;\n }\n }\n }\n\n if (i < text.length - 1) {\n for (let l = 0; l < fontDef.lines; l++) {\n lineOutputs[l] += \" \".repeat(fontDef.letterspace_size);\n }\n }\n }\n\n return lineOutputs.join(\"\\n\");\n}\n","/**\n * TextNode — building block for styled text composition.\n *\n * Design:\n * - Children are `string | TextNode` (heterogeneous).\n * - Leaf text is stored as a string child, NOT a separate `_text` field.\n * This means `clear()` always wipes all content and `children` setter\n * works correctly for dynamic updates.\n * - `fromNodes(nodes[], options?)` takes array + options signature.\n * - `children` setter re-parents the new children and marks the node dirty.\n */\n\nimport { type ColorInput, type RGBA, parseColor } from \"../lib/rgba\";\nimport { type StyledText, type TextChunk, styledTextToAnsi } from \"../lib/styledText\";\nimport { TextAttributes } from \"../lib/styledText\";\nimport { StyledText as StyledTextClass } from \"../lib/styledText\";\n\nexport interface TextNodeOptions {\n id?: string;\n fg?: ColorInput;\n bg?: ColorInput;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n dim?: boolean;\n strikethrough?: boolean;\n blink?: boolean;\n}\n\nexport interface StyleAttrs {\n fg?: ColorInput;\n bg?: ColorInput;\n /** Pre-computed attribute bitmask (TextAttributes flags). */\n attributes?: number;\n}\n\n/** A child can be either a string (leaf text) or a nested node. */\nexport type TextNodeChild = string | TextNode;\n\nlet _textNodeCounter = 0;\n\n/**\n * TextNode — a lightweight styled-text composition node.\n * Can be used standalone or nested in Text.\n */\nexport class TextNode {\n private static _counter = 0;\n public readonly id: string;\n public _fg: RGBA | undefined;\n public _bg: RGBA | undefined;\n public _attributes: number;\n public isDirty = false;\n public parent: TextNode | null = null;\n\n /**\n * Children are heterogeneous: strings are leaf text, TextNodeRenderables are\n * nested nodes. Stored as a union array.\n *\n * NOTE: Do NOT store leaf text in a separate field — always use children.\n * This ensures `clear()` wipes everything and the `children` setter works.\n */\n protected _children: TextNodeChild[] = [];\n\n constructor(options: TextNodeOptions = {}) {\n _textNodeCounter++;\n this.id = options.id ?? `textnode-${_textNodeCounter}`;\n this._fg = options.fg ? parseColor(options.fg) : undefined;\n this._bg = options.bg ? parseColor(options.bg) : undefined;\n this._attributes = 0;\n if (options.bold) this._attributes |= TextAttributes.BOLD;\n if (options.italic) this._attributes |= TextAttributes.ITALIC;\n if (options.underline) this._attributes |= TextAttributes.UNDERLINE;\n if (options.dim) this._attributes |= TextAttributes.DIM;\n if (options.strikethrough) this._attributes |= TextAttributes.STRIKETHROUGH;\n if (options.blink) this._attributes |= TextAttributes.BLINK;\n }\n\n // ── Factory methods ────────────────────────────────────────────────────────\n\n /**\n * Create a leaf node from a plain string with optional style.\n * Signature: `TextNode.fromString(text, options?)`.\n */\n static fromString(text: string, style?: StyleAttrs): TextNode {\n const node = new TextNode({\n fg: style?.fg,\n bg: style?.bg,\n });\n if (style?.attributes) node._attributes = style.attributes;\n // Store as a string child — this is the canonical storage location.\n node._children = [text];\n return node;\n }\n\n /**\n * Create a container node from an array of child nodes with optional root style.\n * Signature: `fromNodes(nodes: TextNode[], options?)`.\n *\n * Previous implementation used variadic rest params and no options,\n * which broke call sites that pass `([a,b,c], { fg: \"...\" })`.\n */\n static fromNodes(nodes: TextNode[], options: StyleAttrs = {}): TextNode {\n const root = new TextNode({\n fg: options.fg,\n bg: options.bg,\n });\n if (options.attributes) root._attributes = options.attributes;\n for (const node of nodes) root.add(node);\n return root;\n }\n\n // ── Style getters / setters ────────────────────────────────────────────────\n\n get fg(): RGBA | undefined {\n return this._fg;\n }\n\n set fg(color: ColorInput) {\n this._fg = parseColor(color);\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n get bg(): RGBA | undefined {\n return this._bg;\n }\n\n set bg(color: ColorInput) {\n this._bg = parseColor(color);\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n get attributes(): number {\n return this._attributes;\n }\n\n set attributes(v: number) {\n this._attributes = v;\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n // ── Children ──────────────────────────────────────────────────────────────\n\n /**\n * Read-only view of this node's children (strings + sub-nodes).\n * For mutation use the setter or `add`/`remove`/`clear`.\n */\n get children(): readonly TextNodeChild[] {\n return this._children;\n }\n\n /**\n * Replace all children with a new array of strings and/or nodes.\n * The `children` setter: detaches old node children, adopts\n * new ones, and marks the node dirty so the owner Text resyncs.\n *\n * Usage (dynamic update pattern):\n * ```ts\n * counterNode.children = [`\\n\\nCounter: ${n}`];\n * ```\n */\n set children(newChildren: TextNodeChild[]) {\n // Detach old node children\n for (const child of this._children) {\n if (child instanceof TextNode) {\n child.parent = null;\n }\n }\n // Adopt new node children\n for (const child of newChildren) {\n if (child instanceof TextNode) {\n child.parent = this;\n }\n }\n this._children = [...newChildren];\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n // ── Mutation methods ───────────────────────────────────────────────────────\n\n /**\n * Append a string, TextNode, or StyledText as a child.\n * Returns the index at which the child was inserted.\n */\n add(child: TextNodeChild | StyledText, index?: number): number {\n let item: TextNodeChild;\n if (typeof child === \"string\") {\n item = child;\n } else if (child instanceof TextNode) {\n child.parent = this;\n item = child;\n } else {\n // StyledText — serialise to ANSI string and store as a leaf string child\n item = styledTextToAnsi(child as StyledText);\n }\n\n if (index !== undefined) {\n this._children.splice(index, 0, item);\n } else {\n this._children.push(item);\n }\n this.isDirty = true;\n this._bubbleDirty();\n return index ?? this._children.length - 1;\n }\n\n remove(child: TextNode): void {\n const idx = this._children.indexOf(child);\n if (idx !== -1) {\n this._children.splice(idx, 1);\n child.parent = null;\n this.isDirty = true;\n this._bubbleDirty();\n }\n }\n\n /**\n * Insert `child` before `anchor`. Throws if `anchor` is provided but not\n * found — strict contract (helps catch anchor mismatches).\n */\n insertBefore(child: TextNodeChild | StyledText, anchor?: TextNode): void {\n const item =\n typeof child === \"string\" || child instanceof TextNode\n ? child\n : styledTextToAnsi(child as StyledText);\n\n if (!anchor) {\n this._children.unshift(item);\n } else {\n const idx = this._children.indexOf(anchor);\n if (idx === -1) {\n throw new Error(\n `[TextNode] insertBefore: anchor node (id=${anchor.id}) not found among children`,\n );\n }\n this._children.splice(idx, 0, item);\n }\n if (item instanceof TextNode) item.parent = this;\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n /**\n * Remove all children and mark the node dirty.\n * Unlike the old implementation there is NO separate `_text` field to miss.\n */\n clear(): void {\n for (const child of this._children) {\n if (child instanceof TextNode) {\n child.parent = null;\n }\n }\n this._children = [];\n this.isDirty = true;\n this._bubbleDirty();\n }\n\n getChildren(): readonly TextNodeChild[] {\n return this._children;\n }\n\n // ── Rendering helpers ─────────────────────────────────────────────────────\n\n /**\n * Walk this node and all descendants, accumulating {@link TextChunk}s with\n * inherited style applied. Called by `Text.onLifecyclePass` to\n * build the flat chunk array that goes to the engine.\n */\n gatherWithInheritedStyle(inherited: {\n fg?: RGBA;\n bg?: RGBA;\n attributes?: number;\n link?: { url: string } | undefined;\n }): TextChunk[] {\n const chunks: TextChunk[] = [];\n\n const fg = this._fg ?? inherited.fg;\n const bg = this._bg ?? inherited.bg;\n const attrs = this._attributes\n ? (inherited.attributes ?? 0) | this._attributes\n : inherited.attributes;\n\n for (const child of this._children) {\n if (typeof child === \"string\") {\n // Leaf string child — emit as a chunk with current inherited style\n if (child) {\n chunks.push({\n __isChunk: true,\n text: child,\n fg,\n bg,\n attributes: attrs,\n });\n }\n } else {\n // Nested node — recurse\n chunks.push(\n ...child.gatherWithInheritedStyle({\n fg,\n bg,\n attributes: attrs,\n link: inherited.link,\n }),\n );\n }\n }\n\n return chunks;\n }\n\n /** Serialise this node tree to an ANSI-escaped string. */\n toString(): string {\n const chunks = this.gatherWithInheritedStyle({});\n const st = new StyledTextClass(chunks);\n return styledTextToAnsi(st);\n }\n\n // ── Internal ──────────────────────────────────────────────────────────────\n\n /** Walk up the parent chain and mark all ancestors dirty. */\n private _bubbleDirty(): void {\n let p = this.parent;\n while (p) {\n p.isDirty = true;\n // If we reach a RootTextNode, notify it so it can signal its\n // owning Text to resync on the next lifecycle pass.\n if (p instanceof RootTextNode) {\n p.markDirtyFromChild();\n break;\n }\n p = p.parent;\n }\n }\n}\n\n/**\n * RootTextNode — the root text node for a Text.\n * When any descendant calls `_bubbleDirty()` and the dirty flag reaches this\n * root, the `onDirty` callback is invoked so the owning `Text` can\n * schedule a re-sync to the engine on the next lifecycle pass.\n */\nexport class RootTextNode extends TextNode {\n private readonly _onDirty: (() => void) | undefined;\n\n constructor(options: TextNodeOptions = {}, onDirty?: () => void) {\n super(options);\n this._onDirty = onDirty;\n }\n\n /**\n * Overrides the private `_bubbleDirty` propagation: when this root is\n * reached, fire the `onDirty` callback instead of (or in addition to)\n * walking further up (there is no parent above the root).\n */\n markDirtyFromChild(): void {\n this.isDirty = true;\n this._onDirty?.();\n }\n}\n","/**\n * Text — displays styled text content backed by a TextNode tree.\n *\n * Architecture:\n * - Owns a `RootTextNode` that acts as the root of a composable\n * styled-text tree.\n * - `add(node)` attaches a TextNode to the root\n * (`demoText.add(containerNode)` API — no ANSI round-trip workaround needed).\n * - `onLifecyclePass()` is called once per frame by the `CliRenderer` lifecycle\n * loop; it checks `rootTextNode.isDirty`, gathers chunks, serialises to ANSI,\n * and pushes to the engine. This enables the dynamic-update pattern:\n * ```ts\n * counterNode.children = [`Counter: ${n}`];\n * // ↑ marks the tree dirty; no manual re-serialisation required.\n * ```\n * - `content` (string / StyledText) setter is kept for backward-compatibility.\n * - The previous ANSI-flatten-on-every-setter approach is replaced: mutations\n * to the node tree are deferred to the lifecycle pass (O(1) dirty-check, not\n * O(n) serialise-on-every-frame).\n */\n\nimport { type ColorInput, type RGBA, parseColor, rgbaToEngineColor } from \"../lib/rgba\";\nimport { StyledText, styledTextToAnsi } from \"../lib/styledText\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\nimport { RootTextNode, type TextNode } from \"./TextNode\";\n\nexport interface TextOptions extends BoxOptions {\n content?: StyledText | string;\n /** Foreground (text) color. */\n fg?: ColorInput;\n /** Background color (alias for backgroundColor). */\n bg?: ColorInput;\n /** Text wrap mode. */\n wrapMode?: \"none\" | \"char\" | \"word\";\n /** Truncate long lines with ellipsis. */\n truncate?: boolean;\n /** Text alignment. */\n textAlign?: \"left\" | \"center\" | \"right\";\n margin?: number;\n /** Enable text selection. */\n selectable?: boolean;\n /** Selection background color. */\n selectionBg?: ColorInput;\n /** Selection foreground color. */\n selectionFg?: ColorInput;\n}\n\nlet _textCounter = 0;\n\nexport class Text extends Box {\n private _fg: RGBA | null = null;\n private _bg: RGBA | null = null;\n private _textNodeId: number;\n private _wrapMode: \"none\" | \"char\" | \"word\";\n private _truncate: boolean;\n\n /**\n * The root of the TextNode tree. All structured text attached via `add()`\n * lives here. The lifecycle pass reads `isDirty` and, when true, gathers\n * chunks from this tree and pushes them to the engine.\n */\n public readonly rootTextNode: RootTextNode;\n\n /**\n * Bound lifecycle pass function, registered with the renderer so it is\n * invoked once per frame. Kept as an arrow function so `unregister` works\n * correctly on cleanup.\n */\n private readonly _lifecyclePassFn: () => void;\n\n constructor(renderer: CliRenderer, options: TextOptions = {}) {\n _textCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `text-${_textCounter}`,\n backgroundColor: options.bg ?? options.backgroundColor,\n });\n\n if (options.fg) this._fg = parseColor(options.fg);\n if (options.bg) this._bg = parseColor(options.bg);\n this._wrapMode = options.wrapMode ?? \"none\";\n this._truncate = options.truncate ?? false;\n\n // Create the inner Text node in the engine\n this._textNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._textNodeId);\n\n // Create the root text node — marks itself dirty on any descendant change\n this.rootTextNode = new RootTextNode({}, () => {\n // This callback fires when ANY descendant mutates; the lifecycle pass\n // will handle the actual re-push to the engine.\n });\n\n // Seed the root with the initial content option (if any)\n const raw = options.content ?? \"\";\n const initial = typeof raw === \"string\" ? raw : styledTextToAnsi(raw as StyledText);\n if (initial) {\n this.rootTextNode.add(initial);\n }\n\n this._applyTextStyle(options);\n this._syncToEngine();\n\n // Register per-frame lifecycle pass so dirty-tree mutations auto-sync\n this._lifecyclePassFn = () => this.onLifecyclePass();\n renderer.registerLifecyclePass(this._lifecyclePassFn);\n }\n\n // ── Content API ───────────────────────────────────────────────────────────\n\n /**\n * Attach a TextNode to the root text node.\n *\n * This is the canonical BetterTUI API (`demoText.add(containerNode)`).\n *\n * NOTE: Named `addNode` rather than `add` because `Text` extends\n * `Box` whose `add(Box)` has a different signature.\n */\n addNode(node: TextNode, index?: number): void {\n this.rootTextNode.add(node, index);\n // isDirty is propagated through the tree; lifecycle pass will sync.\n }\n\n /**\n * Convenience: remove a previously added TextNode from the root.\n */\n removeNode(node: TextNode): void {\n this.rootTextNode.remove(node);\n }\n\n /**\n * `content` setter — accepts a plain string or StyledText.\n * Replaces all children of the root text node with a single string child.\n * Kept for backward-compatibility with code that does `text.content = \"...\"`.\n */\n get content(): string {\n const chunks = this.rootTextNode.gatherWithInheritedStyle({});\n if (chunks.length === 0) return \"\";\n return styledTextToAnsi(new StyledText(chunks));\n }\n\n set content(value: StyledText | string | string[]) {\n const normalised = Array.isArray(value) ? value.join(\"\\n\") : value;\n const text =\n normalised instanceof StyledText ? styledTextToAnsi(normalised) : String(normalised);\n this.rootTextNode.clear();\n if (text) {\n this.rootTextNode.add(text);\n }\n // Sync immediately so single-assignment renders without waiting a frame\n this._syncToEngine();\n }\n\n /** Clear all text content (clears the root node tree). */\n clear(): void {\n this.rootTextNode.clear();\n this._syncToEngine();\n }\n\n // ── Style API ─────────────────────────────────────────────────────────────\n\n get wrapMode(): \"none\" | \"char\" | \"word\" {\n return this._wrapMode;\n }\n\n set wrapMode(value: \"none\" | \"char\" | \"word\") {\n this._wrapMode = value;\n this._applyTextStyle({ wrapMode: value });\n }\n\n get truncate(): boolean {\n return this._truncate;\n }\n\n set truncate(value: boolean) {\n this._truncate = value;\n const styleJson: Record<string, unknown> = { text_truncate: value };\n // biome-ignore lint/suspicious/noExplicitAny: engine accepts extended style JSON\n this._renderer.setNodeStyle(this._textNodeId, styleJson as any);\n }\n\n get fg(): RGBA | null {\n return this._fg;\n }\n\n set fg(color: ColorInput) {\n this._fg = parseColor(color);\n this._applyTextStyle({});\n }\n\n set bg(color: ColorInput) {\n this._bg = parseColor(color);\n this._applyTextStyle({});\n this.backgroundColor = color;\n }\n\n set textColor(color: ColorInput) {\n this.fg = color;\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────\n\n /**\n * Called once per frame by the CliRenderer lifecycle loop.\n * Checks whether the root text node is dirty; if so, re-gathers all chunks\n * from the node tree and pushes the new ANSI string to the engine.\n *\n * This is the mechanism behind BetterTUI's \"mutate a node → auto-update\"\n * pattern.\n */\n onLifecyclePass(): void {\n if (!this.rootTextNode.isDirty) return;\n if (this._isDestroyed) return;\n this._syncToEngine();\n this.rootTextNode.isDirty = false;\n }\n\n // ── Cleanup ───────────────────────────────────────────────────────────────\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.unregisterLifecyclePass(this._lifecyclePassFn);\n try {\n this._renderer.removeNode(this._textNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n\n // ── Internal ──────────────────────────────────────────────────────────────\n\n /** Push the current node-tree content to the engine as an ANSI string. */\n private _syncToEngine(): void {\n if (this._isDestroyed) return;\n const chunks = this.rootTextNode.gatherWithInheritedStyle({\n fg: this._fg ?? undefined,\n bg: this._bg ?? undefined,\n });\n const ansi = styledTextToAnsi(new StyledText(chunks));\n this._renderer.setText(this._textNodeId, ansi);\n }\n\n private _applyTextStyle(options: Partial<TextOptions>): void {\n const styleJson: Record<string, unknown> = {};\n if (this._fg) styleJson.fg = rgbaToEngineColor(this._fg);\n if (this._bg) styleJson.bg = rgbaToEngineColor(this._bg);\n if (options.textAlign) styleJson.text_align = options.textAlign;\n const wm = options.wrapMode ?? this._wrapMode;\n if (wm) styleJson.text_wrap = wm !== \"none\";\n // biome-ignore lint/suspicious/noExplicitAny: engine accepts extended style JSON\n this._renderer.setNodeStyle(this._textNodeId, styleJson as any);\n }\n}\n","/**\n * Stub renderables for features that require complex implementation.\n * These provide type-correct APIs that compile, with simplified functionality.\n */\n\nimport { renderFontToText } from \"../lib/asciiFont\";\nimport { type ColorInput, RGBA, parseColor } from \"../lib/rgba\";\nimport type { StyledText, TextChunk } from \"../lib/styledText\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { type BorderStyleKind, Box, type BoxOptions } from \"./Box\";\nimport { Text, type TextOptions } from \"./Text\";\n\n// ── ASCIIFont ─────────────────────────────────────────────────────────────────\n\nexport type ASCIIFontKind = \"tiny\" | \"block\" | \"shade\" | \"slick\" | string;\n\nexport interface ASCIIFontOptions extends BoxOptions {\n text?: string;\n font?: ASCIIFontKind;\n color?: ColorInput | ColorInput[];\n backgroundColor?: ColorInput;\n selectionBg?: ColorInput;\n selectionFg?: ColorInput;\n}\n\nlet _asciiCounter = 0;\n\nexport class ASCIIFont extends Box {\n private _text: string;\n private _font: ASCIIFontKind;\n private _color: RGBA[];\n private _contentNodeId: number;\n\n // ASCII art maps for tiny font (simple 3-char-wide)\n private static readonly TINY_CHARS: Record<string, string> = {\n \" \": \" \\n \\n \",\n A: \" A \\n/ \\\\\\nA_A\",\n B: \"B_ \\nB_|\\nB_/\",\n C: \" _C\\n C \\n_C/\",\n \"0\": \"_0_\\n0 0\\n0_0\",\n \"1\": \"_1 \\n 1 \\n_1_\",\n };\n\n constructor(renderer: CliRenderer, options: ASCIIFontOptions = {}) {\n _asciiCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `asciifont-${_asciiCounter}`,\n });\n\n this._text = options.text ?? \"\";\n this._font = options.font ?? \"block\";\n const rawColor = options.color;\n const toRGBA = (c: ColorInput): RGBA =>\n c !== null && typeof c === \"object\" && \"r\" in c ? c : parseColor(c);\n this._color = Array.isArray(rawColor)\n ? rawColor.map(toRGBA)\n : rawColor\n ? [toRGBA(rawColor)]\n : [{ r: 255, g: 255, b: 255, a: 255 }];\n\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n this._render();\n }\n\n get text(): string {\n return this._text;\n }\n\n set text(v: string) {\n this._text = v;\n this._render();\n }\n\n get font(): ASCIIFontKind {\n return this._font;\n }\n\n set font(v: ASCIIFontKind) {\n this._font = v;\n this._render();\n }\n\n get color(): RGBA[] {\n return this._color;\n }\n\n set color(v: RGBA | RGBA[]) {\n this._color = Array.isArray(v) ? v : [v];\n this._render();\n }\n\n override getEstimatedHeight(): number {\n const renderedText = renderFontToText(this._text, this._font, this._color);\n const lines = renderedText ? renderedText.split(\"\\n\").length : 3;\n let h = lines;\n if (typeof this._options.marginTop === \"number\") h += this._options.marginTop;\n if (typeof this._options.marginBottom === \"number\") h += this._options.marginBottom;\n return h;\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n const renderedText = renderFontToText(this._text, this._font, this._color);\n this._renderer.setText(this._contentNodeId, renderedText);\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n /* ignore */\n }\n super.destroy();\n }\n\n /** Returns whether this renderable has an active selection. */\n hasSelection(): boolean {\n return false;\n }\n}\n\n// ── FrameBuffer ───────────────────────────────────────────────────────────────\n\nexport interface FrameBufferOptions extends BoxOptions {\n drawFn?: (buffer: FrameBufferLike, deltaTime: number, renderable: FrameBuffer) => void;\n}\n\nexport interface FrameBufferLike {\n width: number;\n height: number;\n setCell(x: number, y: number, char: string, fg?: RGBA, bg?: RGBA): void;\n drawText(text: string, x: number, y: number, fg?: RGBA, bg?: RGBA): void;\n fillRect(x: number, y: number, w: number, h: number, color: RGBA): void;\n clear(color?: RGBA): void;\n}\n\nlet _framebufferCounter = 0;\n\nexport class FrameBuffer extends Box {\n private _drawFn: FrameBufferOptions[\"drawFn\"];\n private _buffer: SimpleFrameBuffer;\n private _contentNodeId: number;\n\n get frameBuffer(): FrameBufferLike {\n return this._buffer;\n }\n\n constructor(renderer: CliRenderer, options: FrameBufferOptions = {}) {\n _framebufferCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `framebuffer-${_framebufferCounter}`,\n });\n\n const w = typeof options.width === \"number\" ? options.width : 80;\n const h = typeof options.height === \"number\" ? options.height : 24;\n this._buffer = new SimpleFrameBuffer(w, h);\n this._drawFn = options.drawFn;\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n }\n\n draw(deltaTime: number): void {\n if (this._isDestroyed || !this._drawFn) return;\n this._drawFn(this._buffer, deltaTime, this);\n this._flush();\n }\n\n private _flush(): void {\n this._renderer.setText(this._contentNodeId, this._buffer.toString());\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n /* ignore */\n }\n super.destroy();\n }\n}\n\nclass SimpleFrameBuffer implements FrameBufferLike {\n readonly width: number;\n readonly height: number;\n private cells: Array<{ char: string; fg?: RGBA; bg?: RGBA }>;\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.cells = Array.from({ length: width * height }, () => ({ char: \" \" }));\n }\n\n setCell(x: number, y: number, char: string, fg?: RGBA, bg?: RGBA): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n this.cells[y * this.width + x] = { char, fg, bg };\n }\n\n drawText(text: string, x: number, y: number, fg?: RGBA, _bg?: RGBA): void {\n for (let i = 0; i < text.length; i++) {\n this.setCell(x + i, y, text[i] ?? \"\", fg);\n }\n }\n\n fillRect(x: number, y: number, w: number, h: number, color: RGBA): void {\n for (let dy = 0; dy < h; dy++) {\n for (let dx = 0; dx < w; dx++) {\n this.setCell(x + dx, y + dy, \" \", undefined, color);\n }\n }\n }\n\n clear(color?: RGBA): void {\n for (let i = 0; i < this.cells.length; i++) {\n this.cells[i] = { char: \" \", bg: color };\n }\n }\n\n toString(): string {\n let result = \"\";\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n const cell = this.cells[y * this.width + x];\n if (!cell) continue;\n if (cell.fg && cell.fg.a > 0) {\n result += `\\x1b[38;2;${cell.fg.r};${cell.fg.g};${cell.fg.b}m`;\n }\n if (cell.bg && cell.bg.a > 0) {\n result += `\\x1b[48;2;${cell.bg.r};${cell.bg.g};${cell.bg.b}m`;\n }\n result += cell.char;\n if (cell.fg || cell.bg) result += \"\\x1b[0m\";\n }\n if (y < this.height - 1) result += \"\\n\";\n }\n return result;\n }\n}\n\n// ── Code ──────────────────────────────────────────────────────────────────────\n\nexport interface CodeOptions extends TextOptions {\n language?: string;\n filetype?: string;\n showLineNumbers?: boolean;\n code?: string;\n selectionBg?: ColorInput;\n selectionFg?: ColorInput;\n syntaxStyle?: unknown;\n}\n\nlet _codeCounter = 0;\n\nexport class Code extends Text {\n private _language: string;\n private _showLineNumbers: boolean;\n private _code: string;\n filetype = \"\";\n selectionBg: ColorInput = undefined;\n selectionFg: ColorInput = undefined;\n syntaxStyle: unknown = null;\n virtualLineCount = 0;\n\n constructor(renderer: CliRenderer, options: CodeOptions = {}) {\n _codeCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `code-${_codeCounter}`,\n content: options.code ?? options.content ?? \"\",\n });\n this._language = options.language ?? options.filetype ?? \"text\";\n this._showLineNumbers = options.showLineNumbers !== false;\n this._code = options.code ?? \"\";\n this.filetype = options.filetype ?? this._language;\n if (this._code) this._renderCode();\n }\n\n get code(): string {\n return this._code;\n }\n set code(v: string) {\n this._code = v;\n this._renderCode();\n }\n get showLineNumbers(): boolean {\n return this._showLineNumbers;\n }\n set showLineNumbers(v: boolean) {\n this._showLineNumbers = v;\n this._renderCode();\n }\n set language(v: string) {\n this._language = v;\n this._renderCode();\n }\n\n conceal(_ranges: unknown): void {}\n\n private _renderCode(): void {\n const lines = this._code.split(\"\\n\");\n const lineNumWidth = String(lines.length).length;\n const rendered = lines.map((line, i) => {\n if (this._showLineNumbers) {\n const num = String(i + 1).padStart(lineNumWidth);\n return `\\x1b[38;2;80;80;100m${num}\\x1b[0m \\x1b[38;2;200;200;200m${line}\\x1b[0m`;\n }\n return `\\x1b[38;2;200;200;200m${line}\\x1b[0m`;\n });\n this.content = rendered.join(\"\\n\");\n }\n}\n\n// ── Diff ──────────────────────────────────────────────────────────────────────\n\nexport interface DiffOptions extends TextOptions {\n oldText?: string;\n newText?: string;\n mode?: \"unified\" | \"split\";\n}\n\nlet _diffCounter = 0;\n\nexport class Diff extends Text {\n constructor(renderer: CliRenderer, options: DiffOptions = {}) {\n _diffCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `diff-${_diffCounter}`,\n });\n if (options.oldText !== undefined || options.newText !== undefined) {\n this._setDiff(options.oldText ?? \"\", options.newText ?? \"\");\n }\n }\n\n setDiff(oldText: string, newText: string): void {\n this._setDiff(oldText, newText);\n }\n\n private _setDiff(oldText: string, newText: string): void {\n const oldLines = oldText.split(\"\\n\");\n const newLines = newText.split(\"\\n\");\n const lines: string[] = [];\n\n // Simple line-by-line diff display\n const maxLen = Math.max(oldLines.length, newLines.length);\n for (let i = 0; i < maxLen; i++) {\n const old = oldLines[i];\n const next = newLines[i];\n if (old === undefined) {\n lines.push(`\\x1b[38;2;0;200;0m+ ${next ?? \"\"}\\x1b[0m`);\n } else if (next === undefined) {\n lines.push(`\\x1b[38;2;200;0;0m- ${old}\\x1b[0m`);\n } else if (old === next) {\n lines.push(` ${old}`);\n } else {\n lines.push(`\\x1b[38;2;200;0;0m- ${old}\\x1b[0m`);\n lines.push(`\\x1b[38;2;0;200;0m+ ${next}\\x1b[0m`);\n }\n }\n this.content = lines.join(\"\\n\");\n }\n}\n\n// ── Markdown ──────────────────────────────────────────────────────────────────\n\nexport interface MarkdownOptions extends TextOptions {\n content?: string | StyledText;\n}\n\nlet _markdownCounter = 0;\n\nexport class Markdown extends Text {\n constructor(renderer: CliRenderer, options: MarkdownOptions = {}) {\n _markdownCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `markdown-${_markdownCounter}`,\n });\n }\n\n set markdown(text: string) {\n // Basic markdown rendering\n const lines = text.split(\"\\n\").map((line) => {\n if (line.startsWith(\"# \")) {\n return `\\x1b[1;38;2;255;200;0m${line.slice(2)}\\x1b[0m`;\n }\n if (line.startsWith(\"## \")) {\n return `\\x1b[1;38;2;200;160;0m${line.slice(3)}\\x1b[0m`;\n }\n if (line.startsWith(\"### \")) {\n return `\\x1b[1;38;2;160;120;0m${line.slice(4)}\\x1b[0m`;\n }\n if (line.startsWith(\"- \") || line.startsWith(\"* \")) {\n return ` \\x1b[38;2;100;200;100m•\\x1b[0m ${line.slice(2)}`;\n }\n if (line.startsWith(\"> \")) {\n return `\\x1b[38;2;100;100;180m│\\x1b[0m ${line.slice(2)}`;\n }\n // Bold **text**\n return line\n .replace(/\\*\\*(.+?)\\*\\*/g, \"\\x1b[1m$1\\x1b[0m\")\n .replace(/\\*(.+?)\\*/g, \"\\x1b[3m$1\\x1b[0m\")\n .replace(/`(.+?)`/g, \"\\x1b[38;2;150;220;150m$1\\x1b[0m\");\n });\n this.content = lines.join(\"\\n\");\n }\n}\n\n// ── TextTable ─────────────────────────────────────────────────────────────────\n\nexport interface TableColumn {\n header: string;\n key?: string;\n width?: number;\n align?: \"left\" | \"center\" | \"right\";\n}\n\nexport type TextTableColumnWidthMode = \"content\" | \"full\";\nexport type TextTableColumnFitter = \"proportional\" | \"balanced\";\nexport type TextTableContent = Array<Array<TextChunk[] | Array<TextChunk>>>;\n\nexport interface TextTableOptions extends BoxOptions {\n columns?: TableColumn[];\n rows?: Record<string, unknown>[][];\n data?: string[][];\n showBorder?: boolean;\n headerColor?: ColorInput;\n rowColor?: ColorInput;\n alternateRowColor?: ColorInput;\n wrapMode?: \"none\" | \"word\" | \"char\";\n columnWidthMode?: TextTableColumnWidthMode;\n columnFitter?: TextTableColumnFitter;\n cellPadding?: number;\n border?: boolean;\n outerBorder?: boolean;\n showBorders?: boolean;\n borderStyle?: BorderStyleKind;\n borderColor?: ColorInput;\n fg?: ColorInput;\n bg?: ColorInput;\n content?: TextTableContent;\n}\n\nlet _tableCounter = 0;\n\nexport class TextTable extends Box {\n private _columns: TableColumn[];\n private _data: string[][];\n private _contentNodeId: number;\n private _headerColor: RGBA;\n private _rowColor: RGBA;\n private _wrapMode: \"none\" | \"word\" | \"char\";\n private _columnWidthMode: TextTableColumnWidthMode;\n private _columnFitter: TextTableColumnFitter;\n private _cellPadding: number;\n private _outerBorder: boolean;\n private _showBorders: boolean;\n private _content: TextTableContent | null = null;\n\n constructor(renderer: CliRenderer, options: TextTableOptions = {}) {\n _tableCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `table-${_tableCounter}`,\n });\n\n this._columns = options.columns ?? [];\n this._data = options.data ?? [];\n this._headerColor = parseColor(options.headerColor ?? \"#0088ff\");\n this._rowColor = parseColor(options.rowColor ?? \"#dddddd\");\n this._wrapMode = options.wrapMode ?? \"none\";\n this._columnWidthMode = options.columnWidthMode ?? \"content\";\n this._columnFitter = options.columnFitter ?? \"proportional\";\n this._cellPadding = options.cellPadding ?? 0;\n this._outerBorder = options.outerBorder !== false;\n this._showBorders = options.showBorders !== false;\n this._content = options.content ?? null;\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n this._render();\n }\n\n get wrapMode(): \"none\" | \"word\" | \"char\" {\n return this._wrapMode;\n }\n set wrapMode(v: \"none\" | \"word\" | \"char\") {\n this._wrapMode = v;\n this._render();\n }\n\n get columnWidthMode(): TextTableColumnWidthMode {\n return this._columnWidthMode;\n }\n set columnWidthMode(v: TextTableColumnWidthMode) {\n this._columnWidthMode = v;\n this._render();\n }\n\n get columnFitter(): TextTableColumnFitter {\n return this._columnFitter;\n }\n set columnFitter(v: TextTableColumnFitter) {\n this._columnFitter = v;\n this._render();\n }\n\n get cellPadding(): number {\n return this._cellPadding;\n }\n set cellPadding(v: number) {\n this._cellPadding = v;\n this._render();\n }\n\n get outerBorder(): boolean {\n return this._outerBorder;\n }\n set outerBorder(v: boolean) {\n this._outerBorder = v;\n this._render();\n }\n\n get showBorders(): boolean {\n return this._showBorders;\n }\n set showBorders(v: boolean) {\n this._showBorders = v;\n this._render();\n }\n\n get content(): TextTableContent | null {\n return this._content;\n }\n set content(v: TextTableContent | null) {\n this._content = v;\n this._render();\n }\n\n setData(columns: TableColumn[], data: string[][]): void {\n this._columns = columns;\n this._data = data;\n this._render();\n }\n\n addRow(row: string[]): void {\n this._data.push(row);\n this._render();\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n const lines: string[] = [];\n\n // Header row\n if (this._columns.length > 0) {\n const hc = `${this._headerColor.r};${this._headerColor.g};${this._headerColor.b}`;\n const headers = this._columns.map((col) => {\n const w = col.width ?? 12;\n return `\\x1b[1;38;2;${hc}m${col.header.slice(0, w).padEnd(w)}\\x1b[0m`;\n });\n lines.push(headers.join(\" │ \"));\n lines.push(this._columns.map((col) => \"─\".repeat(col.width ?? 12)).join(\"─┼─\"));\n }\n\n const rc = `${this._rowColor.r};${this._rowColor.g};${this._rowColor.b}`;\n for (const row of this._data) {\n const cells =\n this._columns.length > 0\n ? this._columns.map((col, i) => {\n const w = col.width ?? 12;\n const cell = (row[i] ?? \"\").slice(0, w).padEnd(w);\n return `\\x1b[38;2;${rc}m${cell}\\x1b[0m`;\n })\n : row.map((cell) => `\\x1b[38;2;${rc}m${cell}\\x1b[0m`);\n lines.push(cells.join(\" │ \"));\n }\n\n this._renderer.setText(this._contentNodeId, lines.join(\"\\n\"));\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n /* ignore */\n }\n super.destroy();\n }\n}\n\n// ── LineNumber ────────────────────────────────────────────────────────────────\n\nexport interface LineNumberOptions extends BoxOptions {\n lineCount?: number;\n startLine?: number;\n color?: ColorInput;\n highlightColor?: ColorInput;\n highlightLine?: number;\n target?: unknown;\n}\n\nlet _lineNumCounter = 0;\n\nexport class LineNumber extends Box {\n private _lineCount: number;\n private _startLine: number;\n private _color: RGBA;\n private _highlightColor: RGBA;\n private _highlightLine: number;\n private _contentNodeId: number;\n fg: ColorInput = undefined;\n bg: ColorInput = undefined;\n\n constructor(renderer: CliRenderer, options: LineNumberOptions = {}) {\n _lineNumCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `linenum-${_lineNumCounter}`,\n });\n this._lineCount = options.lineCount ?? 0;\n this._startLine = options.startLine ?? 1;\n this._color = parseColor(options.color ?? \"#555577\");\n this._highlightColor = parseColor(options.highlightColor ?? \"#8888aa\");\n this._highlightLine = options.highlightLine ?? -1;\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n this._render();\n }\n\n get lineCount(): number {\n return this._lineCount;\n }\n set lineCount(v: number) {\n this._lineCount = v;\n this._render();\n }\n get showLineNumbers(): boolean {\n return true;\n }\n set highlightLine(v: number) {\n this._highlightLine = v;\n this._render();\n }\n\n setLineColor(_line: number, _color: ColorInput): void {\n this._render();\n }\n clearAllLineColors(): void {\n this._render();\n }\n setLineSign(_line: number, _sign: string, _color?: ColorInput): void {\n this._render();\n }\n clearLineSign(_line: number): void {\n this._render();\n }\n getLineSigns(_line: number): string[] {\n return [];\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n const lines: string[] = [];\n const width = String(this._startLine + this._lineCount).length;\n const nc = `${this._color.r};${this._color.g};${this._color.b}`;\n const hc = `${this._highlightColor.r};${this._highlightColor.g};${this._highlightColor.b}`;\n for (let i = 0; i < this._lineCount; i++) {\n const num = this._startLine + i;\n const isHighlight = num === this._highlightLine;\n const numStr = String(num).padStart(width);\n lines.push(\n isHighlight ? `\\x1b[38;2;${hc}m${numStr}\\x1b[0m` : `\\x1b[38;2;${nc}m${numStr}\\x1b[0m`,\n );\n }\n this._renderer.setText(this._contentNodeId, lines.join(\"\\n\"));\n }\n override destroy(): void {\n if (this._isDestroyed) return;\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n /* ignore */\n }\n super.destroy();\n }\n}\n// ── TimeToFirstDraw ───────────────────────────────────────────────────────────\n\nexport interface TimeToFirstDrawOptions extends TextOptions {\n fg?: ColorInput;\n color?: RGBA;\n}\n\nlet _ttfdCounter = 0;\n\nexport class TimeToFirstDraw extends Box {\n private _fg: RGBA;\n private _color: RGBA;\n private _contentNodeId: number;\n private _startTime: number;\n\n constructor(renderer: CliRenderer, options: TimeToFirstDrawOptions = {}) {\n _ttfdCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `ttfd-${_ttfdCounter}`,\n });\n this._fg = parseColor(options.fg ?? \"#888888\");\n this._color = options.color ?? this._fg;\n this._startTime = Date.now();\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n // Apply the foreground color to the text node using setNodeStyle\n renderer.setNodeStyle(this._contentNodeId, { fg: RGBA.toHex(this._color) });\n this._render();\n }\n\n get fg(): RGBA {\n return this._fg;\n }\n\n set fg(color: ColorInput) {\n this._fg = parseColor(color);\n this._color = this._fg;\n this._renderer.setNodeStyle(this._contentNodeId, {\n fg: RGBA.toHex(this._color),\n });\n this._render();\n }\n\n get color(): RGBA {\n return this._color;\n }\n\n set color(v: RGBA) {\n this._color = v;\n this._renderer.setNodeStyle(this._contentNodeId, {\n fg: RGBA.toHex(this._color),\n });\n this._render();\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n const elapsed = Date.now() - this._startTime;\n // Use plain text - colors should be applied via style system, not ANSI codes\n this._renderer.setText(this._contentNodeId, `Time to first draw: ${elapsed}ms`);\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n /* ignore */\n }\n super.destroy();\n }\n}\n","/**\n * TabSelect — a horizontal tab navigation widget.\n */\n\nimport type { KeyEvent } from \"../lib/keyHandler\";\nimport { RenderableEvents, TabSelectEvents } from \"../lib/renderableEvents\";\nimport { type ColorInput, type RGBA, parseColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\nexport interface TabOption {\n name: string;\n description?: string;\n value?: unknown;\n}\n\nexport interface TabSelectOptions extends BoxOptions {\n options?: TabOption[];\n selectedIndex?: number;\n /** Fixed width for each tab in characters. Set to 0 for auto-width based on content. */\n tabWidth?: number;\n /** Minimum width for auto-sized tabs. Ignored when tabWidth > 0. */\n minTabWidth?: number;\n /** Padding added to each side of tab text in auto mode. Default: 2. */\n tabPadding?: number;\n /** Gap between tabs in characters. Default: 1. */\n tabGap?: number;\n showDescription?: boolean;\n showUnderline?: boolean;\n showScrollArrows?: boolean;\n scrollArrowLeft?: string;\n scrollArrowRight?: string;\n wrapSelection?: boolean;\n backgroundColor?: ColorInput;\n textColor?: ColorInput;\n selectedTextColor?: ColorInput;\n selectedBackgroundColor?: ColorInput;\n activeUnderlineColor?: ColorInput;\n inactiveUnderlineColor?: ColorInput;\n descriptionColor?: ColorInput;\n}\n\nexport type TabSelectRenderableOptions = TabSelectOptions;\n\nlet _tabSelectCounter = 0;\n\n/** Calculate display widths for each tab based on content and options. */\nfunction calculateTabWidths(\n options: TabOption[],\n tabWidth: number,\n minTabWidth: number,\n tabPadding: number,\n): number[] {\n if (tabWidth > 0) {\n // Fixed width mode\n return options.map(() => tabWidth);\n }\n // Auto-width mode: content length + padding, with minimum\n return options.map((opt) => Math.max(minTabWidth, opt.name.length + tabPadding * 2));\n}\n\nexport class TabSelect extends Box {\n private _tabOptions: TabOption[];\n private _selectedIndex: number;\n private _tabWidth: number;\n private _minTabWidth: number;\n private _tabPadding: number;\n private _tabGap: number;\n private _showDescription: boolean;\n private _showUnderline: boolean;\n private _showScrollArrows: boolean;\n private _scrollArrowLeft: string;\n private _scrollArrowRight: string;\n private _wrapSelection: boolean;\n private _textColor: RGBA;\n private _selectedTextColor: RGBA;\n private _selectedBgColor: RGBA | null = null;\n private _activeUnderlineColor: RGBA;\n private _inactiveUnderlineColor: RGBA;\n private _descriptionColor: RGBA;\n private _contentNodeId: number;\n private readonly _keyHandler: (key: KeyEvent) => void;\n\n constructor(renderer: CliRenderer, options: TabSelectOptions = {}) {\n _tabSelectCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `tabselect-${_tabSelectCounter}`,\n focusable: true,\n });\n\n this._tabOptions = options.options ?? [];\n this._selectedIndex = options.selectedIndex ?? 0;\n this._tabWidth = options.tabWidth ?? 0; // Default to auto-width (0 = auto)\n this._minTabWidth = options.minTabWidth ?? 8; // Minimum width for auto mode\n this._tabPadding = options.tabPadding ?? 2; // Padding on each side\n this._tabGap = options.tabGap ?? 1; // Gap between tabs\n this._showDescription = options.showDescription !== false;\n this._showUnderline = options.showUnderline !== false;\n this._showScrollArrows = options.showScrollArrows !== false;\n this._scrollArrowLeft = options.scrollArrowLeft ?? \"◀\";\n this._scrollArrowRight = options.scrollArrowRight ?? \"▶\";\n this._wrapSelection = options.wrapSelection ?? false;\n this._textColor = parseColor(options.textColor ?? \"#888888\");\n this._selectedTextColor = parseColor(options.selectedTextColor ?? \"#ffffff\");\n this._activeUnderlineColor = parseColor(options.activeUnderlineColor ?? \"#0088ff\");\n this._inactiveUnderlineColor = parseColor(options.inactiveUnderlineColor ?? \"#333333\");\n this._descriptionColor = parseColor(options.descriptionColor ?? \"#666666\");\n\n if (options.selectedBackgroundColor) {\n this._selectedBgColor = parseColor(options.selectedBackgroundColor);\n }\n\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n\n this._keyHandler = this._handleKey.bind(this);\n this._render();\n }\n\n get options(): TabOption[] {\n return this._tabOptions;\n }\n\n set options(opts: TabOption[]) {\n this._tabOptions = opts;\n this._selectedIndex = Math.min(this._selectedIndex, Math.max(0, opts.length - 1));\n this._render();\n }\n\n get selectedIndex(): number {\n return this._selectedIndex;\n }\n\n set selectedIndex(idx: number) {\n this._selectedIndex = Math.max(0, Math.min(this._tabOptions.length - 1, idx));\n this._render();\n }\n\n get showDescription(): boolean {\n return this._showDescription;\n }\n\n set showDescription(v: boolean) {\n this._showDescription = v;\n this._render();\n }\n\n get showUnderline(): boolean {\n return this._showUnderline;\n }\n\n set showUnderline(v: boolean) {\n this._showUnderline = v;\n this._render();\n }\n\n get showScrollArrows(): boolean {\n return this._showScrollArrows;\n }\n\n set showScrollArrows(v: boolean) {\n this._showScrollArrows = v;\n this._render();\n }\n\n get scrollArrowLeft(): string {\n return this._scrollArrowLeft;\n }\n\n set scrollArrowLeft(v: string) {\n this._scrollArrowLeft = v;\n this._render();\n }\n\n get scrollArrowRight(): string {\n return this._scrollArrowRight;\n }\n\n set scrollArrowRight(v: string) {\n this._scrollArrowRight = v;\n this._render();\n }\n\n get wrapSelection(): boolean {\n return this._wrapSelection;\n }\n\n set wrapSelection(v: boolean) {\n this._wrapSelection = v;\n }\n\n getSelectedOption(): TabOption | undefined {\n return this._tabOptions[this._selectedIndex];\n }\n\n getSelectedIndex(): number {\n return this._selectedIndex;\n }\n\n selectCurrent(): void {\n const opt = this.getSelectedOption();\n if (opt) {\n this.emit(TabSelectEvents.ITEM_SELECTED, this._selectedIndex, opt);\n }\n }\n\n moveLeft(steps = 1): void {\n const prev = this._selectedIndex;\n let next = this._selectedIndex - steps;\n if (this._wrapSelection) {\n next = ((next % this._tabOptions.length) + this._tabOptions.length) % this._tabOptions.length;\n } else {\n next = Math.max(0, next);\n }\n if (next !== prev) {\n this._selectedIndex = next;\n this._render();\n const opt = this.getSelectedOption();\n if (opt) this.emit(TabSelectEvents.SELECTION_CHANGED, next, opt);\n }\n }\n\n moveRight(steps = 1): void {\n const prev = this._selectedIndex;\n let next = this._selectedIndex + steps;\n if (this._wrapSelection) {\n next = next % this._tabOptions.length;\n } else {\n next = Math.min(this._tabOptions.length - 1, next);\n }\n if (next !== prev) {\n this._selectedIndex = next;\n this._render();\n const opt = this.getSelectedOption();\n if (opt) this.emit(TabSelectEvents.SELECTION_CHANGED, next, opt);\n }\n }\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n this._render();\n this.emit(RenderableEvents.FOCUSED, this);\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n this._focused = false;\n this._render();\n this.emit(RenderableEvents.BLURRED, this);\n }\n\n private _handleKey(key: KeyEvent): void {\n if (!this._focused || this._isDestroyed) return;\n\n if (key.name === \"left\" || (key.shift && key.name === \"tab\")) {\n this.moveLeft();\n } else if (key.name === \"right\" || key.name === \"tab\") {\n this.moveRight();\n } else if (key.name === \"return\" || key.name === \"linefeed\") {\n this.selectCurrent();\n }\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n\n const lines: string[] = [];\n const tabLine: string[] = [];\n\n // Calculate dynamic widths for each tab\n const tabWidths = calculateTabWidths(\n this._tabOptions,\n this._tabWidth,\n this._minTabWidth,\n this._tabPadding,\n );\n\n if (this._showScrollArrows) {\n tabLine.push(`\\x1b[38;2;100;100;100m${this._scrollArrowLeft}\\x1b[0m`);\n }\n\n for (let i = 0; i < this._tabOptions.length; i++) {\n const opt = this._tabOptions[i];\n if (!opt) continue;\n const isSelected = i === this._selectedIndex;\n const width = tabWidths[i] ?? this._minTabWidth;\n\n // Center the name within the tab width, padding on both sides\n const name = opt.name.padEnd(width).slice(0, width);\n const textColor = isSelected ? this._selectedTextColor : this._textColor;\n const tc = `${textColor.r};${textColor.g};${textColor.b}`;\n\n if (isSelected && this._selectedBgColor) {\n const bc = `${this._selectedBgColor.r};${this._selectedBgColor.g};${this._selectedBgColor.b}`;\n tabLine.push(`\\x1b[48;2;${bc}m\\x1b[38;2;${tc}m${name}\\x1b[0m`);\n } else {\n tabLine.push(`\\x1b[38;2;${tc}m${name}\\x1b[0m`);\n }\n\n // Add gap between tabs (but not after the last one)\n if (i < this._tabOptions.length - 1 && this._tabGap > 0) {\n tabLine.push(\" \".repeat(this._tabGap));\n }\n }\n\n if (this._showScrollArrows) {\n tabLine.push(`\\x1b[38;2;100;100;100m${this._scrollArrowRight}\\x1b[0m`);\n }\n\n lines.push(tabLine.join(\"\"));\n\n if (this._showUnderline) {\n const underline: string[] = [];\n for (let i = 0; i < this._tabOptions.length; i++) {\n const isSelected = i === this._selectedIndex;\n const color = isSelected ? this._activeUnderlineColor : this._inactiveUnderlineColor;\n const cc = `${color.r};${color.g};${color.b}`;\n const width = tabWidths[i] ?? this._minTabWidth;\n underline.push(`\\x1b[38;2;${cc}m${\"─\".repeat(width)}\\x1b[0m`);\n // Add matching gap between underlines\n if (i < this._tabOptions.length - 1 && this._tabGap > 0) {\n underline.push(\" \".repeat(this._tabGap));\n }\n }\n lines.push(underline.join(\"\"));\n }\n\n if (this._showDescription) {\n const opt = this.getSelectedOption();\n if (opt?.description) {\n const dc = `${this._descriptionColor.r};${this._descriptionColor.g};${this._descriptionColor.b}`;\n lines.push(`\\x1b[38;2;${dc}m${opt.description}\\x1b[0m`);\n } else {\n lines.push(\"\");\n }\n }\n\n this._renderer.setText(this._contentNodeId, lines.join(\"\\n\"));\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n}\n\nexport { TabSelectEvents };\n","/**\n * VNode composition system for BetterTUI.\n * Provides a declarative API for building UI trees.\n */\n\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box as BoxClass, type BoxOptions } from \"../renderables/Box\";\nimport { Input as InputClass, type InputOptions } from \"../renderables/Input\";\nimport { Select as SelectClass, type SelectOptions } from \"../renderables/Select\";\nimport {\n ASCIIFont as ASCIIFontClass,\n type ASCIIFontOptions,\n Code as CodeClass,\n type CodeOptions,\n FrameBuffer as FrameBufferClass,\n type FrameBufferLike,\n type FrameBufferOptions,\n} from \"../renderables/Stubs\";\nimport { TabSelect as TabSelectClass, type TabSelectOptions } from \"../renderables/TabSelect\";\nimport { Text as TextClass, type TextOptions } from \"../renderables/Text\";\n\n/** A VNode (virtual node) — a lazy description of a renderable. */\nexport interface VNode {\n _type: string | (new (renderer: CliRenderer, options: Record<string, unknown>) => BoxClass);\n _props: Record<string, unknown>;\n _children: VNode[];\n}\n\n/**\n * Create a VNode.\n */\nexport function h(\n type: string | (new (renderer: CliRenderer, options: Record<string, unknown>) => BoxClass),\n props?: Record<string, unknown> | null,\n ...children: (VNode | string | null | undefined)[]\n): VNode {\n return {\n _type: type,\n _props: props ?? {},\n _children: children\n .filter(Boolean)\n .map((c) => (typeof c === \"string\" ? h(\"Text\", { content: c }) : (c as VNode))),\n };\n}\n\n/**\n * Instantiate a VNode tree into real renderables.\n */\nexport function instantiate(ctx: CliRenderer, vnode: VNode): BoxClass {\n const { _type: type, _props: props, _children: children } = vnode;\n\n let instance: BoxClass;\n\n if (typeof type === \"function\") {\n // Custom component class\n instance = new (\n type as new (\n renderer: CliRenderer,\n options: Record<string, unknown>,\n ) => BoxClass\n )(ctx, props);\n } else {\n // Built-in type\n switch (type) {\n case \"Text\":\n instance = new TextClass(ctx, props as TextOptions);\n break;\n case \"Input\":\n instance = new InputClass(ctx, props as InputOptions);\n break;\n case \"Select\":\n instance = new SelectClass(ctx, props as SelectOptions);\n break;\n case \"TabSelect\":\n instance = new TabSelectClass(ctx, props as TabSelectOptions);\n break;\n case \"Code\":\n instance = new CodeClass(ctx, props as CodeOptions);\n break;\n case \"FrameBuffer\":\n case \"Generic\": {\n // Generic: uses a render function prop\n const renderFn = props.render as FrameBufferOptions[\"drawFn\"];\n instance = new FrameBufferClass(ctx, {\n ...props,\n drawFn: renderFn,\n } as FrameBufferOptions);\n break;\n }\n case \"ASCIIFont\":\n instance = new ASCIIFontClass(ctx, props as ASCIIFontOptions);\n break;\n default:\n instance = new BoxClass(ctx, props as BoxOptions);\n }\n }\n\n // Instantiate and attach children\n for (const child of children) {\n const childInstance = instantiate(ctx, child);\n instance.add(childInstance);\n }\n\n return instance;\n}\n\n/**\n * Redirect add/remove/focus calls to a named child renderable.\n */\nexport function delegate(targets: string | string[], vnode: VNode): VNode {\n return {\n ...vnode,\n _props: {\n ...vnode._props,\n __delegateTargets: Array.isArray(targets) ? targets : [targets],\n },\n };\n}\n\n/** Maybe create a renderable from a VNode or return existing renderable. */\nexport function maybeMakeRenderable(ctx: CliRenderer, input: VNode | BoxClass): BoxClass {\n if (input instanceof BoxClass) return input;\n return instantiate(ctx, input as VNode);\n}\n\n// ── Functional VNode constructors ─────────────────────────────────────────────\n\nexport function BoxVNode(props?: BoxOptions, ...children: VNode[]): VNode {\n return { _type: \"Box\", _props: (props ?? {}) as Record<string, unknown>, _children: children };\n}\n\nexport function TextVNode(props?: TextOptions, ...children: (VNode | string)[]): VNode {\n const processedChildren = children.map((c) =>\n typeof c === \"string\" ? h(\"Text\", { content: c }) : c,\n );\n return {\n _type: \"Text\",\n _props: (props ?? {}) as Record<string, unknown>,\n _children: processedChildren,\n };\n}\n\nexport function InputVNode(props?: InputOptions, ...children: VNode[]): VNode {\n return { _type: \"Input\", _props: (props ?? {}) as Record<string, unknown>, _children: children };\n}\n\nexport function SelectVNode(props?: SelectOptions, ...children: VNode[]): VNode {\n return { _type: \"Select\", _props: (props ?? {}) as Record<string, unknown>, _children: children };\n}\n\nexport function TabSelectVNode(props?: TabSelectOptions, ...children: VNode[]): VNode {\n return {\n _type: \"TabSelect\",\n _props: (props ?? {}) as Record<string, unknown>,\n _children: children,\n };\n}\n\nexport function CodeVNode(props?: CodeOptions, ...children: VNode[]): VNode {\n return { _type: \"Code\", _props: (props ?? {}) as Record<string, unknown>, _children: children };\n}\n\nexport {\n BoxVNode as Box,\n TextVNode as Text,\n InputVNode as Input,\n SelectVNode as Select,\n TabSelectVNode as TabSelect,\n CodeVNode as Code,\n GenericVNode as Generic,\n};\n\nexport function GenericVNode(\n props?: BoxOptions & { render?: (buffer: FrameBufferLike, dt: number, r: BoxClass) => void },\n ...children: VNode[]\n): VNode {\n return {\n _type: \"Generic\",\n _props: (props ?? {}) as Record<string, unknown>,\n _children: children,\n };\n}\n\nexport function ScrollBox(props?: BoxOptions, ...children: VNode[]): VNode {\n return {\n _type: \"ScrollBox\",\n _props: (props ?? {}) as Record<string, unknown>,\n _children: children,\n };\n}\n\nexport function ASCIIFont(props?: ASCIIFontOptions, ...children: VNode[]): VNode {\n return {\n _type: \"ASCIIFont\",\n _props: (props ?? {}) as Record<string, unknown>,\n _children: children,\n };\n}\n\n// ── vstyles: vnode-compatible text styling ────────────────────────────────────\n\nfunction _vstyleText(text: string, fg?: string, _attrs?: number, bg?: string): VNode {\n return h(\"Text\", { content: text, fg, bg });\n}\n\nexport const vstyles = {\n bold: (text: string) => _vstyleText(text, undefined, 1),\n italic: (text: string) => _vstyleText(text, undefined, 4),\n underline: (text: string) => _vstyleText(text, undefined, 8),\n dim: (text: string) => _vstyleText(text, undefined, 2),\n color: (color: string, ...children: (string | VNode)[]) => {\n const textChildren = children.map((c) =>\n typeof c === \"string\" ? h(\"Text\", { content: c }) : c,\n );\n return h(\"Text\", { fg: color }, ...textChildren);\n },\n bgColor: (color: string, ...children: (string | VNode)[]) => {\n const textChildren = children.map((c) =>\n typeof c === \"string\" ? h(\"Text\", { content: c }) : c,\n );\n return h(\"Text\", { bg: color }, ...textChildren);\n },\n fg: (color: string) => (text: string) => _vstyleText(text, color),\n bg: (color: string) => (text: string) => _vstyleText(text, undefined, 0, color),\n styled: (attrs: Record<string, unknown>, text: string) => h(\"Text\", { content: text, ...attrs }),\n boldItalic: (text: string) => _vstyleText(text, undefined, 5),\n boldUnderline: (text: string) => _vstyleText(text, undefined, 9),\n};\n","export { Keymap } from \"./keybinding\";\nexport type {\n KeymapEvent,\n CommandHandler,\n CommandContext,\n CommandEntry,\n InterceptHandler,\n InterceptContext,\n KeyListener,\n KeymapOptions,\n ActiveKeyInfo,\n BindingInfo,\n} from \"./keybinding\";\n\nexport { SystemClock } from \"./clock\";\nexport type { Clock, TimerHandle } from \"./clock\";\n\nexport {\n isValidColor,\n validateLayoutConstraints,\n validateStyle,\n validate,\n warnIfInvalid,\n} from \"./validation\";\nexport type { ValidationError, ValidationResult } from \"./validation\";\n\nexport {\n parseKeypress,\n nonAlphanumericKeys,\n terminalNamedSingleStrokeKeys,\n} from \"./parseKeypress\";\nexport type {\n ParsedKey,\n KeyEventType,\n ParseKeypressOptions,\n} from \"./parseKeypress\";\n\nexport {\n parseKittyKeyboard,\n kittyNamedSingleStrokeKeys,\n} from \"./parseKeypressKitty\";\n\nexport { MouseParser } from \"./parseMouse\";\nexport type { MouseEventType, RawMouseEvent, ScrollInfo } from \"./parseMouse\";\n\nexport { KeyHandler, InternalKeyHandler, PasteEvent } from \"./keyHandler\";\nexport { KeyEvent as KeyboardEvent, KeyEvent } from \"./keyHandler\";\nexport type { KeyHandlerEventMap } from \"./keyHandler\";\n\nexport {\n defaultKeyAliases,\n mergeKeyAliases,\n mergeKeyBindings,\n getKeyBindingKey,\n getKeyBindingKeys,\n getKeyBindingAction,\n matchesKeyBinding,\n buildKeyBindingsMap,\n keyBindingToString,\n} from \"./renderableKeyBindings\";\nexport type {\n KeyBinding,\n KeyBindingLike,\n KeyBindingLookup,\n KeyAliasMap,\n} from \"./renderableKeyBindings\";\n\nexport { KeyInput } from \"./keyInput\";\n\nexport { StdinParser } from \"./stdinParser\";\nexport type {\n StdinEvent,\n StdinParserOptions,\n StdinParserProtocolContext,\n StdinResponseProtocol,\n PasteMetadata,\n} from \"./stdinParser\";\n\n// ── New exports ───────────────────────────────────────────────────────────────\n\nexport { RGBA, parseColor, rgbaToEngineColor } from \"./rgba\";\nexport type { ColorInput } from \"./rgba\";\n\nexport {\n TextAttributes,\n StyledText,\n isStyledText,\n stringToStyledText,\n styledTextToAnsi,\n visibleWidth,\n t,\n // Style attribute helpers\n bold,\n italic,\n underline,\n strikethrough,\n dim,\n reverse,\n blink,\n // Named fg colors\n black,\n red,\n green,\n yellow,\n blue,\n magenta,\n cyan,\n white,\n brightBlack,\n brightRed,\n brightGreen,\n brightYellow,\n brightBlue,\n brightMagenta,\n brightCyan,\n brightWhite,\n // Named bg colors\n bgBlack,\n bgRed,\n bgGreen,\n bgBlue,\n bgYellow,\n bgCyan,\n bgMagenta,\n bgWhite,\n // Curried helpers\n fg,\n bg,\n link,\n} from \"./styledText\";\nexport type { TextChunk, StylableInput } from \"./styledText\";\n\nexport {\n CliRenderEvents,\n RenderableEvents,\n InputEvents,\n SelectEvents,\n TabSelectEvents,\n SliderEvents,\n LayoutEvents,\n} from \"./renderableEvents\";\n\nexport {\n singleton,\n getSingleton,\n destroySingleton,\n hasSingleton,\n} from \"./singleton\";\n\nexport {\n env,\n registerEnvVar,\n getEnvVarConfig,\n getAllEnvVarConfigs,\n clearEnvCache,\n generateEnvMarkdown,\n generateEnvColored,\n} from \"./env\";\nexport type { EnvVarConfig } from \"./env\";\n\nexport { Timeline, createTimeline } from \"./timeline\";\nexport type { TimelineOptions, TweenConfig } from \"./timeline\";\n\nexport {\n h,\n instantiate,\n delegate,\n maybeMakeRenderable,\n // VNode factories (prefixed to avoid clash with widget classes)\n Box as VNodeBox,\n Text as VNodeText,\n Input as VNodeInput,\n Select as VNodeSelect,\n TabSelect as VNodeTabSelect,\n Code as VNodeCode,\n Generic,\n ScrollBox as VNodeScrollBox,\n ASCIIFont as VNodeASCIIFont,\n vstyles,\n} from \"./vnode\";\nexport type { VNode } from \"./vnode\";\n","import type { LogEntry, LogLevel } from \"./devtools.types\";\n\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n};\n\nexport interface LoggerOptions {\n maxEntries?: number;\n minLevel?: LogLevel | undefined;\n onEntry?: ((entry: LogEntry) => void) | undefined;\n}\n\nexport class Logger {\n private entries: LogEntry[] = [];\n private nextId = 0;\n private minLevel: LogLevel;\n private maxEntries: number;\n private onEntry: ((entry: LogEntry) => void) | undefined;\n\n constructor(options: LoggerOptions = {}) {\n this.maxEntries = options.maxEntries ?? 1000;\n this.minLevel = options.minLevel ?? \"trace\";\n this.onEntry = options.onEntry;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[this.minLevel];\n }\n\n private record(level: LogLevel, category: string, message: string, data?: unknown): LogEntry {\n const entry: LogEntry = {\n id: this.nextId++,\n timestamp: performance.now(),\n level,\n category,\n message,\n data,\n };\n\n if (this.shouldLog(level)) {\n this.entries.push(entry);\n if (this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onEntry?.(entry);\n }\n\n return entry;\n }\n\n trace(category: string, message: string, data?: unknown): LogEntry {\n return this.record(\"trace\", category, message, data);\n }\n\n debug(category: string, message: string, data?: unknown): LogEntry {\n return this.record(\"debug\", category, message, data);\n }\n\n info(category: string, message: string, data?: unknown): LogEntry {\n return this.record(\"info\", category, message, data);\n }\n\n warn(category: string, message: string, data?: unknown): LogEntry {\n return this.record(\"warn\", category, message, data);\n }\n\n error(category: string, message: string, data?: unknown): LogEntry {\n return this.record(\"error\", category, message, data);\n }\n\n getEntries(): readonly LogEntry[] {\n return this.entries;\n }\n\n getEntriesByLevel(level: LogLevel): LogEntry[] {\n return this.entries.filter((e) => e.level === level);\n }\n\n getEntriesByCategory(category: string): LogEntry[] {\n return this.entries.filter((e) => e.category === category);\n }\n\n search(query: string): LogEntry[] {\n const lower = query.toLowerCase();\n return this.entries.filter(\n (e) => e.message.toLowerCase().includes(lower) || e.category.toLowerCase().includes(lower),\n );\n }\n\n clear(): void {\n this.entries = [];\n }\n\n get count(): number {\n return this.entries.length;\n }\n}\n","import type { CommandType, RecordedCommand } from \"./devtools.types\";\n\nexport interface CommandInspectorOptions {\n maxCommands?: number | undefined;\n onCommand?: ((command: RecordedCommand) => void) | undefined;\n}\n\nexport class CommandInspector {\n private commands: RecordedCommand[] = [];\n private nextId = 0;\n private maxCommands: number;\n private onCommand: ((command: RecordedCommand) => void) | undefined;\n private commandCounts = new Map<string, number>();\n\n constructor(options: CommandInspectorOptions = {}) {\n this.maxCommands = options.maxCommands ?? 5000;\n this.onCommand = options.onCommand;\n }\n\n record(type: CommandType, payload: Record<string, unknown>, duration?: number): RecordedCommand {\n const command: RecordedCommand = {\n id: this.nextId++,\n timestamp: performance.now(),\n type,\n payload,\n duration,\n };\n\n this.commands.push(command);\n if (this.commands.length > this.maxCommands) {\n this.commands.shift();\n }\n\n this.commandCounts.set(type, (this.commandCounts.get(type) ?? 0) + 1);\n this.onCommand?.(command);\n\n return command;\n }\n\n getCommands(): readonly RecordedCommand[] {\n return this.commands;\n }\n\n getCommandsByType(type: string): RecordedCommand[] {\n return this.commands.filter((c) => c.type === type);\n }\n\n getCommandsInRange(start: number, end: number): RecordedCommand[] {\n return this.commands.filter((c) => c.timestamp >= start && c.timestamp <= end);\n }\n\n getCounts(): Map<string, number> {\n return new Map(this.commandCounts);\n }\n\n getTotalCount(): number {\n return this.commands.length;\n }\n\n getRecent(count: number): RecordedCommand[] {\n return this.commands.slice(-count);\n }\n\n clear(): void {\n this.commands = [];\n this.commandCounts.clear();\n }\n\n /** Get a summary of command activity */\n getSummary(frameCount?: number): {\n total: number;\n byType: Record<string, number>;\n lastTimestamp: number | null;\n avgCommandsPerFrame: number;\n } {\n const byType: Record<string, number> = {};\n for (const [type, count] of this.commandCounts) {\n byType[type] = count;\n }\n\n const lastCommand =\n this.commands.length > 0 ? this.commands[this.commands.length - 1] : undefined;\n const lastTimestamp = lastCommand != null ? lastCommand.timestamp : null;\n\n return {\n total: this.commands.length,\n byType,\n lastTimestamp,\n avgCommandsPerFrame:\n frameCount != null && frameCount > 0 ? this.commands.length / frameCount : 0,\n };\n }\n}\n","import type { EventCategory, RecordedEvent } from \"./devtools.types\";\n\nexport interface EventInspectorOptions {\n maxEvents?: number | undefined;\n onEvent?: ((event: RecordedEvent) => void) | undefined;\n}\n\nexport class EventInspector {\n private events: RecordedEvent[] = [];\n private nextId = 0;\n private maxEvents: number;\n private onEvent: ((event: RecordedEvent) => void) | undefined;\n private categoryCounts = new Map<string, number>();\n\n constructor(options: EventInspectorOptions = {}) {\n this.maxEvents = options.maxEvents ?? 5000;\n this.onEvent = options.onEvent;\n }\n\n record(\n category: EventCategory,\n type: string,\n target?: string,\n data?: unknown,\n propagation?: \"captured\" | \"target\" | \"bubbled\",\n ): RecordedEvent {\n const event: RecordedEvent = {\n id: this.nextId++,\n timestamp: performance.now(),\n category,\n type,\n target,\n data,\n propagation,\n };\n\n this.events.push(event);\n if (this.events.length > this.maxEvents) {\n this.events.shift();\n }\n\n this.categoryCounts.set(category, (this.categoryCounts.get(category) ?? 0) + 1);\n this.onEvent?.(event);\n\n return event;\n }\n\n recordKeyboard(\n key: string,\n modifiers: { ctrl: boolean; shift: boolean; alt: boolean; meta: boolean },\n target?: string,\n ): RecordedEvent {\n return this.record(\"keyboard\", \"keydown\", target, { key, modifiers });\n }\n\n recordMouse(type: string, x: number, y: number, button?: string, target?: string): RecordedEvent {\n return this.record(\"mouse\", type, target, { x, y, button });\n }\n\n recordFocus(type: \"focus\" | \"blur\", nodeId: string): RecordedEvent {\n return this.record(\"focus\", type, nodeId);\n }\n\n recordResize(\n width: number,\n height: number,\n prevWidth?: number,\n prevHeight?: number,\n ): RecordedEvent {\n return this.record(\"resize\", \"resize\", undefined, { width, height, prevWidth, prevHeight });\n }\n\n recordLifecycle(type: string, data?: unknown): RecordedEvent {\n return this.record(\"lifecycle\", type, undefined, data);\n }\n\n getEvents(): readonly RecordedEvent[] {\n return this.events;\n }\n\n getEventsByCategory(category: EventCategory): RecordedEvent[] {\n return this.events.filter((e) => e.category === category);\n }\n\n getEventsByType(type: string): RecordedEvent[] {\n return this.events.filter((e) => e.type === type);\n }\n\n getEventsInRange(start: number, end: number): RecordedEvent[] {\n return this.events.filter((e) => e.timestamp >= start && e.timestamp <= end);\n }\n\n getCategoryCounts(): Map<string, number> {\n return new Map(this.categoryCounts);\n }\n\n getRecent(count: number): RecordedEvent[] {\n return this.events.slice(-count);\n }\n\n clear(): void {\n this.events = [];\n this.categoryCounts.clear();\n }\n\n get count(): number {\n return this.events.length;\n }\n}\n","import type { FrameMetrics, PerformanceSnapshot } from \"./devtools.types\";\n\nexport interface PerformanceTrackerOptions {\n maxFrames?: number | undefined;\n onFrame?: ((metrics: FrameMetrics) => void) | undefined;\n}\n\nexport class PerformanceTracker {\n private frames: FrameMetrics[] = [];\n private nextFrameNumber = 0;\n private maxFrames: number;\n private onFrame: ((frame: FrameMetrics) => void) | undefined;\n private frameStart = 0;\n private commandCountAtStart = 0;\n\n constructor(options: PerformanceTrackerOptions = {}) {\n this.maxFrames = options.maxFrames ?? 300;\n this.onFrame = options.onFrame;\n }\n\n /** Call at the start of a frame */\n beginFrame(commandCount: number): void {\n this.frameStart = performance.now();\n this.commandCountAtStart = commandCount;\n }\n\n /** Call at the end of a frame with metrics */\n endFrame(options: {\n dirtyRegionCount?: number;\n renderDuration?: number;\n layoutDuration?: number;\n paintDuration?: number;\n ffiDuration?: number;\n }): FrameMetrics {\n const now = performance.now();\n const metrics: FrameMetrics = {\n frameNumber: this.nextFrameNumber++,\n timestamp: now,\n duration: now - this.frameStart,\n commandCount: this.commandCountAtStart,\n dirtyRegionCount: options.dirtyRegionCount ?? 0,\n renderDuration: options.renderDuration,\n layoutDuration: options.layoutDuration,\n paintDuration: options.paintDuration,\n ffiDuration: options.ffiDuration,\n };\n\n this.frames.push(metrics);\n if (this.frames.length > this.maxFrames) {\n this.frames.shift();\n }\n\n this.onFrame?.(metrics);\n return metrics;\n }\n\n /** Record a frame with all metrics at once */\n recordFrame(metrics: Partial<FrameMetrics> & { duration: number }): FrameMetrics {\n const { timestamp: _ignored, ...rest } = metrics;\n const frame: FrameMetrics = {\n frameNumber: this.nextFrameNumber++,\n timestamp: performance.now(),\n commandCount: 0,\n dirtyRegionCount: 0,\n ...rest,\n };\n\n this.frames.push(frame);\n if (this.frames.length > this.maxFrames) {\n this.frames.shift();\n }\n\n this.onFrame?.(frame);\n return frame;\n }\n\n getFrames(): readonly FrameMetrics[] {\n return this.frames;\n }\n\n getRecentFrames(count: number): FrameMetrics[] {\n return this.frames.slice(-count);\n }\n\n /** Calculate current FPS based on recent frames */\n getFps(sampleSize = 60): number {\n const recent = this.frames.slice(-sampleSize);\n if (recent.length < 2) return 0;\n\n const first = recent[0];\n const last = recent[recent.length - 1];\n if (first === undefined || last === undefined) return 0;\n const elapsed = last.timestamp - first.timestamp;\n\n if (elapsed <= 0) return 0;\n return ((recent.length - 1) / elapsed) * 1000;\n }\n\n /** Get a full performance snapshot */\n getSnapshot(): PerformanceSnapshot {\n const frames = this.frames;\n const durations = frames.map((f) => f.duration);\n\n const fps = this.getFps();\n const avgFrameTime =\n durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0;\n const minFrameTime = durations.length > 0 ? Math.min(...durations) : 0;\n const maxFrameTime = durations.length > 0 ? Math.max(...durations) : 0;\n const totalFrames = frames.length;\n const droppedFrames = frames.filter((f) => f.duration > 33.33).length; // >2 frames at 60fps\n const commandCount = frames.reduce((sum, f) => sum + f.commandCount, 0);\n const dirtyNodeCount = frames.reduce((sum, f) => sum + f.dirtyRegionCount, 0);\n\n let memoryUsage: PerformanceSnapshot[\"memoryUsage\"] | undefined;\n if (typeof globalThis !== \"undefined\" && \"performance\" in globalThis) {\n const perf = globalThis.performance as {\n memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number; totalJSHeapSize: number };\n };\n /* c8 ignore start — performance.memory is Chrome-only, not available in Node.js */\n if (perf.memory) {\n memoryUsage = {\n heapUsed: perf.memory.usedJSHeapSize,\n heapTotal: perf.memory.jsHeapSizeLimit,\n external: perf.memory.totalJSHeapSize,\n };\n }\n /* c8 ignore stop */\n }\n\n return {\n fps,\n avgFrameTime,\n minFrameTime,\n maxFrameTime,\n totalFrames,\n droppedFrames,\n commandCount,\n dirtyNodeCount,\n memoryUsage,\n };\n }\n\n clear(): void {\n this.frames = [];\n this.nextFrameNumber = 0;\n }\n\n get count(): number {\n return this.frames.length;\n }\n}\n","import type { DevToolsNode } from \"./devtools.types\";\n\nexport interface TreeInspectorOptions {\n onTreeUpdate?: ((root: DevToolsNode | null) => void) | undefined;\n}\n\nexport class TreeInspector {\n private root: DevToolsNode | null = null;\n private nodeIndex = new Map<string, DevToolsNode>();\n private dirtyNodes = new Set<string>();\n private onTreeUpdate: ((root: DevToolsNode | null) => void) | undefined;\n\n constructor(options: TreeInspectorOptions = {}) {\n this.onTreeUpdate = options.onTreeUpdate;\n }\n\n /** Build a tree from a flat list of node descriptors */\n buildTree(\n nodes: Array<{\n id: string;\n type: string;\n parent?: string;\n props?: Record<string, unknown>;\n style?: Record<string, unknown>;\n layout?: { x: number; y: number; width: number; height: number };\n dirty?: boolean;\n visible?: boolean;\n zIndex?: number;\n }>,\n ): DevToolsNode {\n this.nodeIndex.clear();\n this.dirtyNodes.clear();\n\n // Create all nodes\n const nodeMap = new Map<string, DevToolsNode>();\n for (const n of nodes) {\n const treeNode: DevToolsNode = {\n id: n.id,\n type: n.type,\n props: n.props ?? {},\n style: n.style,\n layout: n.layout,\n children: [],\n parent: n.parent,\n dirty: n.dirty,\n visible: n.visible,\n zIndex: n.zIndex,\n };\n nodeMap.set(n.id, treeNode);\n this.nodeIndex.set(n.id, treeNode);\n if (n.dirty) this.dirtyNodes.add(n.id);\n }\n\n // Wire parent-child relationships\n let root: DevToolsNode | null = null;\n for (const treeNode of nodeMap.values()) {\n if (treeNode.parent) {\n const parentNode = nodeMap.get(treeNode.parent);\n if (parentNode) {\n parentNode.children.push(treeNode);\n }\n } else {\n root = treeNode;\n }\n }\n\n this.root = root;\n this.onTreeUpdate?.(root);\n return root ?? { id: \"empty\", type: \"Empty\", props: {}, children: [] };\n }\n\n /** Update a single node's properties */\n updateNode(id: string, updates: Partial<Omit<DevToolsNode, \"id\" | \"children\">>): void {\n const node = this.nodeIndex.get(id);\n if (!node) return;\n\n if (updates.props !== undefined) node.props = updates.props;\n if (updates.style !== undefined) node.style = updates.style;\n if (updates.layout !== undefined) node.layout = updates.layout;\n if (updates.dirty !== undefined) {\n node.dirty = updates.dirty;\n if (updates.dirty) {\n this.dirtyNodes.add(id);\n } else {\n this.dirtyNodes.delete(id);\n }\n }\n if (updates.visible !== undefined) node.visible = updates.visible;\n if (updates.zIndex !== undefined) node.zIndex = updates.zIndex;\n }\n\n /** Mark a node as dirty */\n markDirty(id: string): void {\n this.dirtyNodes.add(id);\n const node = this.nodeIndex.get(id);\n if (node) node.dirty = true;\n }\n\n /** Clear dirty state for all nodes */\n clearDirty(): void {\n for (const id of this.dirtyNodes) {\n const node = this.nodeIndex.get(id);\n if (node) node.dirty = false;\n }\n this.dirtyNodes.clear();\n }\n\n getNode(id: string): DevToolsNode | undefined {\n return this.nodeIndex.get(id);\n }\n\n getRoot(): DevToolsNode | null {\n return this.root;\n }\n\n getDirtyNodes(): DevToolsNode[] {\n return [...this.dirtyNodes]\n .map((id) => this.nodeIndex.get(id))\n .filter((n): n is DevToolsNode => n !== undefined);\n }\n\n /** Find nodes matching a predicate */\n findNodes(predicate: (node: DevToolsNode) => boolean): DevToolsNode[] {\n const results: DevToolsNode[] = [];\n const walk = (node: DevToolsNode) => {\n if (predicate(node)) results.push(node);\n for (const child of node.children) {\n walk(child);\n }\n };\n if (this.root) walk(this.root);\n return results;\n }\n\n /** Get the path from root to a given node */\n getPath(nodeId: string): DevToolsNode[] {\n const path: DevToolsNode[] = [];\n let current = this.nodeIndex.get(nodeId);\n while (current) {\n path.unshift(current);\n current = current.parent ? this.nodeIndex.get(current.parent) : undefined;\n }\n return path;\n }\n\n /** Count total nodes in the tree */\n countNodes(): number {\n return this.nodeIndex.size;\n }\n\n /** Get all nodes as a flat array */\n getAllNodes(): DevToolsNode[] {\n return [...this.nodeIndex.values()];\n }\n\n clear(): void {\n this.root = null;\n this.nodeIndex.clear();\n this.dirtyNodes.clear();\n }\n}\n","import type { SchedulerSnapshot } from \"./devtools.types\";\n\nexport interface SchedulerInspectorOptions {\n onFrameDrop?: ((droppedCount: number) => void) | undefined;\n}\n\nexport class SchedulerInspector {\n private frameCount = 0;\n private droppedFrames = 0;\n private pendingFrames = 0;\n private isRunning = false;\n private isRendering = false;\n private hasScheduledRender = false;\n private highestPriority = \"idle\";\n private idleCallbacksPending = 0;\n private animationFramesPending = 0;\n private frameBudgetMs = 16.67;\n private utilization = 0;\n private onFrameDrop: ((droppedCount: number) => void) | undefined;\n\n constructor(options: SchedulerInspectorOptions = {}) {\n this.onFrameDrop = options.onFrameDrop;\n }\n\n updateState(state: Partial<SchedulerSnapshot>): void {\n if (state.isRunning !== undefined) this.isRunning = state.isRunning;\n if (state.isRendering !== undefined) this.isRendering = state.isRendering;\n if (state.hasScheduledRender !== undefined) this.hasScheduledRender = state.hasScheduledRender;\n if (state.frameCount !== undefined) this.frameCount = state.frameCount;\n if (state.pendingFrames !== undefined) this.pendingFrames = state.pendingFrames;\n if (state.highestPriority !== undefined) this.highestPriority = state.highestPriority;\n if (state.idleCallbacksPending !== undefined)\n this.idleCallbacksPending = state.idleCallbacksPending;\n if (state.animationFramesPending !== undefined)\n this.animationFramesPending = state.animationFramesPending;\n if (state.frameBudgetMs !== undefined) this.frameBudgetMs = state.frameBudgetMs;\n if (state.utilization !== undefined) this.utilization = state.utilization;\n }\n\n recordFrameDrop(): void {\n this.droppedFrames++;\n this.onFrameDrop?.(this.droppedFrames);\n }\n\n incrementFrameCount(): void {\n this.frameCount++;\n }\n\n getSnapshot(): SchedulerSnapshot {\n return {\n isRunning: this.isRunning,\n isRendering: this.isRendering,\n hasScheduledRender: this.hasScheduledRender,\n frameCount: this.frameCount,\n droppedFrames: this.droppedFrames,\n pendingFrames: this.pendingFrames,\n highestPriority: this.highestPriority,\n idleCallbacksPending: this.idleCallbacksPending,\n animationFramesPending: this.animationFramesPending,\n frameBudgetMs: this.frameBudgetMs,\n utilization: this.utilization,\n };\n }\n\n getDropRate(): number {\n if (this.frameCount === 0) return 0;\n return this.droppedFrames / this.frameCount;\n }\n\n clear(): void {\n this.frameCount = 0;\n this.droppedFrames = 0;\n this.pendingFrames = 0;\n this.isRunning = false;\n this.isRendering = false;\n this.hasScheduledRender = false;\n this.highestPriority = \"idle\";\n this.idleCallbacksPending = 0;\n this.animationFramesPending = 0;\n this.frameBudgetMs = 16.67;\n this.utilization = 0;\n }\n}\n","import type { FocusSnapshot } from \"./devtools.types\";\n\nexport interface FocusInspectorOptions {\n onFocusChange?: ((snapshot: FocusSnapshot) => void) | undefined;\n}\n\nexport class FocusInspector {\n private focusedNodeId: string | null = null;\n private previousNodeId: string | null = null;\n private focusableNodes: string[] = [];\n private tabOrder: string[] = [];\n private currentScope: string | null = null;\n private focusHistory: Array<{\n timestamp: number;\n nodeId: string | null;\n type: \"focus\" | \"blur\";\n }> = [];\n private onFocusChange: ((snapshot: FocusSnapshot) => void) | undefined;\n\n constructor(options: FocusInspectorOptions = {}) {\n this.onFocusChange = options.onFocusChange;\n }\n\n recordFocus(nodeId: string): void {\n this.previousNodeId = this.focusedNodeId;\n this.focusedNodeId = nodeId;\n this.focusHistory.push({ timestamp: performance.now(), nodeId, type: \"focus\" });\n this.onFocusChange?.(this.getSnapshot());\n }\n\n recordBlur(nodeId: string): void {\n if (this.focusedNodeId === nodeId) {\n this.previousNodeId = nodeId;\n this.focusedNodeId = null;\n }\n this.focusHistory.push({ timestamp: performance.now(), nodeId, type: \"blur\" });\n this.onFocusChange?.(this.getSnapshot());\n }\n\n setFocusableNodes(nodes: string[]): void {\n this.focusableNodes = nodes;\n }\n\n setTabOrder(order: string[]): void {\n this.tabOrder = order;\n }\n\n setScope(scope: string | null): void {\n this.currentScope = scope;\n }\n\n getSnapshot(): FocusSnapshot {\n return {\n focusedNodeId: this.focusedNodeId,\n previousNodeId: this.previousNodeId,\n focusableNodes: [...this.focusableNodes],\n tabOrder: [...this.tabOrder],\n currentScope: this.currentScope,\n };\n }\n\n getFocusHistory(): Array<{ timestamp: number; nodeId: string | null; type: \"focus\" | \"blur\" }> {\n return this.focusHistory;\n }\n\n getRecentFocusChanges(\n count: number,\n ): Array<{ timestamp: number; nodeId: string | null; type: \"focus\" | \"blur\" }> {\n return this.focusHistory.slice(-count);\n }\n\n isFocused(nodeId: string): boolean {\n return this.focusedNodeId === nodeId;\n }\n\n clear(): void {\n this.focusedNodeId = null;\n this.previousNodeId = null;\n this.focusableNodes = [];\n this.tabOrder = [];\n this.currentScope = null;\n this.focusHistory = [];\n }\n}\n","import type { TerminalCapabilities } from \"./devtools.types\";\n\nexport interface CapabilityInspectorOptions {\n onCapabilitiesDetected?: ((caps: TerminalCapabilities) => void) | undefined;\n}\n\nconst DEFAULT_CAPABILITIES: TerminalCapabilities = {\n trueColor: false,\n kittyKeyboard: false,\n mouseSupport: false,\n osc52: false,\n osc8: false,\n pixelSupport: false,\n alternateScreen: false,\n terminalBrand: \"unknown\",\n terminalSize: { columns: 80, rows: 24 },\n syncUpdate: false,\n bracketedPaste: false,\n focusEvents: false,\n strikethrough: false,\n underlineColor: false,\n cursorStyle: false,\n hyperlinks: false,\n inlineImages: false,\n sixel: false,\n};\n\nexport class CapabilityInspector {\n private capabilities: TerminalCapabilities = { ...DEFAULT_CAPABILITIES };\n private onCapabilitiesDetected: ((caps: TerminalCapabilities) => void) | undefined;\n\n constructor(options: CapabilityInspectorOptions = {}) {\n this.onCapabilitiesDetected = options.onCapabilitiesDetected;\n }\n\n update(capabilities: Partial<TerminalCapabilities>): void {\n Object.assign(this.capabilities, capabilities);\n this.onCapabilitiesDetected?.(this.capabilities);\n }\n\n updateFromNative(capabilitiesJson: string): void {\n try {\n const parsed = JSON.parse(capabilitiesJson) as Partial<TerminalCapabilities>;\n this.update(parsed);\n } catch {\n // Malformed capabilities JSON, ignore\n }\n }\n\n get(): TerminalCapabilities {\n return { ...this.capabilities };\n }\n\n has(capability: keyof TerminalCapabilities): boolean {\n const value = this.capabilities[capability];\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return value !== \"unknown\" && value !== \"\";\n if (typeof value === \"object\" && value !== null) return true;\n /* c8 ignore next 2 — return false is unreachable: all capabilities are boolean, string, or object */\n return false;\n }\n\n getSummary(): string[] {\n const features: string[] = [];\n if (this.capabilities.trueColor) features.push(\"trueColor\");\n if (this.capabilities.kittyKeyboard) features.push(\"kittyKeyboard\");\n if (this.capabilities.mouseSupport) features.push(\"mouse\");\n if (this.capabilities.osc52) features.push(\"osc52\");\n if (this.capabilities.osc8) features.push(\"osc8\");\n if (this.capabilities.pixelSupport) features.push(\"pixel\");\n if (this.capabilities.alternateScreen) features.push(\"altScreen\");\n if (this.capabilities.syncUpdate) features.push(\"sync\");\n if (this.capabilities.bracketedPaste) features.push(\"bracketedPaste\");\n if (this.capabilities.focusEvents) features.push(\"focusEvents\");\n if (this.capabilities.strikethrough) features.push(\"strikethrough\");\n if (this.capabilities.underlineColor) features.push(\"underlineColor\");\n if (this.capabilities.cursorStyle) features.push(\"cursorStyle\");\n if (this.capabilities.hyperlinks) features.push(\"hyperlinks\");\n if (this.capabilities.inlineImages) features.push(\"inlineImages\");\n if (this.capabilities.sixel) features.push(\"sixel\");\n return features;\n }\n\n clear(): void {\n this.capabilities = { ...DEFAULT_CAPABILITIES };\n }\n}\n","import type { EventCategory, TimelineEntry } from \"./devtools.types\";\n\nexport interface DevToolsTimelineOptions {\n maxEntries?: number | undefined;\n onEntry?: ((entry: TimelineEntry) => void) | undefined;\n}\n\nexport class DevToolsTimeline {\n private entries: TimelineEntry[] = [];\n private nextId = 0;\n private maxEntries: number;\n private onEntry: ((entry: TimelineEntry) => void) | undefined;\n\n constructor(options: DevToolsTimelineOptions = {}) {\n this.maxEntries = options.maxEntries ?? 5000;\n this.onEntry = options.onEntry;\n }\n\n record(\n category: TimelineEntry[\"category\"],\n type: string,\n duration?: number,\n data?: unknown,\n ): TimelineEntry {\n const entry: TimelineEntry = {\n id: this.nextId++,\n timestamp: performance.now(),\n category,\n type,\n duration,\n data,\n };\n\n this.entries.push(entry);\n if (this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n\n this.onEntry?.(entry);\n return entry;\n }\n\n recordRender(duration: number, data?: unknown): TimelineEntry {\n return this.record(\"render\", \"frame\", duration, data);\n }\n\n recordCommand(type: string, duration?: number): TimelineEntry {\n return this.record(\"command\", type, duration);\n }\n\n recordEvent(category: EventCategory, type: string, data?: unknown): TimelineEntry {\n return this.record(category, type, undefined, data);\n }\n\n getEntries(): readonly TimelineEntry[] {\n return this.entries;\n }\n\n getEntriesByCategory(category: TimelineEntry[\"category\"]): TimelineEntry[] {\n return this.entries.filter((e) => e.category === category);\n }\n\n getEntriesInRange(start: number, end: number): TimelineEntry[] {\n return this.entries.filter((e) => e.timestamp >= start && e.timestamp <= end);\n }\n\n getRecent(count: number): TimelineEntry[] {\n return this.entries.slice(-count);\n }\n\n /** Get entries grouped by time windows */\n getGroupedByWindow(\n windowMs: number,\n ): Array<{ start: number; end: number; entries: TimelineEntry[] }> {\n if (this.entries.length === 0) return [];\n\n const groups: Array<{ start: number; end: number; entries: TimelineEntry[] }> = [];\n let currentGroup: { start: number; end: number; entries: TimelineEntry[] } | null = null;\n\n for (const entry of this.entries) {\n if (!currentGroup || entry.timestamp - currentGroup.start >= windowMs) {\n if (currentGroup) groups.push(currentGroup);\n currentGroup = { start: entry.timestamp, end: entry.timestamp, entries: [entry] };\n } else {\n currentGroup.entries.push(entry);\n currentGroup.end = entry.timestamp;\n }\n }\n\n if (currentGroup) groups.push(currentGroup);\n return groups;\n }\n\n clear(): void {\n this.entries = [];\n }\n\n get count(): number {\n return this.entries.length;\n }\n}\n","import type { DevToolsNode, SnapshotDiff, TreeSnapshot } from \"./devtools.types\";\n\nexport interface SnapshotOptions {\n maxSnapshots?: number | undefined;\n}\n\nexport class SnapshotManager {\n private snapshots: TreeSnapshot[] = [];\n private nextId = 0;\n private maxSnapshots: number;\n\n constructor(options: SnapshotOptions = {}) {\n this.maxSnapshots = options.maxSnapshots ?? 50;\n }\n\n /** Capture a snapshot of the current tree */\n capture(tree: DevToolsNode): TreeSnapshot {\n const snapshot: TreeSnapshot = {\n id: this.nextId++,\n timestamp: performance.now(),\n tree: structuredClone(tree),\n nodeCount: this.countNodes(tree),\n };\n\n this.snapshots.push(snapshot);\n if (this.snapshots.length > this.maxSnapshots) {\n this.snapshots.shift();\n }\n\n return snapshot;\n }\n\n /** Compare two snapshots and return the diff */\n diff(snapshotA: number, snapshotB: number): SnapshotDiff | null {\n const a = this.snapshots.find((s) => s.id === snapshotA);\n const b = this.snapshots.find((s) => s.id === snapshotB);\n if (!a || !b) return null;\n\n return this.diffTrees(a.tree, b.tree);\n }\n\n /** Compare two trees */\n diffTrees(a: DevToolsNode, b: DevToolsNode): SnapshotDiff {\n const aNodes = this.flattenTree(a);\n const bNodes = this.flattenTree(b);\n\n const aIds = new Set(aNodes.map((n) => n.id));\n const bIds = new Set(bNodes.map((n) => n.id));\n\n const added = [...bIds].filter((id) => !aIds.has(id));\n const removed = [...aIds].filter((id) => !bIds.has(id));\n\n const changed: SnapshotDiff[\"changed\"] = [];\n const aMap = new Map(aNodes.map((n) => [n.id, n]));\n const bMap = new Map(bNodes.map((n) => [n.id, n]));\n\n for (const id of aIds) {\n if (!bIds.has(id)) continue;\n const aNode = aMap.get(id);\n const bNode = bMap.get(id);\n /* istanbul ignore if — safety check: both nodes always exist since id is verified in both Maps */\n if (aNode === undefined || bNode === undefined) continue;\n\n // NOTE: JSON.stringify comparison is order-sensitive; acceptable for snapshot diffs\n if (JSON.stringify(aNode.props) !== JSON.stringify(bNode.props)) {\n changed.push({ id, field: \"props\", old: aNode.props, new: bNode.props });\n }\n /* c8 ignore start — style and layout !== comparisons are fully tested; remaining branch is a v8 tracking artifact */\n if (JSON.stringify(aNode.style) !== JSON.stringify(bNode.style)) {\n changed.push({ id, field: \"style\", old: aNode.style, new: bNode.style });\n }\n if (JSON.stringify(aNode.layout) !== JSON.stringify(bNode.layout)) {\n changed.push({ id, field: \"layout\", old: aNode.layout, new: bNode.layout });\n }\n /* c8 ignore stop */\n }\n\n return { added, removed, changed };\n }\n\n getSnapshots(): readonly TreeSnapshot[] {\n return this.snapshots;\n }\n\n getSnapshot(id: number): TreeSnapshot | undefined {\n return this.snapshots.find((s) => s.id === id);\n }\n\n private flattenTree(node: DevToolsNode): DevToolsNode[] {\n const result: DevToolsNode[] = [node];\n for (const child of node.children) {\n result.push(...this.flattenTree(child));\n }\n return result;\n }\n\n private countNodes(node: DevToolsNode): number {\n let count = 1;\n for (const child of node.children) {\n count += this.countNodes(child);\n }\n return count;\n }\n\n clear(): void {\n this.snapshots = [];\n }\n}\n","import type {\n DevToolsNode,\n DiagnosticExport,\n FocusSnapshot,\n FrameMetrics,\n LogEntry,\n PerformanceSnapshot,\n RecordedCommand,\n RecordedEvent,\n SchedulerSnapshot,\n TerminalCapabilities,\n TimelineEntry,\n TreeSnapshot,\n} from \"./devtools.types\";\n\nexport interface ExportOptions {\n /** Include logs in the export */\n includeLogs?: boolean | undefined;\n /** Include commands in the export */\n includeCommands?: boolean | undefined;\n /** Include events in the export */\n includeEvents?: boolean | undefined;\n /** Include frame metrics in the export */\n includeFrames?: boolean | undefined;\n /** Include timeline in the export */\n includeTimeline?: boolean | undefined;\n /** Include snapshots in the export */\n includeSnapshots?: boolean | undefined;\n}\n\nexport interface ExportData {\n /** Logs to include */\n logs?: readonly LogEntry[] | undefined;\n /** Commands to include */\n commands?: readonly RecordedCommand[] | undefined;\n /** Events to include */\n events?: readonly RecordedEvent[] | undefined;\n /** Frame metrics to include */\n frames?: readonly FrameMetrics[] | undefined;\n /** Performance snapshot */\n performance?: PerformanceSnapshot | undefined;\n /** Render tree */\n tree?: DevToolsNode | undefined;\n /** Scheduler snapshot */\n scheduler?: SchedulerSnapshot | undefined;\n /** Focus snapshot */\n focus?: FocusSnapshot | undefined;\n /** Terminal capabilities */\n capabilities?: TerminalCapabilities | undefined;\n /** Timeline entries */\n timeline?: readonly TimelineEntry[] | undefined;\n /** Tree snapshots */\n snapshots?: readonly TreeSnapshot[] | undefined;\n}\n\n/** Create a diagnostic export from collected data */\nexport function createExport(data: ExportData, options: ExportOptions = {}): DiagnosticExport {\n const {\n includeLogs = true,\n includeCommands = true,\n includeEvents = true,\n includeFrames = true,\n includeTimeline = true,\n includeSnapshots = true,\n } = options;\n\n return {\n version: \"1.0.0\",\n timestamp: performance.now(),\n duration: 0,\n logs: includeLogs ? (data.logs ?? []) : [],\n commands: includeCommands ? (data.commands ?? []) : [],\n events: includeEvents ? (data.events ?? []) : [],\n frames: includeFrames ? (data.frames ?? []) : [],\n performance: data.performance ?? {\n fps: 0,\n avgFrameTime: 0,\n minFrameTime: 0,\n maxFrameTime: 0,\n totalFrames: 0,\n droppedFrames: 0,\n commandCount: 0,\n dirtyNodeCount: 0,\n },\n tree: data.tree,\n scheduler: data.scheduler,\n focus: data.focus,\n capabilities: data.capabilities,\n timeline: includeTimeline ? (data.timeline ?? []) : [],\n snapshots: includeSnapshots ? (data.snapshots ?? []) : [],\n };\n}\n\n/** Serialize a diagnostic export to JSON */\nexport function exportToJson(exportData: DiagnosticExport): string {\n return JSON.stringify(exportData, null, 2);\n}\n\n/** Create a summary report from a diagnostic export */\nexport function createSummary(exportData: DiagnosticExport): string {\n const lines: string[] = [\n \"BetterTUI DevTools Diagnostic Report\",\n \"=====================================\",\n \"\",\n `Version: ${exportData.version}`,\n `Duration: ${(exportData.duration / 1000).toFixed(2)}s`,\n \"\",\n \"## Performance\",\n ` FPS: ${exportData.performance.fps.toFixed(1)}`,\n ` Avg Frame Time: ${exportData.performance.avgFrameTime.toFixed(2)}ms`,\n ` Dropped Frames: ${exportData.performance.droppedFrames}/${exportData.performance.totalFrames}`,\n ` Total Commands: ${exportData.performance.commandCount}`,\n ` Avg Commands/Frame: ${exportData.performance.totalFrames > 0 ? (exportData.commands.length / exportData.performance.totalFrames).toFixed(2) : \"0.00\"}`,\n \"\",\n \"## Activity\",\n ` Logs: ${exportData.logs.length}`,\n ` Commands: ${exportData.commands.length}`,\n ` Events: ${exportData.events.length}`,\n ` Timeline Entries: ${exportData.timeline.length}`,\n ` Snapshots: ${exportData.snapshots.length}`,\n ];\n\n if (exportData.scheduler) {\n lines.push(\n \"\",\n \"## Scheduler\",\n ` Frame Count: ${exportData.scheduler.frameCount}`,\n ` Dropped: ${exportData.scheduler.droppedFrames}`,\n ` Utilization: ${(exportData.scheduler.utilization * 100).toFixed(1)}%`,\n );\n }\n\n if (exportData.focus) {\n lines.push(\n \"\",\n \"## Focus\",\n ` Focused: ${exportData.focus.focusedNodeId ?? \"none\"}`,\n ` Focusable Nodes: ${exportData.focus.focusableNodes.length}`,\n );\n }\n\n if (exportData.capabilities) {\n lines.push(\n \"\",\n \"## Terminal\",\n ` Brand: ${exportData.capabilities.terminalBrand}`,\n ` Size: ${exportData.capabilities.terminalSize.columns}x${exportData.capabilities.terminalSize.rows}`,\n ` True Color: ${exportData.capabilities.trueColor}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","import { EventEmitter } from \"node:events\";\nimport { Writable } from \"node:stream\";\n\nexport type CapturedOutput = {\n stream: \"stdout\" | \"stderr\";\n output: string;\n};\n\nexport class Capture extends EventEmitter {\n private outputCache: CapturedOutput[] = [];\n\n get size(): number {\n return this.outputCache.length;\n }\n\n write(stream: \"stdout\" | \"stderr\", data: string): void {\n this.outputCache.push({ stream, output: data });\n this.emit(\"write\", stream, data);\n }\n\n claimOutput(): string {\n const output = this.outputCache.map((o) => o.output).join(\"\");\n this.clear();\n return output;\n }\n\n clear(): void {\n this.outputCache = [];\n }\n}\n\nexport class CapturedWritableStream extends Writable {\n public isTTY = true;\n public columns: number = process.stdout?.columns || 80;\n public rows: number = process.stdout?.rows || 24;\n\n constructor(\n private stream: \"stdout\" | \"stderr\",\n private captureInstance: Capture,\n ) {\n super();\n }\n\n _write(\n chunk: unknown,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void,\n ): void {\n const data = typeof chunk === \"string\" ? chunk : String(chunk);\n this.captureInstance.write(this.stream, data);\n callback();\n }\n\n getColorDepth(): number {\n return process.stdout?.getColorDepth?.() || 8;\n }\n}\n","import { Console } from \"node:console\";\nimport { EventEmitter } from \"node:events\";\nimport { writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { env, registerEnvVar } from \"../lib/env\";\nimport { Capture, CapturedWritableStream } from \"../lib/outputCapture\";\nimport { singleton } from \"../lib/singleton\";\n\nexport enum ConsoleLogLevel {\n LOG = \"LOG\",\n INFO = \"INFO\",\n WARN = \"WARN\",\n ERROR = \"ERROR\",\n DEBUG = \"DEBUG\",\n}\n\nexport interface CallerInfo {\n functionName: string;\n fullPath: string;\n fileName: string;\n lineNumber: number;\n columnNumber: number;\n}\n\nfunction getCallerInfo(): CallerInfo | null {\n const err = new Error();\n const stackLines = err.stack?.split(\"\\n\").slice(5) || [];\n if (!stackLines.length) return null;\n\n const callerLine = stackLines[0]?.trim();\n if (!callerLine) return null;\n\n const regex = /at\\s+(?:([\\w$.<>]+)\\s+\\()?((?:\\/|[A-Za-z]:\\\\)[^:]+):(\\d+):(\\d+)\\)?/;\n const match = callerLine.match(regex);\n if (!match) return null;\n\n return {\n functionName: match[1] || \"<anonymous>\",\n fullPath: match[2] || \"\",\n fileName: (match[2] || \"\").split(/[\\\\/]/).pop() || \"<unknown>\",\n lineNumber: Number.parseInt(match[3] || \"0\", 10),\n columnNumber: Number.parseInt(match[4] || \"0\", 10),\n };\n}\n\nexport type ConsoleLogEntry = [Date, ConsoleLogLevel, unknown[], CallerInfo | null];\n\nexport const capture = singleton(\"ConsoleCapture\", () => new Capture());\n\nregisterEnvVar({\n name: \"BTUI_USE_CONSOLE\",\n description: \"Enable global console.* capture for the built-in terminal console overlay.\",\n type: \"boolean\",\n default: true,\n});\n\nregisterEnvVar({\n name: \"SHOW_CONSOLE\",\n description: \"Open the built-in terminal console overlay at startup.\",\n type: \"boolean\",\n default: false,\n});\n\nexport class TerminalConsoleCache extends EventEmitter {\n private _cachedLogs: ConsoleLogEntry[] = [];\n private readonly MAX_CACHE_SIZE = 1000;\n private _collectCallerInfo = false;\n private _cachingEnabled = true;\n private _originalConsole: typeof console | null = null;\n private _active = false;\n\n get cachedLogs(): ConsoleLogEntry[] {\n return this._cachedLogs;\n }\n\n public activate(): void {\n if (this._active) return;\n if (!this._originalConsole) {\n this._originalConsole = globalThis.console;\n }\n this.setupConsoleCapture();\n this.overrideConsoleMethods();\n this._active = true;\n }\n\n private setupConsoleCapture(): void {\n if (!env.BTUI_USE_CONSOLE) return;\n\n const mockStdout = new CapturedWritableStream(\"stdout\", capture);\n const mockStderr = new CapturedWritableStream(\"stderr\", capture);\n\n globalThis.console = new Console({\n stdout: mockStdout,\n stderr: mockStderr,\n colorMode: true,\n inspectOptions: {\n compact: false,\n breakLength: 80,\n depth: 2,\n },\n }) as unknown as Console;\n }\n\n private overrideConsoleMethods(): void {\n console.log = (...args: unknown[]) => {\n this.appendToConsole(ConsoleLogLevel.LOG, ...args);\n };\n\n console.info = (...args: unknown[]) => {\n this.appendToConsole(ConsoleLogLevel.INFO, ...args);\n };\n\n console.warn = (...args: unknown[]) => {\n this.appendToConsole(ConsoleLogLevel.WARN, ...args);\n };\n\n console.error = (...args: unknown[]) => {\n this.appendToConsole(ConsoleLogLevel.ERROR, ...args);\n };\n\n console.debug = (...args: unknown[]) => {\n this.appendToConsole(ConsoleLogLevel.DEBUG, ...args);\n };\n\n // Polyfill React / devtools timeStamp if missing\n if (typeof console.timeStamp !== \"function\") {\n (console as unknown as Record<string, unknown>).timeStamp = () => {};\n }\n }\n\n public setCollectCallerInfo(enabled: boolean): void {\n this._collectCallerInfo = enabled;\n }\n\n public clearConsole(): void {\n this._cachedLogs = [];\n }\n\n public setCachingEnabled(enabled: boolean): void {\n this._cachingEnabled = enabled;\n }\n\n public deactivate(): void {\n if (!this._active) return;\n this.restoreOriginalConsole();\n this._active = false;\n }\n\n private restoreOriginalConsole(): void {\n if (this._originalConsole) {\n globalThis.console = this._originalConsole;\n }\n }\n\n public addLogEntry(level: ConsoleLogLevel, ...args: unknown[]): ConsoleLogEntry {\n const callerInfo = this._collectCallerInfo ? getCallerInfo() : null;\n const logEntry: ConsoleLogEntry = [new Date(), level, args, callerInfo];\n\n if (this._cachingEnabled) {\n if (this._cachedLogs.length >= this.MAX_CACHE_SIZE) {\n this._cachedLogs.shift();\n }\n this._cachedLogs.push(logEntry);\n }\n\n return logEntry;\n }\n\n private appendToConsole(level: ConsoleLogLevel, ...args: unknown[]): void {\n const entry = this.addLogEntry(level, ...args);\n this.emit(\"entry\", entry);\n }\n\n public destroy(): void {\n this.deactivate();\n }\n}\n\nexport const terminalConsoleCache = singleton(\"TerminalConsoleCache\", () => {\n const instance = new TerminalConsoleCache();\n if (typeof process !== \"undefined\") {\n process.on(\"exit\", () => {\n if (env.BTUI_DUMP_CAPTURES) {\n try {\n const timestamp = Date.now();\n const filepath = join(process.cwd(), `_btui_dump_${timestamp}.log`);\n const logs = instance.cachedLogs\n .map(\n ([date, level, args]) =>\n `[${date.toISOString()}] [${level}] ${args.map(String).join(\" \")}`,\n )\n .join(\"\\n\");\n writeFileSync(filepath, logs, \"utf8\");\n } catch {\n // ignore write error during process exit\n }\n }\n instance.destroy();\n });\n }\n return instance;\n});\n","/**\n * ANSI helpers for the debug overlay.\n *\n * The overlay is composited by writing absolute-positioned ANSI to stdout\n * *after* the engine's frame output (the engine returns finished base64 ANSI\n * bytes; there is no TS-accessible cell buffer). These helpers build the escape\n * sequences and lay out box-drawn panels. All coordinates are 1-based to match\n * the terminal's `CSI row;col H` convention.\n */\n\n// ─── Cursor control ──────────────────────────────────────────────────────────\n\n/** Save the cursor position (DEC save). */\nexport const SAVE_CURSOR = \"\\x1b7\";\n\n/** Restore the cursor position (DEC restore). */\nexport const RESTORE_CURSOR = \"\\x1b8\";\n\n/** Reset all SGR attributes. */\nexport const RESET = \"\\x1b[0m\";\n\n/** Move the cursor to an absolute (row, col), both 1-based. */\nexport function moveTo(row: number, col: number): string {\n const r = Math.max(1, Math.floor(row));\n const c = Math.max(1, Math.floor(col));\n return `\\x1b[${r};${c}H`;\n}\n\n// ─── SGR helpers ─────────────────────────────────────────────────────────────\n\n/** Wrap text in an SGR sequence and a reset. */\nexport function sgr(text: string, ...codes: number[]): string {\n if (codes.length === 0) return text;\n return `\\x1b[${codes.join(\";\")}m${text}${RESET}`;\n}\n\n/** 24-bit foreground color. */\nexport function fg(r: number, g: number, b: number): string {\n return `\\x1b[38;2;${r};${g};${b}m`;\n}\n\n/** 24-bit background color. */\nexport function bg(r: number, g: number, b: number): string {\n return `\\x1b[48;2;${r};${g};${b}m`;\n}\n\n// ─── String width / truncation / padding ─────────────────────────────────────\n\n// Matches SGR/CSI escape sequences so width math ignores styling.\n// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escapes are control chars by definition\nconst ANSI_PATTERN = /\\x1b\\[[0-9;]*[A-Za-z]|\\x1b[78]/g;\n\n/** Strip ANSI escape sequences from a string. */\nexport function stripAnsi(text: string): string {\n return text.replace(ANSI_PATTERN, \"\");\n}\n\n/** Visible width of a string (ANSI-aware, treats each code point as width 1). */\nexport function displayWidth(text: string): number {\n return [...stripAnsi(text)].length;\n}\n\n/**\n * Truncate a string to a visible width, appending an ellipsis when clipped.\n * ANSI-unaware truncation would corrupt escape sequences, so callers should\n * pass plain text; styling is applied by the panel afterwards.\n */\nexport function truncate(text: string, width: number, ellipsis = \"…\"): string {\n if (width <= 0) return \"\";\n const chars = [...text];\n if (chars.length <= width) return text;\n if (width <= ellipsis.length) return chars.slice(0, width).join(\"\");\n return chars.slice(0, width - ellipsis.length).join(\"\") + ellipsis;\n}\n\n/** Right-pad plain text to a fixed visible width. */\nexport function padEnd(text: string, width: number, fill = \" \"): string {\n const w = displayWidth(text);\n if (w >= width) return text;\n return text + fill.repeat(width - w);\n}\n\n/** Left-pad plain text to a fixed visible width. */\nexport function padStart(text: string, width: number, fill = \" \"): string {\n const w = displayWidth(text);\n if (w >= width) return text;\n return fill.repeat(width - w) + text;\n}\n\n// ─── Box drawing ─────────────────────────────────────────────────────────────\n\nexport interface BoxChars {\n topLeft: string;\n topRight: string;\n bottomLeft: string;\n bottomRight: string;\n horizontal: string;\n vertical: string;\n}\n\nexport const ROUNDED_BOX: BoxChars = {\n topLeft: \"╭\",\n topRight: \"╮\",\n bottomLeft: \"╰\",\n bottomRight: \"╯\",\n horizontal: \"─\",\n vertical: \"│\",\n};\n\nexport const SHARP_BOX: BoxChars = {\n topLeft: \"┌\",\n topRight: \"┐\",\n bottomLeft: \"└\",\n bottomRight: \"┘\",\n horizontal: \"─\",\n vertical: \"│\",\n};\n\nexport interface DrawBoxOptions {\n title?: string | undefined;\n /** Inner content width (columns between the vertical borders). */\n width: number;\n chars?: BoxChars;\n /** Optional style codes applied to the border characters. */\n borderSgr?: number[];\n}\n\n/**\n * Draw a box around the given content lines. Content is truncated/padded to the\n * requested inner width. Returns the framed lines (borders included), each a\n * complete row of the panel. Lines do not include positioning; the host places\n * them with {@link moveTo}.\n */\nexport function drawBox(lines: string[], options: DrawBoxOptions): string[] {\n const chars = options.chars ?? ROUNDED_BOX;\n const width = Math.max(1, options.width);\n const border = (s: string): string =>\n options.borderSgr && options.borderSgr.length > 0 ? sgr(s, ...options.borderSgr) : s;\n\n const h = chars.horizontal;\n const out: string[] = [];\n\n // Top border with optional title.\n if (options.title) {\n const title = ` ${truncate(options.title, Math.max(0, width - 2))} `;\n const titleW = displayWidth(title);\n const remaining = Math.max(0, width - titleW);\n out.push(\n border(chars.topLeft) + border(title) + border(h.repeat(remaining)) + border(chars.topRight),\n );\n } else {\n out.push(border(chars.topLeft + h.repeat(width) + chars.topRight));\n }\n\n // Content rows.\n for (const line of lines) {\n const plain = truncate(line, width);\n const padded = padEnd(plain, width);\n out.push(border(chars.vertical) + padded + border(chars.vertical));\n }\n\n // Bottom border.\n out.push(border(chars.bottomLeft + h.repeat(width) + chars.bottomRight));\n\n return out;\n}\n\n// ─── Bar / sparkline helpers ─────────────────────────────────────────────────\n\nconst SPARK_CHARS = [\"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\"];\n\n/** Render a numeric series as a unicode sparkline of the given width. */\nexport function sparkline(values: number[], width: number): string {\n if (width <= 0 || values.length === 0) return \"\";\n const sample = values.slice(-width);\n const max = Math.max(...sample, 0.0001);\n const min = Math.min(...sample, 0);\n const range = max - min || 1;\n return sample\n .map((v) => {\n const idx = Math.min(\n SPARK_CHARS.length - 1,\n Math.max(0, Math.round(((v - min) / range) * (SPARK_CHARS.length - 1))),\n );\n return SPARK_CHARS[idx];\n })\n .join(\"\");\n}\n\n/** Render a 0..1 ratio as a horizontal bar of the given width. */\nexport function bar(ratio: number, width: number, filledChar = \"█\", emptyChar = \"░\"): string {\n if (width <= 0) return \"\";\n const clamped = Math.min(1, Math.max(0, ratio));\n const filled = Math.round(clamped * width);\n return filledChar.repeat(filled) + emptyChar.repeat(width - filled);\n}\n","import type { DevTools } from \"../index\";\n\n/**\n * Identifiers for the built-in debug panels.\n *\n * Panels map to the six diagnostics surfaces from the design proposal (§6.2):\n * performance, tree, layout, events, dirty-regions, and render statistics.\n * Panels 1 and 6 (performance + render statistics) share a single rendered\n * panel; both live under {@link DebugPanel.Performance}.\n */\nexport enum DebugPanel {\n /** Panel 1 + 6 — FPS, frame timing, render calls, bytes, cache, memory. */\n Performance = \"performance\",\n /** Panel 2 — node tree viewer (display-only in the all-TS pass). */\n Tree = \"tree\",\n /** Panel 3 — layout inspector (box model, flex, computed dims). */\n Layout = \"layout\",\n /** Panel 4 — event tracer (key/mouse/focus/resize log). */\n Events = \"events\",\n /** Panel 5 — dirty-region visualizer (stats-level in the all-TS pass). */\n DirtyRegions = \"dirtyRegions\",\n}\n\n/**\n * Context handed to a {@link Panel} each frame. Panels are pure renderers:\n * they read from the DevTools facade and diagnostics and return lines.\n */\nexport interface PanelContext {\n /** The live DevTools facade (inspectors + queries). */\n readonly devtools: DevTools;\n /** Engine diagnostics snapshot for the current frame. */\n readonly diagnostics: {\n renderCalls: number;\n renderBytes: number;\n eventDispatches: number;\n layoutComputations: number;\n cacheHits: number;\n cacheMisses: number;\n allocations: number;\n averageFrameTime: number;\n fps: number;\n };\n /** Dirty-region count reported by the last engine frame. */\n readonly dirtyRegionCount: number;\n /** Maximum width a panel may occupy (columns). */\n readonly maxWidth: number;\n /** Maximum height a panel may occupy (rows). */\n readonly maxHeight: number;\n}\n\n/**\n * A debug panel: a pure function from state to lines. The {@link OverlayHost}\n * positions the returned lines; a panel never writes to stdout itself.\n */\nexport interface Panel {\n /** Which panel this renders. */\n readonly id: DebugPanel;\n /** Title shown in the panel's header. */\n readonly title: string;\n /** Produce the panel body as an array of plain (unpositioned) lines. */\n render(ctx: PanelContext): string[];\n}\n","import { displayWidth, sparkline } from \"../ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"../panel.types\";\n\nfunction labelled(label: string, value: string, width: number): string {\n const gap = Math.max(1, width - displayWidth(label) - displayWidth(value));\n return label + \" \".repeat(gap) + value;\n}\n\n/**\n * Panel 5 — Dirty Region Visualizer (stats-level).\n *\n * The true per-cell dirty highlight needs napi cell-buffer access, which the\n * shipped engine does not expose (see the task plan). This pass reports the\n * dirty-region count per frame and its recent trend — everything reachable from\n * `RenderResult.dirty_region_count` today.\n */\nexport const dirtyRegionsPanel: Panel = {\n id: DebugPanel.DirtyRegions,\n title: \"Dirty Regions\",\n\n render(ctx: PanelContext): string[] {\n const { devtools } = ctx;\n const w = ctx.maxWidth;\n const frames = devtools.performance.getFrames();\n const dirtyCounts = frames.map((f) => f.dirtyRegionCount);\n const total = dirtyCounts.reduce((a, b) => a + b, 0);\n\n const lines: string[] = [];\n lines.push(labelled(\"Current\", String(ctx.dirtyRegionCount), w));\n if (dirtyCounts.length > 0) {\n const avg = total / dirtyCounts.length;\n lines.push(labelled(\"Avg\", avg.toFixed(1), w));\n lines.push(labelled(\"Max\", String(Math.max(...dirtyCounts)), w));\n const spark = sparkline(dirtyCounts, w);\n if (spark) lines.push(spark);\n }\n lines.push(\"\");\n lines.push(\"per-cell highlight:\");\n lines.push(\"needs Rust napi (deferred)\");\n return lines;\n },\n};\n","import type { RecordedEvent } from \"../../devtools.types\";\nimport { truncate } from \"../ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"../panel.types\";\n\nconst CATEGORY_GLYPH: Record<string, string> = {\n keyboard: \"⌨\",\n mouse: \"🖱\",\n focus: \"◎\",\n resize: \"⤢\",\n lifecycle: \"◆\",\n clipboard: \"📋\",\n animation: \"✦\",\n scheduler: \"⏱\",\n};\n\nfunction summarize(event: RecordedEvent): string {\n const data = event.data as Record<string, unknown> | undefined;\n switch (event.category) {\n case \"keyboard\": {\n const key = data && typeof data.key === \"string\" ? data.key : \"?\";\n return `key ${key}`;\n }\n case \"mouse\": {\n const x = data?.x ?? \"?\";\n const y = data?.y ?? \"?\";\n return `${event.type} @${x},${y}`;\n }\n case \"focus\":\n return `${event.type} ${event.target ?? \"\"}`.trim();\n case \"resize\": {\n const width = data?.width ?? \"?\";\n const height = data?.height ?? \"?\";\n return `${width}×${height}`;\n }\n default:\n return event.type;\n }\n}\n\n/**\n * Panel 4 — Event Tracer.\n *\n * Renders the most recent key/mouse/focus/resize events from the\n * EventInspector, newest last, one per line. Data-complete today.\n */\nexport const eventsPanel: Panel = {\n id: DebugPanel.Events,\n title: \"Events\",\n\n render(ctx: PanelContext): string[] {\n const { devtools } = ctx;\n const w = ctx.maxWidth;\n const rows = Math.max(1, ctx.maxHeight);\n const log = devtools.getEventLog();\n\n if (log.length === 0) {\n return [\"(no events yet)\"];\n }\n\n const recent = log.slice(-rows);\n return recent.map((event) => {\n const glyph = CATEGORY_GLYPH[event.category] ?? \"•\";\n return truncate(`${glyph} ${summarize(event)}`, w);\n });\n },\n};\n","import { displayWidth } from \"../ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"../panel.types\";\n\nfunction labelled(label: string, value: string, width: number): string {\n const gap = Math.max(1, width - displayWidth(label) - displayWidth(value));\n return label + \" \".repeat(gap) + value;\n}\n\n/**\n * Panel 3 — Layout Inspector.\n *\n * Shows the box model (position + computed dims) for the highlighted node, or\n * a summary of the recorded tree when nothing is highlighted. Data comes from\n * the TreeInspector's recorded layout JSON (`getNode().layout`).\n */\nexport const layoutPanel: Panel = {\n id: DebugPanel.Layout,\n title: \"Layout\",\n\n render(ctx: PanelContext): string[] {\n const { devtools } = ctx;\n const w = ctx.maxWidth;\n const target = devtools.highlightedNodeId;\n\n if (!target) {\n return [\n \"No node highlighted.\",\n \"\",\n `Nodes: ${devtools.tree.countNodes()}`,\n \"Use highlight(id) to inspect.\",\n ];\n }\n\n const node = devtools.inspect(target);\n if (!node) {\n return [`Node ${target} not found.`];\n }\n\n const lines: string[] = [];\n lines.push(labelled(\"id\", node.id, w));\n lines.push(labelled(\"type\", node.type, w));\n\n const layout = node.layout;\n if (layout) {\n lines.push(\"─\".repeat(w));\n lines.push(labelled(\"x, y\", `${layout.x}, ${layout.y}`, w));\n lines.push(labelled(\"size\", `${layout.width}×${layout.height}`, w));\n } else {\n lines.push(\"(no layout recorded)\");\n }\n\n const style = node.style;\n if (style && Object.keys(style).length > 0) {\n lines.push(\"─\".repeat(w));\n for (const [key, value] of Object.entries(style)) {\n lines.push(labelled(key, formatValue(value), w));\n }\n }\n\n return lines;\n },\n};\n\nfunction formatValue(value: unknown): string {\n if (value === null || value === undefined) return \"—\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value);\n}\n","import { bar, displayWidth, padEnd, sparkline } from \"../ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"../panel.types\";\n\n/** Format a byte count into a short human string. */\nfunction humanBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}K`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}M`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}G`;\n}\n\nfunction labelled(label: string, value: string, width: number): string {\n const gap = Math.max(1, width - displayWidth(label) - displayWidth(value));\n return label + \" \".repeat(gap) + value;\n}\n\n/**\n * Panel 1 (Performance) + Panel 6 (Render Statistics).\n *\n * Data-complete today: pulls FPS, frame time, render calls, bytes, cache\n * hit/miss, and allocations from engine diagnostics + the PerformanceTracker,\n * and memory from `process.memoryUsage()`.\n */\nexport const performancePanel: Panel = {\n id: DebugPanel.Performance,\n title: \"Performance\",\n\n render(ctx: PanelContext): string[] {\n const { diagnostics, devtools } = ctx;\n const w = ctx.maxWidth;\n const snapshot = devtools.getStats();\n const frames = devtools.performance.getFrames();\n const durations = frames.map((f) => f.duration);\n const mem = devtools.getMemoryStats();\n\n const fps = snapshot.fps > 0 ? snapshot.fps : diagnostics.fps;\n const avgFrame =\n snapshot.avgFrameTime > 0 ? snapshot.avgFrameTime : diagnostics.averageFrameTime;\n\n const cacheTotal = diagnostics.cacheHits + diagnostics.cacheMisses;\n const cacheRatio = cacheTotal === 0 ? 0 : diagnostics.cacheHits / cacheTotal;\n\n const lines: string[] = [];\n lines.push(labelled(\"FPS\", fps.toFixed(1), w));\n lines.push(labelled(\"Frame\", `${avgFrame.toFixed(2)}ms`, w));\n if (durations.length > 0) {\n lines.push(\n labelled(\n \"min/max\",\n `${snapshot.minFrameTime.toFixed(1)}/${snapshot.maxFrameTime.toFixed(1)}ms`,\n w,\n ),\n );\n const spark = sparkline(durations, w);\n if (spark) lines.push(spark);\n }\n lines.push(labelled(\"Frames\", String(snapshot.totalFrames), w));\n lines.push(labelled(\"Dropped\", String(snapshot.droppedFrames), w));\n\n lines.push(\"─\".repeat(w));\n\n lines.push(labelled(\"Renders\", String(diagnostics.renderCalls), w));\n lines.push(labelled(\"Bytes\", humanBytes(diagnostics.renderBytes), w));\n lines.push(labelled(\"Layouts\", String(diagnostics.layoutComputations), w));\n lines.push(labelled(\"Events\", String(diagnostics.eventDispatches), w));\n lines.push(labelled(\"Allocs\", String(diagnostics.allocations), w));\n\n const cachePct = `${(cacheRatio * 100).toFixed(0)}%`;\n lines.push(labelled(\"Cache\", `${diagnostics.cacheHits}/${cacheTotal} ${cachePct}`, w));\n lines.push(padEnd(bar(cacheRatio, w), w));\n\n lines.push(\"─\".repeat(w));\n\n lines.push(labelled(\"Heap\", `${humanBytes(mem.heapUsed)}/${humanBytes(mem.heapTotal)}`, w));\n lines.push(labelled(\"RSS\", humanBytes(mem.rss), w));\n\n return lines;\n },\n};\n","import type { DevToolsNode } from \"../../devtools.types\";\nimport { truncate } from \"../ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"../panel.types\";\n\n/** Flatten a tree to indented display lines (depth-first). */\nfunction walk(\n node: DevToolsNode,\n depth: number,\n out: string[],\n maxRows: number,\n highlight: string | null,\n): void {\n if (out.length >= maxRows) return;\n const indent = \" \".repeat(depth);\n const marker = node.id === highlight ? \"▸ \" : \"\";\n const dims = node.layout ? ` ${node.layout.width}×${node.layout.height}` : \"\";\n out.push(`${indent}${marker}${node.type}#${node.id}${dims}`);\n for (const child of node.children) {\n walk(child, depth + 1, out, maxRows, highlight);\n }\n}\n\n/**\n * Panel 2 — Node Tree Viewer (display-only in the all-TS pass).\n *\n * Renders the recorded render tree with id/type/dims. Click-to-inspect\n * hit-routing is deferred to a later Rust phase (see the task plan); this pass\n * shows the tree and marks the highlighted node.\n */\nexport const treePanel: Panel = {\n id: DebugPanel.Tree,\n title: \"Tree\",\n\n render(ctx: PanelContext): string[] {\n const { devtools } = ctx;\n const w = ctx.maxWidth;\n const rows = Math.max(1, ctx.maxHeight);\n const root = devtools.tree.getRoot();\n\n if (!root) {\n return [`(no tree recorded — ${devtools.tree.countNodes()} nodes)`];\n }\n\n const lines: string[] = [];\n walk(root, 0, lines, rows, devtools.highlightedNodeId);\n return lines.map((line) => truncate(line, w));\n },\n};\n","import type { DiagnosticSnapshot } from \"../../platform/logger\";\nimport type { DevTools } from \"../index\";\nimport { RESET, RESTORE_CURSOR, SAVE_CURSOR, displayWidth, drawBox, moveTo } from \"./ansiUtils\";\nimport { DebugPanel, type Panel, type PanelContext } from \"./panel.types\";\nimport { dirtyRegionsPanel } from \"./panels/dirtyRegionsPanel\";\nimport { eventsPanel } from \"./panels/eventsPanel\";\nimport { layoutPanel } from \"./panels/layoutPanel\";\nimport { performancePanel } from \"./panels/performancePanel\";\nimport { treePanel } from \"./panels/treePanel\";\n\n/** Corner the overlay is anchored to. */\nexport type OverlayCorner = \"top-right\" | \"top-left\" | \"bottom-right\" | \"bottom-left\";\n\n/** The minimal renderer surface the overlay reads from. */\nexport interface OverlayRenderer {\n readonly terminalWidth: number;\n readonly viewportHeight: number;\n getDiagnostics(): DiagnosticSnapshot;\n write(text: string): void;\n}\n\nexport interface OverlayHostOptions {\n /** Corner to anchor panels to. Defaults to top-right. */\n corner?: OverlayCorner;\n /** Inner width of each panel in columns. Defaults to 28. */\n panelWidth?: number;\n /** Max rows a scrolling panel (events/tree) may show. Defaults to 8. */\n panelBodyRows?: number;\n}\n\nconst PANEL_ORDER: DebugPanel[] = [\n DebugPanel.Performance,\n DebugPanel.Tree,\n DebugPanel.Layout,\n DebugPanel.Events,\n DebugPanel.DirtyRegions,\n];\n\nconst PANELS: Record<DebugPanel, Panel> = {\n [DebugPanel.Performance]: performancePanel,\n [DebugPanel.Tree]: treePanel,\n [DebugPanel.Layout]: layoutPanel,\n [DebugPanel.Events]: eventsPanel,\n [DebugPanel.DirtyRegions]: dirtyRegionsPanel,\n};\n\n/**\n * Owns per-frame ANSI compositing of the debug overlay.\n *\n * The overlay is written *over* the engine's incremental output and is not part\n * of the engine's dirty-diff, so the host tracks the rect it painted last frame\n * and clears any rows that are no longer covered — preventing trails when a\n * panel shrinks, moves, or is toggled off.\n */\nexport class OverlayHost {\n private readonly renderer: OverlayRenderer;\n private readonly devtools: DevTools;\n private corner: OverlayCorner;\n private panelWidth: number;\n private panelBodyRows: number;\n /** Rows (1-based) painted on the previous frame, and their painted width. */\n private previousRows: Map<number, number> = new Map();\n private lastDirtyRegionCount = 0;\n\n constructor(renderer: OverlayRenderer, devtools: DevTools, options: OverlayHostOptions = {}) {\n this.renderer = renderer;\n this.devtools = devtools;\n this.corner = options.corner ?? \"top-right\";\n this.panelWidth = options.panelWidth ?? 28;\n this.panelBodyRows = options.panelBodyRows ?? 8;\n }\n\n /** Whether any panel is currently visible. */\n get visible(): boolean {\n return this.devtools.visiblePanels.size > 0;\n }\n\n configure(options: OverlayHostOptions): void {\n if (options.corner !== undefined) this.corner = options.corner;\n if (options.panelWidth !== undefined) this.panelWidth = options.panelWidth;\n if (options.panelBodyRows !== undefined) this.panelBodyRows = options.panelBodyRows;\n }\n\n /** Record the engine's reported dirty-region count for the current frame. */\n setDirtyRegionCount(count: number): void {\n this.lastDirtyRegionCount = count;\n }\n\n /**\n * Composite the visible panels over the current frame. Saves the cursor,\n * clears rows vacated since the last paint, draws each visible panel, then\n * restores the cursor. A no-op when nothing is visible (but still clears any\n * previously-painted rows exactly once).\n */\n paint(): void {\n const width = this.renderer.terminalWidth;\n const height = this.renderer.viewportHeight;\n const innerWidth = Math.max(4, Math.min(this.panelWidth, width - 2));\n\n const framed = this.buildFrame(innerWidth, height);\n\n // Nothing visible: clear leftovers from the previous paint and stop.\n if (framed.length === 0) {\n if (this.previousRows.size > 0) {\n this.renderer.write(this.clearPreviousOnly());\n this.previousRows.clear();\n }\n return;\n }\n\n const boxWidth = innerWidth + 2;\n const startCol = this.startColumn(width, boxWidth);\n const startRow = this.startRow(height, framed.length);\n\n let out = SAVE_CURSOR;\n\n const nextRows = new Map<number, number>();\n for (let i = 0; i < framed.length; i++) {\n const row = startRow + i;\n if (row < 1 || row > height) continue;\n out += moveTo(row, startCol) + RESET + framed[i];\n nextRows.set(row, boxWidth);\n }\n\n // Clear rows painted last frame that we are not painting now.\n for (const [row, prevW] of this.previousRows) {\n if (!nextRows.has(row) && row >= 1 && row <= height) {\n out += moveTo(row, this.startColumn(width, prevW)) + \" \".repeat(prevW);\n }\n }\n\n out += RESTORE_CURSOR + RESET;\n this.renderer.write(out);\n this.previousRows = nextRows;\n }\n\n /**\n * Force-clear the whole overlay region (used on toggle-off before a full\n * redraw). Returns nothing; writes directly.\n */\n clear(): void {\n if (this.previousRows.size === 0) return;\n this.renderer.write(this.clearPreviousOnly());\n this.previousRows.clear();\n }\n\n private clearPreviousOnly(): string {\n const width = this.renderer.terminalWidth;\n let out = SAVE_CURSOR;\n for (const [row, prevW] of this.previousRows) {\n out += moveTo(row, this.startColumn(width, prevW)) + \" \".repeat(prevW);\n }\n out += RESTORE_CURSOR + RESET;\n return out;\n }\n\n /** Build the framed lines for all visible panels, stacked vertically. */\n private buildFrame(innerWidth: number, maxHeight: number): string[] {\n const diagnostics = this.renderer.getDiagnostics();\n const ctx: PanelContext = {\n devtools: this.devtools,\n diagnostics,\n dirtyRegionCount: this.lastDirtyRegionCount,\n maxWidth: innerWidth,\n maxHeight: this.panelBodyRows,\n };\n\n const out: string[] = [];\n for (const id of PANEL_ORDER) {\n if (!this.devtools.visiblePanels.has(id)) continue;\n const panel = PANELS[id];\n const body = panel.render(ctx);\n const framed = drawBox(body, {\n title: panel.title,\n width: innerWidth,\n borderSgr: [90],\n });\n for (const line of framed) {\n if (out.length >= maxHeight) return out;\n out.push(line);\n }\n }\n return out;\n }\n\n private startColumn(width: number, boxWidth: number): number {\n if (this.corner === \"top-left\" || this.corner === \"bottom-left\") return 1;\n return Math.max(1, width - boxWidth + 1);\n }\n\n private startRow(height: number, frameHeight: number): number {\n if (this.corner === \"bottom-left\" || this.corner === \"bottom-right\") {\n return Math.max(1, height - frameHeight + 1);\n }\n return 1;\n }\n}\n\n/** Exposed for tests: the visible width of a framed line. */\nexport function frameLineWidth(line: string): number {\n return displayWidth(line);\n}\n","// ─── Types ───────────────────────────────────────────────────────────────────\nexport type {\n LogLevel as DevToolsLogLevel,\n LogEntry,\n CommandType,\n RecordedCommand,\n EventCategory,\n RecordedEvent,\n FrameMetrics,\n PerformanceSnapshot,\n DevToolsNode,\n SchedulerSnapshot,\n FocusSnapshot,\n TerminalCapabilities as DevToolsTerminalCapabilities,\n TimelineEntry,\n TreeSnapshot,\n SnapshotDiff,\n DiagnosticExport,\n} from \"./devtools.types\";\n\n// ─── Modules ─────────────────────────────────────────────────────────────────\nexport { Logger as DevToolsLogger } from \"./logger\";\nexport type { LoggerOptions } from \"./logger\";\nexport { CommandInspector } from \"./commandInspector\";\nexport type { CommandInspectorOptions } from \"./commandInspector\";\nexport { EventInspector } from \"./eventInspector\";\nexport type { EventInspectorOptions } from \"./eventInspector\";\nexport { PerformanceTracker } from \"./performance\";\nexport type { PerformanceTrackerOptions } from \"./performance\";\nexport { TreeInspector } from \"./treeInspector\";\nexport type { TreeInspectorOptions } from \"./treeInspector\";\nexport { SchedulerInspector } from \"./schedulerInspector\";\nexport type { SchedulerInspectorOptions } from \"./schedulerInspector\";\nexport { FocusInspector } from \"./focusInspector\";\nexport type { FocusInspectorOptions } from \"./focusInspector\";\nexport { CapabilityInspector } from \"./capabilityInspector\";\nexport type { CapabilityInspectorOptions } from \"./capabilityInspector\";\nexport { DevToolsTimeline } from \"./timeline\";\nexport type { DevToolsTimelineOptions } from \"./timeline\";\nexport { SnapshotManager } from \"./snapshot\";\nexport type { SnapshotOptions } from \"./snapshot\";\nexport { createExport, exportToJson, createSummary } from \"./export\";\nexport type { ExportOptions, ExportData } from \"./export\";\nexport {\n TerminalConsoleCache,\n terminalConsoleCache,\n ConsoleLogLevel,\n capture,\n} from \"./consoleCapture\";\nexport type { ConsoleLogEntry, CallerInfo } from \"./consoleCapture\";\n\n// ─── Overlay ─────────────────────────────────────────────────────────────────\nexport { OverlayHost } from \"./overlay/overlayHost\";\nexport type { OverlayHostOptions, OverlayCorner } from \"./overlay/overlayHost\";\nexport { DebugPanel } from \"./overlay/panel.types\";\nexport type { Panel, PanelContext } from \"./overlay/panel.types\";\nexport * as ansi from \"./overlay/ansiUtils\";\n\n// ─── DevTools Interface ──────────────────────────────────────────────────────\n\nimport type {\n DevToolsNode,\n DiagnosticExport,\n FrameMetrics,\n LogEntry,\n PerformanceSnapshot,\n RecordedEvent,\n SchedulerSnapshot,\n TerminalCapabilities,\n} from \"./devtools.types\";\nimport type { ExportOptions } from \"./export\";\nimport { DebugPanel } from \"./overlay/panel.types\";\n\nimport { CapabilityInspector } from \"./capabilityInspector\";\nimport { CommandInspector } from \"./commandInspector\";\nimport { EventInspector } from \"./eventInspector\";\nimport { createExport, createSummary, exportToJson } from \"./export\";\nimport { FocusInspector } from \"./focusInspector\";\nimport { Logger } from \"./logger\";\nimport { PerformanceTracker } from \"./performance\";\nimport { SchedulerInspector } from \"./schedulerInspector\";\nimport { SnapshotManager } from \"./snapshot\";\nimport { DevToolsTimeline } from \"./timeline\";\nimport { TreeInspector } from \"./treeInspector\";\n\n/** Memory statistics captured from the Node.js process. */\nexport interface MemoryStats {\n heapUsed: number;\n heapTotal: number;\n external: number;\n rss: number;\n arrayBuffers: number;\n}\n\n/** A lightweight console surface backed by the DevTools logger. */\nexport interface DebugConsole {\n log(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n /** Recent console entries, most-recent last. */\n entries(): readonly LogEntry[];\n clear(): void;\n}\n\nexport interface DevTools {\n /** Whether DevTools is enabled */\n readonly enabled: boolean;\n\n /** Structured logger */\n readonly logger: Logger;\n\n /** Command inspector — records every command emitted */\n readonly commands: CommandInspector;\n\n /** Event inspector — tracks keyboard, mouse, focus, resize events */\n readonly events: EventInspector;\n\n /** Performance tracker — frame timing, FPS, metrics */\n readonly performance: PerformanceTracker;\n\n /** Tree inspector — render tree, props, styles, layout */\n readonly tree: TreeInspector;\n\n /** Scheduler inspector — frame budget, drops, callbacks */\n readonly scheduler: SchedulerInspector;\n\n /** Focus inspector — focused node, tab order, scopes */\n readonly focus: FocusInspector;\n\n /** Terminal capability inspector */\n readonly capabilities: CapabilityInspector;\n\n /** Timeline — chronological event recording */\n readonly timeline: DevToolsTimeline;\n\n /** Snapshot manager — capture and compare tree states */\n readonly snapshots: SnapshotManager;\n\n /** Lightweight console surface backed by the logger */\n readonly console: DebugConsole;\n\n // ─── Panel control (§6.3) ────────────────────────────────────────────────\n\n /** Panels the host overlay should currently render. */\n readonly visiblePanels: ReadonlySet<DebugPanel>;\n\n /** Show a debug panel. */\n show(panel: DebugPanel): void;\n\n /** Hide a debug panel. */\n hide(panel: DebugPanel): void;\n\n /** Toggle a debug panel's visibility. Returns the new visibility. */\n toggle(panel: DebugPanel): boolean;\n\n /** Whether a given panel is currently visible. */\n isVisible(panel: DebugPanel): boolean;\n\n // ─── Queries (§6.3) ──────────────────────────────────────────────────────\n\n /** Current performance snapshot. */\n getStats(): PerformanceSnapshot;\n\n /** Begin capturing a profiling window. */\n startProfiling(): void;\n\n /** Stop the current profiling window and return the frames captured. */\n stopProfiling(): readonly FrameMetrics[];\n\n /** Inspect a node by id; returns its recorded tree node if known. */\n inspect(nodeId: string): DevToolsNode | undefined;\n\n /** Highlight a node (records the highlight target for the overlay). */\n highlight(nodeId: string): void;\n\n /** Clear any active highlight. */\n clearHighlight(): void;\n\n /** The currently highlighted node id, if any. */\n readonly highlightedNodeId: string | null;\n\n /** Enable or disable live event tracing. */\n traceEvents(enabled: boolean): void;\n\n /** Recorded event log. */\n getEventLog(): readonly RecordedEvent[];\n\n /** Layout box for a node, if recorded. */\n inspectLayout(nodeId: string): DevToolsNode[\"layout\"] | undefined;\n\n /** Show the dirty-region panel (stats-level). */\n showDirtyRegions(enabled: boolean): void;\n\n /** Current process memory usage. */\n getMemoryStats(): MemoryStats;\n\n /** Capture a heap snapshot summary (memory stats point-in-time). */\n takeHeapSnapshot(): MemoryStats;\n\n // ─── Recording (existing surface) ─────────────────────────────────────────\n\n /** Record a command being emitted */\n recordCommand(\n type: string,\n payload: Record<string, unknown>,\n duration?: number | undefined,\n ): void;\n\n /** Record a render frame */\n recordFrame(options: {\n duration: number;\n commandCount?: number | undefined;\n dirtyRegionCount?: number | undefined;\n renderDuration?: number | undefined;\n layoutDuration?: number | undefined;\n paintDuration?: number | undefined;\n ffiDuration?: number | undefined;\n }): void;\n\n /** Record a keyboard event */\n recordKeyboard(\n key: string,\n modifiers: { ctrl: boolean; shift: boolean; alt: boolean; meta: boolean },\n target?: string | undefined,\n ): void;\n\n /** Record a mouse event */\n recordMouse(\n type: string,\n x: number,\n y: number,\n button?: string | undefined,\n target?: string | undefined,\n ): void;\n\n /** Record a focus change */\n recordFocus(type: \"focus\" | \"blur\", nodeId: string): void;\n\n /** Record a resize event */\n recordResize(\n width: number,\n height: number,\n prevWidth?: number | undefined,\n prevHeight?: number | undefined,\n ): void;\n\n /** Update terminal capabilities */\n updateCapabilities(capabilities: Partial<TerminalCapabilities>): void;\n\n /** Update scheduler state */\n updateScheduler(state: Partial<SchedulerSnapshot>): void;\n\n /** Capture a tree snapshot */\n captureSnapshot(tree: DevToolsNode): number;\n\n /** Get a full diagnostic export */\n exportData(options?: ExportOptions | undefined): DiagnosticExport;\n\n /** Get export as JSON string */\n exportJson(options?: ExportOptions | undefined): string;\n\n /** Get a summary report */\n getSummary(): string;\n\n /** Reset all inspectors */\n reset(): void;\n\n /** Dispose all resources */\n dispose(): void;\n}\n\n// ─── No-op implementation ────────────────────────────────────────────────────\n\nconst EMPTY_PANELS: ReadonlySet<DebugPanel> = new Set<DebugPanel>();\n\nfunction createNoOpConsole(): DebugConsole {\n const noop = () => {};\n return {\n log: noop,\n info: noop,\n warn: noop,\n error: noop,\n debug: noop,\n entries: () => [],\n clear: noop,\n };\n}\n\nfunction noOpMemoryStats(): MemoryStats {\n return { heapUsed: 0, heapTotal: 0, external: 0, rss: 0, arrayBuffers: 0 };\n}\n\nfunction createNoOpDevTools(): DevTools {\n const noop = () => {};\n const noopZero = () => 0;\n const noopExport = (): DiagnosticExport => ({\n version: \"1.0.0\",\n timestamp: 0,\n duration: 0,\n logs: [],\n commands: [],\n events: [],\n frames: [],\n performance: {\n fps: 0,\n avgFrameTime: 0,\n minFrameTime: 0,\n maxFrameTime: 0,\n totalFrames: 0,\n droppedFrames: 0,\n commandCount: 0,\n dirtyNodeCount: 0,\n },\n timeline: [],\n snapshots: [],\n });\n const noopSnapshot = (): PerformanceSnapshot => ({\n fps: 0,\n avgFrameTime: 0,\n minFrameTime: 0,\n maxFrameTime: 0,\n totalFrames: 0,\n droppedFrames: 0,\n commandCount: 0,\n dirtyNodeCount: 0,\n });\n return {\n enabled: false,\n logger: new Logger(),\n commands: new CommandInspector(),\n events: new EventInspector(),\n performance: new PerformanceTracker(),\n tree: new TreeInspector(),\n scheduler: new SchedulerInspector(),\n focus: new FocusInspector(),\n capabilities: new CapabilityInspector(),\n timeline: new DevToolsTimeline(),\n snapshots: new SnapshotManager(),\n console: createNoOpConsole(),\n visiblePanels: EMPTY_PANELS,\n highlightedNodeId: null,\n show: noop,\n hide: noop,\n toggle: () => false,\n isVisible: () => false,\n getStats: noopSnapshot,\n startProfiling: noop,\n stopProfiling: () => [],\n inspect: () => undefined,\n highlight: noop,\n clearHighlight: noop,\n traceEvents: noop,\n getEventLog: () => [],\n inspectLayout: () => undefined,\n showDirtyRegions: noop,\n getMemoryStats: noOpMemoryStats,\n takeHeapSnapshot: noOpMemoryStats,\n recordCommand: noop,\n recordFrame: noop,\n recordKeyboard: noop,\n recordMouse: noop,\n recordFocus: noop,\n recordResize: noop,\n updateCapabilities: noop,\n updateScheduler: noop,\n captureSnapshot: noopZero,\n exportData: noopExport,\n exportJson: () => JSON.stringify(noopExport()),\n getSummary: () => \"\",\n reset: noop,\n dispose: noop,\n };\n}\n\n// ─── Factory ─────────────────────────────────────────────────────────────────\n\nexport interface CreateDevToolsOptions {\n enabled?: boolean | undefined;\n maxEvents?: number | undefined;\n logging?: boolean | undefined;\n logLevel?: (\"debug\" | \"info\" | \"warn\" | \"error\" | \"trace\") | undefined;\n timeline?: boolean | undefined;\n performance?: boolean | undefined;\n snapshots?: boolean | undefined;\n}\n\n/** Options accepted by the `debug` field of `CliRendererOptions`. */\nexport type DevToolsOptions = CreateDevToolsOptions;\n\nfunction readMemoryStats(): MemoryStats {\n /* c8 ignore start — process.memoryUsage shape depends on the host runtime */\n if (typeof process !== \"undefined\" && typeof process.memoryUsage === \"function\") {\n const m = process.memoryUsage();\n return {\n heapUsed: m.heapUsed,\n heapTotal: m.heapTotal,\n external: m.external,\n rss: m.rss,\n arrayBuffers: m.arrayBuffers ?? 0,\n };\n }\n return noOpMemoryStats();\n /* c8 ignore stop */\n}\n\n/**\n * Create a DevTools instance.\n *\n * When `enabled` is false or omitted, returns a no-op implementation with\n * near-zero overhead. When `enabled: true`, returns a fully functional\n * DevTools instance that can record commands, events, performance metrics,\n * and more.\n */\nexport function createDevTools(options?: CreateDevToolsOptions): DevTools {\n if (!options?.enabled) {\n return createNoOpDevTools();\n }\n\n const maxEvents = options.maxEvents ?? 1000;\n const logger = new Logger({ maxEntries: maxEvents, minLevel: options.logLevel ?? \"debug\" });\n const commands = new CommandInspector({ maxCommands: maxEvents });\n const events = new EventInspector({ maxEvents });\n const performance = new PerformanceTracker({ maxFrames: maxEvents });\n const tree = new TreeInspector();\n const scheduler = new SchedulerInspector();\n const focus = new FocusInspector();\n const capabilities = new CapabilityInspector();\n const timeline = new DevToolsTimeline({ maxEntries: maxEvents });\n const snapshots = new SnapshotManager();\n\n const visiblePanels = new Set<DebugPanel>();\n let highlightedNodeId: string | null = null;\n let tracingEnabled = true;\n let profiling = false;\n let profileStart = 0;\n\n const toArgString = (args: unknown[]): string =>\n args.map((a) => (typeof a === \"string\" ? a : safeStringify(a))).join(\" \");\n\n const consoleSurface: DebugConsole = {\n log: (...args) => logger.info(\"console\", toArgString(args)),\n info: (...args) => logger.info(\"console\", toArgString(args)),\n warn: (...args) => logger.warn(\"console\", toArgString(args)),\n error: (...args) => logger.error(\"console\", toArgString(args)),\n debug: (...args) => logger.debug(\"console\", toArgString(args)),\n entries: () => logger.getEntriesByCategory(\"console\"),\n clear: () => logger.clear(),\n };\n\n return {\n enabled: true,\n logger,\n commands,\n events,\n performance,\n tree,\n scheduler,\n focus,\n capabilities,\n timeline,\n snapshots,\n console: consoleSurface,\n\n get visiblePanels() {\n return visiblePanels;\n },\n\n get highlightedNodeId() {\n return highlightedNodeId;\n },\n\n show(panel) {\n visiblePanels.add(panel);\n },\n\n hide(panel) {\n visiblePanels.delete(panel);\n },\n\n toggle(panel) {\n if (visiblePanels.has(panel)) {\n visiblePanels.delete(panel);\n return false;\n }\n visiblePanels.add(panel);\n return true;\n },\n\n isVisible(panel) {\n return visiblePanels.has(panel);\n },\n\n getStats() {\n return performance.getSnapshot();\n },\n\n startProfiling() {\n profiling = true;\n profileStart = performance.count;\n },\n\n stopProfiling() {\n if (!profiling) return [];\n profiling = false;\n return performance.getFrames().slice(profileStart);\n },\n\n inspect(nodeId) {\n return tree.getNode(nodeId);\n },\n\n highlight(nodeId) {\n highlightedNodeId = nodeId;\n },\n\n clearHighlight() {\n highlightedNodeId = null;\n },\n\n traceEvents(enabled) {\n tracingEnabled = enabled;\n },\n\n getEventLog() {\n return events.getEvents();\n },\n\n inspectLayout(nodeId) {\n return tree.getNode(nodeId)?.layout;\n },\n\n showDirtyRegions(enabled) {\n if (enabled) {\n visiblePanels.add(DebugPanel.DirtyRegions);\n } else {\n visiblePanels.delete(DebugPanel.DirtyRegions);\n }\n },\n\n getMemoryStats() {\n return readMemoryStats();\n },\n\n takeHeapSnapshot() {\n return readMemoryStats();\n },\n\n recordCommand(type, payload, duration) {\n commands.record(type, payload, duration);\n timeline.recordCommand(type, duration);\n logger.debug(\"command\", `Command: ${type}`, payload);\n },\n\n recordFrame(opts) {\n performance.recordFrame({\n duration: opts.duration,\n commandCount: opts.commandCount ?? 0,\n dirtyRegionCount: opts.dirtyRegionCount ?? 0,\n renderDuration: opts.renderDuration,\n layoutDuration: opts.layoutDuration,\n paintDuration: opts.paintDuration,\n ffiDuration: opts.ffiDuration,\n });\n timeline.recordRender(opts.duration);\n },\n\n recordKeyboard(key, modifiers, target) {\n if (!tracingEnabled) return;\n events.recordKeyboard(key, modifiers, target);\n /* c8 ignore next — ?? null fallback for undefined target */\n const kbdTarget: string | null = target ?? null;\n timeline.recordEvent(\"keyboard\", \"keydown\", { key, modifiers, target: kbdTarget });\n },\n\n recordMouse(type, x, y, button, target) {\n if (!tracingEnabled) return;\n events.recordMouse(type, x, y, button, target);\n /* c8 ignore next — ?? null fallback for undefined button */\n const safeButton: string | null = button ?? null;\n /* c8 ignore next — ?? null fallback for undefined target */\n const safeTarget: string | null = target ?? null;\n timeline.recordEvent(\"mouse\", type, { x, y, button: safeButton, target: safeTarget });\n },\n\n recordFocus(type, nodeId) {\n if (!tracingEnabled) return;\n events.recordFocus(type, nodeId);\n if (type === \"focus\") {\n focus.recordFocus(nodeId);\n } else {\n focus.recordBlur(nodeId);\n }\n timeline.recordEvent(\"focus\", type, { nodeId });\n },\n\n recordResize(width, height, prevWidth, prevHeight) {\n if (!tracingEnabled) return;\n events.recordResize(width, height, prevWidth, prevHeight);\n /* c8 ignore next — ?? null fallback for undefined prevWidth/prevHeight */\n const rPrevWidth: number | null = prevWidth ?? null;\n /* c8 ignore next — ?? null fallback for undefined prevWidth/prevHeight */\n const rPrevHeight: number | null = prevHeight ?? null;\n timeline.recordEvent(\"resize\", \"resize\", {\n width,\n height,\n prevWidth: rPrevWidth,\n prevHeight: rPrevHeight,\n });\n },\n\n updateCapabilities(caps) {\n capabilities.update(caps);\n },\n\n updateScheduler(state) {\n scheduler.updateState(state);\n },\n\n captureSnapshot(tree) {\n const snap = snapshots.capture(tree);\n return snap.id;\n },\n\n exportData(options) {\n const root = tree.getRoot();\n return createExport(\n {\n logs: logger.getEntries(),\n commands: commands.getCommands(),\n events: events.getEvents(),\n frames: performance.getFrames(),\n performance: performance.getSnapshot(),\n ...(root !== null ? { tree: root } : {}),\n scheduler: scheduler.getSnapshot(),\n focus: focus.getSnapshot(),\n capabilities: capabilities.get(),\n timeline: timeline.getEntries(),\n snapshots: snapshots.getSnapshots(),\n },\n options,\n );\n },\n\n exportJson(options) {\n return exportToJson(this.exportData(options));\n },\n\n getSummary() {\n return createSummary(this.exportData());\n },\n\n reset() {\n logger.clear();\n commands.clear();\n events.clear();\n performance.clear();\n tree.clear();\n scheduler.clear();\n focus.clear();\n capabilities.clear();\n timeline.clear();\n snapshots.clear();\n visiblePanels.clear();\n highlightedNodeId = null;\n },\n\n dispose() {\n this.reset();\n },\n };\n}\n\n// ─── Local helpers ─────────────────────────────────────────────────────────────\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n /* c8 ignore next — circular/unserialisable values fall back to String() */\n return String(value);\n }\n}\n","/**\n * Serialises a TypeScript {@link LayoutConstraints} object into the flat JSON\n * payload expected by the Rust engine's `NativeEngine.setLayout` call.\n *\n * Extracted from cliRenderer.ts for modularity and testability.\n * The function is a pure transformation — it has no side effects.\n */\n\nimport type { LayoutConstraints } from \"@bettertui/shared\";\n\n/**\n * When an explicit numeric `width` or `height` is set on a\n * node, `flexShrink` defaults to `0` rather than the CSS default of `1`.\n * This prevents fixed-size children from being squeezed by their flex\n * container, which is almost always the desired behaviour in terminal UIs.\n *\n * If the caller has explicitly set `flexShrink`, that value wins.\n */\nfunction resolveFlexShrink(layout: LayoutConstraints): number | undefined {\n if (layout.flexShrink !== undefined) return layout.flexShrink;\n const hasExplicitWidth = typeof layout.width === \"number\";\n const hasExplicitHeight = typeof layout.height === \"number\";\n if (hasExplicitWidth || hasExplicitHeight) return 0;\n return undefined; // let the engine use its default (1)\n}\n\nexport function layoutToEngineJson(layout: LayoutConstraints): Record<string, unknown> {\n const j: Record<string, unknown> = {};\n\n if (layout.flexDirection !== undefined) j.direction = layout.flexDirection;\n if (layout.flexWrap !== undefined) j.flex_wrap = layout.flexWrap;\n if (layout.justifyContent !== undefined) j.justify = layout.justifyContent;\n if (layout.alignItems !== undefined) j.align = layout.alignItems;\n if (layout.alignSelf !== undefined) j.align_self = layout.alignSelf;\n if (layout.alignContent !== undefined) j.align_content = layout.alignContent;\n if (layout.flexGrow !== undefined) j.flex_grow = layout.flexGrow;\n\n const flexShrink = resolveFlexShrink(layout);\n if (flexShrink !== undefined) j.flex_shrink = flexShrink;\n\n if (layout.flexBasis !== undefined) j.flex_basis = String(layout.flexBasis);\n if (layout.display !== undefined) j.display = layout.display;\n\n if (layout.width !== undefined) j.width = String(layout.width);\n if (layout.height !== undefined) j.height = String(layout.height);\n if (layout.minWidth !== undefined) j.min_width = String(layout.minWidth);\n if (layout.minHeight !== undefined) j.min_height = String(layout.minHeight);\n if (layout.maxWidth !== undefined) j.max_width = String(layout.maxWidth);\n if (layout.maxHeight !== undefined) j.max_height = String(layout.maxHeight);\n\n if (layout.position !== undefined) j.position = layout.position;\n if (layout.top !== undefined) j.top = layout.top;\n if (layout.right !== undefined) j.right = layout.right;\n if (layout.bottom !== undefined) j.bottom = layout.bottom;\n if (layout.left !== undefined) j.left = layout.left;\n if (layout.zIndex !== undefined) j.z_index = layout.zIndex;\n if (layout.overflow !== undefined) j.overflow = layout.overflow;\n\n // Inset shorthand — explicit per-edge values win (set above) so only fill\n // remaining edges from the shorthand object.\n if (layout.inset !== undefined) {\n if (j.top === undefined && layout.inset.top !== undefined) j.top = layout.inset.top;\n if (j.right === undefined && layout.inset.right !== undefined) j.right = layout.inset.right;\n if (j.bottom === undefined && layout.inset.bottom !== undefined) j.bottom = layout.inset.bottom;\n if (j.left === undefined && layout.inset.left !== undefined) j.left = layout.inset.left;\n }\n\n // Padding\n const pt =\n layout.paddingTop ??\n (typeof layout.padding === \"number\" ? layout.padding : layout.padding?.top);\n const pr =\n layout.paddingRight ??\n (typeof layout.padding === \"number\" ? layout.padding : layout.padding?.right);\n const pb =\n layout.paddingBottom ??\n (typeof layout.padding === \"number\" ? layout.padding : layout.padding?.bottom);\n const pl =\n layout.paddingLeft ??\n (typeof layout.padding === \"number\" ? layout.padding : layout.padding?.left);\n if (pt !== undefined) j.padding_top = pt;\n if (pr !== undefined) j.padding_right = pr;\n if (pb !== undefined) j.padding_bottom = pb;\n if (pl !== undefined) j.padding_left = pl;\n\n // Margin\n const mt =\n layout.marginTop ?? (typeof layout.margin === \"number\" ? layout.margin : layout.margin?.top);\n const mr =\n layout.marginRight ??\n (typeof layout.margin === \"number\" ? layout.margin : layout.margin?.right);\n const mb =\n layout.marginBottom ??\n (typeof layout.margin === \"number\" ? layout.margin : layout.margin?.bottom);\n const ml =\n layout.marginLeft ?? (typeof layout.margin === \"number\" ? layout.margin : layout.margin?.left);\n if (mt !== undefined) j.margin_top = mt;\n if (mr !== undefined) j.margin_right = mr;\n if (mb !== undefined) j.margin_bottom = mb;\n if (ml !== undefined) j.margin_left = ml;\n\n // Gap\n const gapVal = layout.gap;\n if (gapVal !== undefined) {\n if (typeof gapVal === \"number\") {\n j.gap_row = gapVal;\n j.gap_column = gapVal;\n } else {\n if (gapVal.row !== undefined) j.gap_row = gapVal.row;\n if (gapVal.column !== undefined) j.gap_column = gapVal.column;\n }\n }\n\n // Border layout contribution (applies when box-sizing: border-box is active,\n // which is the default). Typically 0 or 1 cell per bordered side.\n const bt = layout.borderTop;\n const br = layout.borderRight;\n const bb = layout.borderBottom;\n const bl = layout.borderLeft;\n if (bt !== undefined) j.border_top = bt;\n if (br !== undefined) j.border_right = br;\n if (bb !== undefined) j.border_bottom = bb;\n if (bl !== undefined) j.border_left = bl;\n\n return j;\n}\n","import { EventEmitter } from \"node:events\";\nimport { writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { LayoutConstraints, Style } from \"@bettertui/shared\";\nimport type { DevTools, DevToolsOptions } from \"../devtools\";\nimport { createDevTools } from \"../devtools\";\nimport { type ConsoleLogEntry, terminalConsoleCache } from \"../devtools/consoleCapture\";\nimport { OverlayHost } from \"../devtools/overlay/overlayHost\";\nimport { DebugPanel } from \"../devtools/overlay/panel.types\";\nimport { env } from \"../lib/env\";\nimport { InternalKeyHandler } from \"../lib/keyHandler\";\nimport { KeyInput } from \"../lib/keyInput\";\nimport { CliRenderEvents } from \"../lib/renderableEvents\";\nimport type { NapiEngine, NapiKeymap, TerminalCapabilities } from \"./binding\";\nimport {\n createEngine,\n createKeymap,\n detectCapabilities,\n getVersion,\n loggerGetDiagnostics,\n loggerInit,\n} from \"./binding\";\nimport { layoutToEngineJson } from \"./layoutSerializer\";\nimport type { DiagnosticSnapshot, LoggerConfig } from \"./logger\";\nimport type { ExternalOutputMode, ScreenMode } from \"./platform.types\";\n\nexport { CliRenderEvents };\n\nexport interface RawKeyEvent {\n name: string;\n ctrl: boolean;\n shift: boolean;\n alt: boolean;\n meta: boolean;\n sequence: string;\n preventDefault(): void;\n}\n\nexport interface CliRendererOptions {\n width?: number;\n height?: number;\n autoStart?: boolean;\n exitOnCtrlC?: boolean;\n targetFps?: number;\n screenMode?: ScreenMode;\n footerHeight?: number;\n externalOutputMode?: ExternalOutputMode;\n logger?: LoggerConfig;\n debug?: boolean | DevToolsOptions;\n onDestroy?: () => void;\n enableMouseMovement?: boolean;\n useMouse?: boolean;\n autoFocus?: boolean;\n backgroundColor?: string;\n}\n\n/** Interactive terminal console overlay for capturing and inspecting console log output. */\nexport class TerminalConsole extends EventEmitter {\n private _visible = false;\n private _renderer: CliRenderer | null = null;\n keyBindings: Record<string, unknown> = {};\n onCopySelection?: () => void;\n\n constructor(renderer?: CliRenderer) {\n super();\n this._renderer = renderer ?? null;\n if (env.BTUI_USE_CONSOLE) {\n terminalConsoleCache.activate();\n }\n }\n\n attachRenderer(renderer: CliRenderer): void {\n this._renderer = renderer;\n }\n\n show(): void {\n this._visible = true;\n terminalConsoleCache.activate();\n this.emit(\"show\");\n }\n\n hide(): void {\n this._visible = false;\n this.emit(\"hide\");\n }\n\n toggle(): void {\n this._visible = !this._visible;\n if (this._visible) {\n this.show();\n } else {\n this.hide();\n }\n }\n\n get visible(): boolean {\n return this._visible;\n }\n\n clear(): void {\n terminalConsoleCache.clearConsole();\n }\n\n entries(): readonly ConsoleLogEntry[] {\n return terminalConsoleCache.cachedLogs;\n }\n\n saveLogsToFile(filepath?: string): string | null {\n try {\n const timestamp = Date.now();\n const targetPath = filepath || join(process.cwd(), `_console_${timestamp}.log`);\n const formatArg = (arg: unknown) =>\n typeof arg === \"object\" && arg !== null ? JSON.stringify(arg) : String(arg);\n const logs = terminalConsoleCache.cachedLogs\n .map(\n ([date, level, args]) =>\n `[${date.toISOString()}] [${level}] ${args.map(formatArg).join(\" \")}`,\n )\n .join(\"\\n\");\n writeFileSync(targetPath, logs, \"utf8\");\n return targetPath;\n } catch {\n return null;\n }\n }\n}\n\nexport type ThemeMode = \"light\" | \"dark\";\n\ntype FrameCallback = (deltaTime: number) => void | Promise<void>;\n\n// Lazy import to avoid circular at module level\nlet _Root: typeof import(\"../renderables/Box\").Root | undefined;\n\nfunction getRoot() {\n if (!_Root) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n _Root = require(\"../renderables/Box\").Root;\n }\n if (!_Root) throw new Error(\"Root could not be loaded\");\n return _Root;\n}\n\nexport class CliRenderer extends EventEmitter {\n private engine: NapiEngine;\n private keymap: NapiKeymap;\n private _keyInput: KeyInput;\n private _keyDispatch: InternalKeyHandler;\n private _capabilities: TerminalCapabilities;\n private width: number;\n private height: number;\n private renderOffset: number;\n private _screenMode: ScreenMode;\n private _externalOutputMode: ExternalOutputMode;\n private externalOutputBuffer: string[] = [];\n private nodes: Map<number, { parent: number | null; children: number[] }> = new Map();\n private running = false;\n private paused = false;\n private _devtools: DevTools;\n private overlay: OverlayHost | null = null;\n private lastFrameTime = 0;\n private _frameId = 0;\n private _frameInterval: ReturnType<typeof setTimeout> | null = null;\n private _frameCallbacks: Set<FrameCallback> = new Set();\n private _lifecyclePasses: Set<() => void> = new Set();\n private _root: import(\"../renderables/Box\").Root | null = null;\n private _console: TerminalConsole = new TerminalConsole();\n private _themeMode: ThemeMode = \"dark\";\n private _targetFps: number;\n private _onDestroy: (() => void) | undefined;\n private _pendingRender = false;\n private _resizeHandler: (() => void) | null = null;\n private _liveCount = 0;\n\n constructor(options: CliRendererOptions = {}) {\n super();\n if (options.logger) {\n loggerInit({\n dev: process.env.NODE_ENV !== \"production\",\n ...options.logger,\n });\n }\n this._capabilities = detectCapabilities();\n this.width = options.width ?? this._capabilities.columns;\n this.height = options.height ?? this._capabilities.rows;\n this._targetFps = options.targetFps ?? 60;\n\n this._screenMode = options.screenMode ?? \"alternate-screen\";\n this._externalOutputMode =\n options.externalOutputMode ??\n (this._screenMode === \"split-footer\" ? \"capture-stdout\" : \"passthrough\");\n const footerHeight = options.footerHeight ?? 0;\n this.renderOffset =\n this._screenMode === \"split-footer\" ? Math.max(0, this.height - footerHeight) : 0;\n\n this.engine = createEngine(this.width, this.height);\n this.keymap = createKeymap();\n this._keyInput = new KeyInput();\n this._keyDispatch = new InternalKeyHandler();\n this._onDestroy = options.onDestroy;\n\n // Bridge raw key/paste events from _keyInput through the priority dispatcher.\n // Global handlers registered via renderer.keyHandler.on() (tier-1) fire first\n // and can call key.preventDefault() / key.stopPropagation() before the focused\n // widget's handler (tier-2, registered via onInternal()) sees the event.\n this._keyInput.on(\"keypress\", (key) => this._keyDispatch.processParsedKey(key));\n this._keyInput.on(\"keyrelease\", (key) => this._keyDispatch.processParsedKey(key));\n this._keyInput.on(\"paste\", (event) =>\n this._keyDispatch.processPaste(event.bytes, event.metadata),\n );\n\n const rootId = this.engine.root();\n this.nodes.set(rootId, { parent: null, children: [] });\n this.setNodeLayout(rootId, { width: \"100%\", height: \"100%\" });\n\n // Debug tooling\n const envDebug =\n process.env.BTUI_DEBUG === \"1\" ||\n process.env.BTUI_DEBUG === \"true\" ||\n process.env.BTUI_SHOW_STATS === \"1\" ||\n process.env.BTUI_SHOW_STATS === \"true\";\n const debugOption = options.debug;\n\n if (debugOption || envDebug) {\n const devToolsOptions: DevToolsOptions =\n typeof debugOption === \"object\" ? { ...debugOption, enabled: true } : { enabled: true };\n this._devtools = createDevTools(devToolsOptions);\n this._devtools.updateCapabilities(mapCapabilities(this._capabilities));\n this.overlay = new OverlayHost(this, this._devtools);\n if (envDebug || debugOption === true) {\n this._devtools.show(DebugPanel.Performance);\n }\n } else {\n this._devtools = createDevTools();\n }\n\n this._console.attachRenderer(this);\n\n // Ctrl+C exit handler & Debug shortcut handlers (tier-1 global listener)\n this._keyDispatch.on(\"keypress\", (key) => {\n if (options.exitOnCtrlC !== false && key.ctrl && key.name === \"c\") {\n this.destroy();\n process.exit(0);\n }\n\n // Backtick (` ` `) or Ctrl+F12 toggles console overlay\n if (key.name === \"`\" || (key.ctrl && key.name === \"f12\")) {\n this._console.toggle();\n }\n\n // F12 or Ctrl+Shift+D toggles performance debug overlay\n if ((key.name === \"f12\" && !key.ctrl) || (key.ctrl && key.shift && key.name === \"d\")) {\n this.toggleDebugOverlay();\n }\n });\n\n // Resize handling\n this._resizeHandler = () => {\n const cols = process.stdout.columns || 80;\n const rows = process.stdout.rows || 24;\n if (cols !== this.width || rows !== this.height) {\n this.resize(cols, rows);\n this.emit(CliRenderEvents.RESIZE, cols, rows);\n }\n };\n process.stdout.on(\"resize\", this._resizeHandler);\n\n if (options.autoStart !== false) {\n this.start();\n }\n }\n\n // ── Getters ─────────────────────────────────────────────────────────────────\n\n get frameId(): number {\n return this._frameId;\n }\n\n get terminalWidth(): number {\n return this.width;\n }\n\n get terminalHeight(): number {\n return this.height;\n }\n\n get viewportHeight(): number {\n return this._screenMode === \"split-footer\" ? this.renderOffset : this.height;\n }\n\n get screenMode(): ScreenMode {\n return this._screenMode;\n }\n\n get externalOutputMode(): ExternalOutputMode {\n return this._externalOutputMode;\n }\n\n get keyInput(): KeyInput {\n return this._keyInput;\n }\n\n /**\n * Two-tier priority key dispatcher.\n *\n * - `.on(\"keypress\", fn)` → tier-1 global handler (fires before any focused\n * widget). Can call `key.preventDefault()` / `key.stopPropagation()`.\n * - `.onInternal(\"keypress\", fn)` → tier-2 renderable handler (used by\n * focusable widgets; only fires when no global handler stopped propagation).\n *\n * Example code that needs to intercept keys before the focused widget should\n * use `renderer.keyHandler.on(...)`. Widgets must use\n * `renderer.keyHandler.onInternal(...)` inside `focus()`.\n */\n get keyHandler(): InternalKeyHandler {\n return this._keyDispatch;\n }\n\n get version(): string {\n return getVersion();\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /** The scene root renderable. All top-level renderables should be added here. */\n get root(): import(\"../renderables/Box\").Root {\n if (!this._root) {\n const Ctor = getRoot();\n this._root = new Ctor(this);\n }\n return this._root;\n }\n\n /** The terminal console overlay. */\n get console(): TerminalConsole {\n return this._console;\n }\n\n /** Current terminal theme mode (light/dark). */\n get themeMode(): ThemeMode {\n return this._themeMode;\n }\n\n /** Terminal capabilities detected at startup. */\n get capabilities(): TerminalCapabilities {\n return this._capabilities;\n }\n\n getDiagnostics(): DiagnosticSnapshot {\n return loggerGetDiagnostics();\n }\n\n get devtools(): DevTools {\n return this._devtools;\n }\n\n get debugEnabled(): boolean {\n return this.overlay !== null;\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n /** Start the render loop and keyboard input. */\n start(): void {\n if (this.running) return;\n this.running = true;\n this.paused = false;\n\n if (this._screenMode === \"alternate-screen\") {\n this.enterAlternateScreen();\n }\n this._keyInput.start();\n this._startFrameLoop();\n }\n\n /** Stop the render loop and exit alternate screen. */\n stop(): void {\n if (!this.running) return;\n this.running = false;\n this._stopFrameLoop();\n this._keyInput.stop();\n\n if (this._screenMode === \"split-footer\") {\n this.flushExternalOutput();\n } else {\n this.exitAlternateScreen();\n }\n }\n\n /**\n * Auto-start / toggle mode.\n * Starts if stopped, or pauses/resumes the loop if running.\n */\n auto(): void {\n if (!this.running) {\n this.start();\n } else if (this.paused) {\n this.resume();\n }\n }\n\n /** Pause the frame loop without stopping input. */\n pause(): void {\n this.paused = true;\n }\n\n /** Resume a paused frame loop. */\n resume(): void {\n this.paused = false;\n }\n\n /** Full suspend: stop input and frame loop. */\n suspend(): void {\n this.paused = true;\n this._keyInput.stop();\n }\n\n /** Full cleanup: stop everything and destroy engine. */\n destroy(): void {\n this._onDestroy?.();\n this._stopFrameLoop();\n try {\n this._keyInput.stop();\n } catch {\n /* ignore */\n }\n if (this._screenMode === \"split-footer\") {\n try {\n this.flushExternalOutput();\n } catch {\n /* ignore */\n }\n } else {\n try {\n this.exitAlternateScreen();\n } catch {\n /* ignore */\n }\n }\n if (this._resizeHandler) {\n process.stdout.off(\"resize\", this._resizeHandler);\n this._resizeHandler = null;\n }\n this.running = false;\n this.emit(CliRenderEvents.DESTROY);\n try {\n this.engine.shutdown();\n } catch {\n /* ignore */\n }\n }\n\n // ── Frame loop ────────────────────────────────────────────────────────────────\n\n private _startFrameLoop(): void {\n const msPerFrame = 1000 / this._targetFps;\n let lastTime = performance.now();\n\n const loop = () => {\n if (!this.running) return;\n\n const frameStart = performance.now();\n const dt = frameStart - lastTime;\n lastTime = frameStart;\n\n if (!this.paused) {\n // Run frame callbacks\n for (const cb of this._frameCallbacks) {\n try {\n cb(dt);\n } catch (err) {\n console.error(\"Frame callback error:\", err);\n }\n }\n\n // Emit frame event\n this._frameId++;\n this.emit(CliRenderEvents.FRAME, { frameId: this._frameId });\n\n // Run lifecycle passes (e.g. Text syncing its node tree to the engine)\n for (const pass of this._lifecyclePasses) {\n try {\n pass();\n } catch (err) {\n console.error(\"Lifecycle pass error:\", err);\n }\n }\n\n // Render\n try {\n this.render();\n } catch {\n /* ignore render errors */\n }\n }\n\n const processingTime = performance.now() - frameStart;\n const delay = Math.max(0, msPerFrame - processingTime);\n if (this.running) {\n this._frameInterval = setTimeout(loop, Math.round(delay));\n }\n };\n\n this._frameInterval = setTimeout(loop, 0);\n }\n\n private _stopFrameLoop(): void {\n if (this._frameInterval !== null) {\n clearTimeout(this._frameInterval);\n this._frameInterval = null;\n }\n }\n\n /** Register a frame callback (called every frame before render). */\n setFrameCallback(cb: FrameCallback): void {\n this._frameCallbacks.add(cb);\n }\n\n /** Remove a previously registered frame callback. */\n removeFrameCallback(cb: FrameCallback): void {\n this._frameCallbacks.delete(cb);\n }\n\n /** Clear all frame callbacks. */\n clearFrameCallbacks(): void {\n this._frameCallbacks.clear();\n }\n\n /** Register a function to be called once per frame before render (lifecycle pass). */\n registerLifecyclePass(fn: () => void): void {\n this._lifecyclePasses.add(fn);\n }\n\n /** Unregister a previously registered lifecycle pass function. */\n unregisterLifecyclePass(fn: () => void): void {\n this._lifecyclePasses.delete(fn);\n }\n\n /** Request an immediate render (useful outside the frame loop). */\n requestRender(): void {\n if (!this._pendingRender) {\n this._pendingRender = true;\n setImmediate(() => {\n this._pendingRender = false;\n try {\n this.render();\n } catch {\n /* ignore */\n }\n });\n }\n }\n\n // ── Visual API ────────────────────────────────────────────────────────────────\n\n /** Set the terminal window title via OSC 0 sequence. */\n setTerminalTitle(title: string): void {\n process.stdout.write(`\\x1b]0;${title}\\x07`);\n }\n\n setBackgroundColor(color: string): void {\n try {\n this.engine.setBackgroundColor?.(color);\n this.engine.setStyle(this.engine.root(), JSON.stringify({ bg: color }));\n } catch {\n /* ignore */\n }\n }\n\n dumpHitGrid(): void {\n try {\n this.engine.hitGridDump?.();\n } catch {\n /* ignore */\n }\n }\n\n copyToClipboardOSC52(text: string): void {\n const encoded = Buffer.from(text).toString(\"base64\");\n process.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n }\n\n clearClipboardOSC52(): void {\n process.stdout.write(\"\\x1b]52;c;!\\x07\");\n }\n\n /** Increment the live render counter; starts the renderer if not running. */\n requestLive(): void {\n this._liveCount++;\n if (!this.running) {\n this.start();\n }\n }\n\n /** Decrement the live render counter. */\n dropLive(): void {\n this._liveCount = Math.max(0, this._liveCount - 1);\n }\n\n clearSelection(): void {}\n getSelectionContainer(): null {\n return null;\n }\n get hasSelection(): boolean {\n return false;\n }\n setCursorPosition(_x: number, _y: number, _visible?: boolean): void {}\n\n toggleDebugOverlay(panel: DebugPanel = DebugPanel.Performance): void {\n if (!this.overlay) return;\n const nowVisible = this._devtools.toggle(panel);\n if (!nowVisible && !this.overlay.visible) {\n this.overlay.clear();\n this.renderFull();\n }\n }\n\n configureDebugOverlay(options: Parameters<OverlayHost[\"configure\"]>[0]): void {\n this.overlay?.configure(options);\n }\n\n // ── Node management ───────────────────────────────────────────────────────────\n\n get rootNodeId(): number {\n return this.engine.root();\n }\n\n getChildrenOf(id: number): number[] {\n return this.nodes.get(id)?.children ?? [];\n }\n\n setNodeStyle(id: number, style: Style): void {\n this.engine.setStyle(id, JSON.stringify(style));\n }\n\n setNodeLayout(id: number, layout: LayoutConstraints): void {\n const layoutJson = layoutToEngineJson(layout);\n this.engine.setLayout(id, JSON.stringify(layoutJson));\n }\n\n insertNodeBefore(parentId: number, childId: number, beforeId: number): void {\n this.engine.insertBefore(beforeId, childId);\n const parentNode = this.nodes.get(parentId);\n if (parentNode) {\n const beforeIdx = parentNode.children.indexOf(beforeId);\n const childIdx = parentNode.children.indexOf(childId);\n if (childIdx !== -1) parentNode.children.splice(childIdx, 1);\n const insertAt = beforeIdx === -1 ? parentNode.children.length : beforeIdx;\n parentNode.children.splice(insertAt, 0, childId);\n const childNode = this.nodes.get(childId);\n if (childNode) childNode.parent = parentId;\n }\n }\n\n createNode(kind: string): number {\n const id = this.engine.createNode(kind);\n this.nodes.set(id, { parent: null, children: [] });\n return id;\n }\n\n appendChild(parent: number, child: number): boolean {\n const result = this.engine.appendChild(parent, child);\n if (result) {\n const parentNode = this.nodes.get(parent);\n const childNode = this.nodes.get(child);\n if (parentNode && childNode) {\n parentNode.children.push(child);\n childNode.parent = parent;\n }\n }\n return result;\n }\n\n removeNode(id: number): void {\n const node = this.nodes.get(id);\n if (node) {\n if (node.parent !== null) {\n const parent = this.nodes.get(node.parent);\n if (parent) {\n parent.children = parent.children.filter((c) => c !== id);\n }\n }\n for (const child of node.children) {\n this.removeNode(child);\n }\n this.nodes.delete(id);\n }\n try {\n this.engine.removeNode(id);\n } catch {\n /* ignore */\n }\n }\n\n setText(id: number, text: string): void {\n this.engine.setText(id, text);\n }\n\n /** Set the scroll offset on a node so its children are shifted during rendering.\n * Use with `overflow: \"hidden\"` on the same node for clipped scrolling. */\n setScrollOffset(nodeId: number, scrollX: number, scrollY: number): void {\n this.engine.setScrollOffset(nodeId, scrollX, scrollY);\n }\n\n clearTree(): void {\n const rootId = this.engine.root();\n const rootNode = this.nodes.get(rootId);\n if (rootNode) {\n for (const child of [...rootNode.children]) {\n this.removeNode(child);\n }\n }\n }\n\n // ── Screen modes ──────────────────────────────────────────────────────────────\n\n setScreenMode(mode: ScreenMode, footerHeight?: number): void {\n const oldMode = this._screenMode;\n this._screenMode = mode;\n\n if (mode === \"split-footer\") {\n this._externalOutputMode = \"capture-stdout\";\n this.renderOffset = Math.max(0, this.height - (footerHeight ?? 0));\n this.engine.setScreenMode(\"split-footer\", footerHeight ?? 0);\n if (oldMode === \"alternate-screen\") {\n this.exitAlternateScreen();\n }\n } else if (mode === \"alternate-screen\") {\n this._externalOutputMode = \"passthrough\";\n this.renderOffset = 0;\n this.engine.setScreenMode(\"alternate-screen\");\n if (oldMode === \"split-footer\") {\n process.stdout.write(\"\\x1b[2J\\x1b[H\");\n }\n this.enterAlternateScreen();\n } else {\n this._externalOutputMode = \"passthrough\";\n this.renderOffset = 0;\n this.engine.setScreenMode(\"main-screen\");\n if (oldMode === \"alternate-screen\") {\n this.exitAlternateScreen();\n }\n }\n }\n\n // ── Rendering ─────────────────────────────────────────────────────────────────\n\n render(): void {\n const start = performance.now();\n this.engine.beginFrame();\n const frame = this.engine.render();\n this.engine.commitFrame();\n this.writeFrame(frame, performance.now() - start);\n }\n\n renderFull(): void {\n const start = performance.now();\n this.engine.beginFrame();\n const frame = this.engine.renderFull();\n this.engine.commitFrame();\n this.writeFrame(frame, performance.now() - start);\n }\n\n private writeFrame(\n frame: { output_data: string; dirty_region_count?: number },\n renderDuration: number,\n ): void {\n if (frame.output_data) {\n const decoded = Buffer.from(frame.output_data, \"base64\");\n if (this._screenMode === \"split-footer\") {\n process.stdout.write(`\\x1b[1;1H${decoded.toString()}`);\n } else {\n process.stdout.write(decoded);\n }\n }\n\n if (this._screenMode === \"split-footer\" && this.externalOutputBuffer.length > 0) {\n this.flushExternalOutput();\n }\n\n if (this._devtools.enabled) {\n const now = performance.now();\n const dirtyRegionCount = frame.dirty_region_count ?? 0;\n this._devtools.recordFrame({\n duration: this.lastFrameTime > 0 ? now - this.lastFrameTime : renderDuration,\n renderDuration,\n dirtyRegionCount,\n });\n this.lastFrameTime = now;\n\n if (this.overlay) {\n this.overlay.setDirtyRegionCount(dirtyRegionCount);\n if (this.overlay.visible) {\n this.overlay.paint();\n }\n }\n }\n }\n\n clearScreen(): void {\n process.stdout.write(\"\\x1b[2J\\x1b[H\");\n }\n\n write(text: string): void {\n process.stdout.write(text);\n }\n\n resize(width: number, height: number): void {\n this.width = width;\n this.height = height;\n if (this._screenMode === \"split-footer\") {\n this.engine.resize(width, this.viewportHeight);\n } else {\n this.engine.resize(width, height);\n }\n }\n\n // ── Key bindings ──────────────────────────────────────────────────────────────\n\n handleKey(sequence: string): string | null {\n return this.keymap.handleKey(sequence);\n }\n\n addKeyBinding(\n layer: string,\n id: string,\n keys: string,\n command: string,\n description?: string,\n priority = 0,\n ): boolean {\n return this.keymap.addBinding(layer, id, keys, command, description ?? null, priority);\n }\n\n // ── Private helpers ───────────────────────────────────────────────────────────\n\n private flushExternalOutput(): void {\n if (this.externalOutputBuffer.length === 0) return;\n const output = this.externalOutputBuffer.join(\"\");\n this.externalOutputBuffer = [];\n process.stdout.write(`\\x1b[${this.renderOffset + 1};1H${output}`);\n }\n\n interceptStdoutWrite = (chunk: string | Uint8Array): boolean => {\n if (this._externalOutputMode === \"capture-stdout\") {\n this.externalOutputBuffer.push(\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString(\"utf8\"),\n );\n return true;\n }\n return false;\n };\n\n private enterAlternateScreen(): void {\n process.stdout.write(\"\\x1b[?1049h\\x1b[?25l\");\n }\n\n private exitAlternateScreen(): void {\n process.stdout.write(\"\\x1b[?25h\\x1b[?1049l\");\n }\n}\n\nexport async function createCliRenderer(options: CliRendererOptions = {}): Promise<CliRenderer> {\n const renderer = new CliRenderer(options);\n return renderer;\n}\n\n// ── Utility ───────────────────────────────────────────────────────────────────\n\nfunction mapCapabilities(caps: TerminalCapabilities): {\n trueColor: boolean;\n kittyKeyboard: boolean;\n mouseSupport: boolean;\n osc52: boolean;\n osc8: boolean;\n pixelSupport: boolean;\n terminalBrand: string;\n terminalSize: { columns: number; rows: number };\n syncUpdate: boolean;\n bracketedPaste: boolean;\n focusEvents: boolean;\n strikethrough: boolean;\n underlineColor: boolean;\n cursorStyle: boolean;\n sixel: boolean;\n inlineImages: boolean;\n} {\n return {\n trueColor: caps.true_color,\n kittyKeyboard: caps.kitty_keyboard,\n mouseSupport: caps.mouse,\n osc52: caps.osc52,\n osc8: caps.osc8,\n pixelSupport: caps.sgr_pixel,\n terminalBrand: caps.brand,\n terminalSize: { columns: caps.columns, rows: caps.rows },\n syncUpdate: caps.sync,\n bracketedPaste: caps.bracketed_paste,\n focusEvents: caps.focus_events,\n strikethrough: caps.strikethrough,\n underlineColor: caps.underline_color,\n cursorStyle: caps.cursor_style,\n sixel: caps.sixel,\n inlineImages: caps.inline_images,\n };\n}\n\nexport { getVersion, detectCapabilities };\n","export type LogLevel = \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerConfig {\n level?: LogLevel;\n color?: boolean;\n timestamp?: boolean;\n module?: boolean;\n thread?: boolean;\n /**\n * Explicit log file path. When set, file logging is enabled in any mode and\n * writes to exactly this path. Overridden by the `BETTERTUI_LOG_DIR` env var.\n */\n file?: string;\n maxFileSize?: number;\n maxFiles?: number;\n /**\n * Development mode. When `true` and no explicit `file` is given, logs are\n * written to a daily file under the repo-root `logs/` directory (and still\n * mirrored to the terminal). When `false` (production), file logging stays\n * OFF unless an explicit `file` path (or `BETTERTUI_LOG_DIR`) is provided.\n *\n * `CliRenderer` defaults this to `process.env.NODE_ENV !== \"production\"` when\n * the caller does not set it explicitly.\n */\n dev?: boolean;\n}\n\nexport interface DiagnosticSnapshot {\n renderCalls: number;\n renderBytes: number;\n eventDispatches: number;\n layoutComputations: number;\n cacheHits: number;\n cacheMisses: number;\n allocations: number;\n averageFrameTime: number;\n fps: number;\n}\n\nexport interface Logger {\n init(config: LoggerConfig): void;\n setLevel(level: LogLevel): void;\n getLevel(): LogLevel;\n setModuleFilter(include?: string[], exclude?: string[]): void;\n getDiagnostics(): DiagnosticSnapshot;\n flush(): void;\n}\n\nexport function cacheHitRatio(snapshot: DiagnosticSnapshot): number {\n const total = snapshot.cacheHits + snapshot.cacheMisses;\n return total === 0 ? 0 : snapshot.cacheHits / total;\n}\n","import type { CliRenderer } from \"../platform/cliRenderer\";\n\nexport const KeyCodes = {\n RETURN: \"\\r\",\n LINEFEED: \"\\n\",\n TAB: \"\\t\",\n BACKSPACE: \"\\x7f\",\n DELETE: \"\\x1b[3~\",\n HOME: \"\\x1b[H\",\n END: \"\\x1b[F\",\n ESCAPE: \"\\x1b\",\n\n ARROW_UP: \"\\x1b[A\",\n ARROW_DOWN: \"\\x1b[B\",\n ARROW_RIGHT: \"\\x1b[C\",\n ARROW_LEFT: \"\\x1b[D\",\n\n F1: \"\\x1bOP\",\n F2: \"\\x1bOQ\",\n F3: \"\\x1bOR\",\n F4: \"\\x1bOS\",\n F5: \"\\x1b[15~\",\n F6: \"\\x1b[17~\",\n F7: \"\\x1b[18~\",\n F8: \"\\x1b[19~\",\n F9: \"\\x1b[20~\",\n F10: \"\\x1b[21~\",\n F11: \"\\x1b[23~\",\n F12: \"\\x1b[24~\",\n\n PAGE_UP: \"\\x1b[5~\",\n PAGE_DOWN: \"\\x1b[6~\",\n} as const;\n\nexport type TestKeyInput = string | keyof typeof KeyCodes;\n\nexport interface MockKeysOptions {\n kittyKeyboard?: boolean | undefined;\n}\n\nexport interface KeyModifiers {\n shift?: boolean;\n ctrl?: boolean;\n alt?: boolean;\n meta?: boolean;\n}\n\nfunction resolveKeyInput(key: TestKeyInput): string {\n if (typeof key === \"string\") {\n if (key in KeyCodes) {\n return KeyCodes[key as keyof typeof KeyCodes];\n }\n return key;\n }\n return KeyCodes[key];\n}\n\nexport function createMockKeys(_renderer: CliRenderer, _options?: MockKeysOptions) {\n const keyHistory: string[] = [];\n\n const pressKey = (key: TestKeyInput, modifiers?: KeyModifiers): void => {\n let keyCode = resolveKeyInput(key);\n keyHistory.push(keyCode);\n\n if (modifiers) {\n if (modifiers.ctrl && keyCode.length === 1) {\n const char = keyCode.toLowerCase();\n if (char >= \"a\" && char <= \"z\") {\n keyCode = String.fromCharCode(char.charCodeAt(0) - 96);\n }\n }\n if (modifiers.alt) {\n keyCode = `\\x1b${keyCode}`;\n }\n }\n\n process.stdin.emit(\"data\", Buffer.from(keyCode));\n };\n\n const pressKeys = async (keys: TestKeyInput[], delayMs = 0): Promise<void> => {\n for (const key of keys) {\n pressKey(key);\n if (delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n };\n\n const typeText = async (text: string, delayMs = 0): Promise<void> => {\n const keys = text.split(\"\");\n await pressKeys(keys, delayMs);\n };\n\n const pressEnter = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.RETURN, modifiers);\n };\n\n const pressEscape = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.ESCAPE, modifiers);\n };\n\n const pressTab = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.TAB, modifiers);\n };\n\n const pressBackspace = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.BACKSPACE, modifiers);\n };\n\n const pressArrow = (\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n modifiers?: KeyModifiers,\n ): void => {\n const keyMap = {\n up: KeyCodes.ARROW_UP,\n down: KeyCodes.ARROW_DOWN,\n left: KeyCodes.ARROW_LEFT,\n right: KeyCodes.ARROW_RIGHT,\n };\n pressKey(keyMap[direction], modifiers);\n };\n\n const pressCtrlC = (): void => {\n pressKey(\"c\", { ctrl: true });\n };\n\n const pressCtrlD = (): void => {\n pressKey(\"d\", { ctrl: true });\n };\n\n const pressPageUp = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.PAGE_UP, modifiers);\n };\n\n const pressPageDown = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.PAGE_DOWN, modifiers);\n };\n\n const pressHome = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.HOME, modifiers);\n };\n\n const pressEnd = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.END, modifiers);\n };\n\n const pressDelete = (modifiers?: KeyModifiers): void => {\n pressKey(KeyCodes.DELETE, modifiers);\n };\n\n const getKeyHistory = (): string[] => [...keyHistory];\n const clearHistory = (): void => {\n keyHistory.length = 0;\n };\n\n return {\n pressKey,\n pressKeys,\n typeText,\n pressEnter,\n pressEscape,\n pressTab,\n pressBackspace,\n pressArrow,\n pressCtrlC,\n pressCtrlD,\n pressPageUp,\n pressPageDown,\n pressHome,\n pressEnd,\n pressDelete,\n getKeyHistory,\n clearHistory,\n };\n}\n","export const MouseButtons = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2,\n\n WHEEL_UP: 64,\n WHEEL_DOWN: 65,\n WHEEL_LEFT: 66,\n WHEEL_RIGHT: 67,\n} as const;\n\nexport type MouseButton = (typeof MouseButtons)[keyof typeof MouseButtons];\n\nexport interface MousePosition {\n x: number;\n y: number;\n}\n\nexport interface MouseModifiers {\n shift?: boolean;\n alt?: boolean;\n ctrl?: boolean;\n}\n\nexport type MouseEventType = \"down\" | \"up\" | \"move\" | \"drag\" | \"scroll\";\n\nexport interface MouseEventOptions {\n button?: MouseButton;\n modifiers?: MouseModifiers;\n delayMs?: number;\n}\n\nexport function createMockMouse() {\n let currentPosition: MousePosition = { x: 0, y: 0 };\n const buttonsPressed = new Set<MouseButton>();\n const eventHistory: string[] = [];\n\n const generateMouseEvent = (\n type: MouseEventType,\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n modifiers: MouseModifiers = {},\n ): string => {\n let buttonCode: number = button;\n\n if (modifiers.shift) buttonCode |= 4;\n if (modifiers.alt) buttonCode |= 8;\n if (modifiers.ctrl) buttonCode |= 16;\n\n switch (type) {\n case \"move\":\n buttonCode = 32 | 3;\n if (modifiers.shift) buttonCode |= 4;\n if (modifiers.alt) buttonCode |= 8;\n if (modifiers.ctrl) buttonCode |= 16;\n break;\n case \"drag\":\n buttonCode = (buttonsPressed.size > 0 ? ([...buttonsPressed][0] as number) : button) | 32;\n if (modifiers.shift) buttonCode |= 4;\n if (modifiers.alt) buttonCode |= 8;\n if (modifiers.ctrl) buttonCode |= 16;\n break;\n case \"scroll\":\n break;\n }\n\n const ansiX = x + 1;\n const ansiY = y + 1;\n\n let pressRelease = \"M\";\n if (type === \"up\" || type === \"move\" || type === \"drag\") {\n pressRelease = \"m\";\n }\n\n return `\\x1b[<${buttonCode};${ansiX};${ansiY}${pressRelease}`;\n };\n\n const emitMouseEvent = async (\n type: MouseEventType,\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n options: Omit<MouseEventOptions, \"button\"> = {},\n ): Promise<void> => {\n const { modifiers = {}, delayMs = 0 } = options;\n\n const eventSequence = generateMouseEvent(type, x, y, button, modifiers);\n eventHistory.push(eventSequence);\n process.stdin.emit(\"data\", Buffer.from(eventSequence));\n\n currentPosition = { x, y };\n\n if (type === \"down\" && button < 64) {\n buttonsPressed.add(button);\n } else if (type === \"up\") {\n buttonsPressed.delete(button);\n }\n\n if (delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n };\n\n const moveTo = async (x: number, y: number, options: MouseEventOptions = {}): Promise<void> => {\n const { button = MouseButtons.LEFT, delayMs = 0, modifiers = {} } = options;\n\n if (buttonsPressed.size > 0) {\n await emitMouseEvent(\"drag\", x, y, [...buttonsPressed][0] as MouseButton, {\n modifiers,\n delayMs,\n });\n } else {\n await emitMouseEvent(\"move\", x, y, button, { modifiers, delayMs });\n }\n\n currentPosition = { x, y };\n };\n\n const click = async (\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { delayMs = 10, modifiers = {} } = options;\n\n await emitMouseEvent(\"down\", x, y, button, { modifiers, delayMs });\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n await emitMouseEvent(\"up\", x, y, button, { modifiers, delayMs });\n };\n\n const doubleClick = async (\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { delayMs = 10, modifiers = {} } = options;\n\n await click(x, y, button, { modifiers, delayMs });\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n await click(x, y, button, { modifiers, delayMs });\n };\n\n const pressDown = async (\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { modifiers = {}, delayMs = 0 } = options;\n await emitMouseEvent(\"down\", x, y, button, { modifiers, delayMs });\n };\n\n const release = async (\n x: number,\n y: number,\n button: MouseButton = MouseButtons.LEFT,\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { modifiers = {}, delayMs = 0 } = options;\n await emitMouseEvent(\"up\", x, y, button, { modifiers, delayMs });\n };\n\n const drag = async (\n startX: number,\n startY: number,\n endX: number,\n endY: number,\n button: MouseButton = MouseButtons.LEFT,\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { delayMs = 10, modifiers = {} } = options;\n\n await pressDown(startX, startY, button, { modifiers });\n\n const steps = 5;\n const dx = (endX - startX) / steps;\n const dy = (endY - startY) / steps;\n\n for (let i = 1; i <= steps; i++) {\n const currentX = Math.round(startX + dx * i);\n const currentY = Math.round(startY + dy * i);\n await emitMouseEvent(\"drag\", currentX, currentY, button, { modifiers, delayMs });\n }\n\n await release(endX, endY, button, { modifiers });\n };\n\n const scroll = async (\n x: number,\n y: number,\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n options: MouseEventOptions = {},\n ): Promise<void> => {\n const { modifiers = {}, delayMs = 0 } = options;\n\n let button: MouseButton;\n switch (direction) {\n case \"up\":\n button = MouseButtons.WHEEL_UP;\n break;\n case \"down\":\n button = MouseButtons.WHEEL_DOWN;\n break;\n case \"left\":\n button = MouseButtons.WHEEL_LEFT;\n break;\n case \"right\":\n button = MouseButtons.WHEEL_RIGHT;\n break;\n }\n\n await emitMouseEvent(\"scroll\", x, y, button, { modifiers, delayMs });\n };\n\n const getCurrentPosition = (): MousePosition => ({ ...currentPosition });\n const getPressedButtons = (): MouseButton[] => [...buttonsPressed];\n const getEventHistory = (): string[] => [...eventHistory];\n const clearHistory = (): void => {\n eventHistory.length = 0;\n };\n\n return {\n moveTo,\n click,\n doubleClick,\n pressDown,\n release,\n drag,\n scroll,\n getCurrentPosition,\n getPressedButtons,\n emitMouseEvent,\n getEventHistory,\n clearHistory,\n };\n}\n","import { Readable, Writable } from \"node:stream\";\n\nexport class TestWriteStream extends Writable {\n public readonly isTTY = true;\n public columns: number;\n public rows: number;\n public buffer: Buffer = Buffer.alloc(0);\n\n constructor(columns = 80, rows = 24) {\n super();\n this.columns = columns;\n this.rows = rows;\n }\n\n override _write(\n chunk: Buffer,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void,\n ): void {\n this.buffer = Buffer.concat([this.buffer, chunk]);\n callback();\n }\n\n getColorDepth(): number {\n return 24;\n }\n\n getOutput(): string {\n return this.buffer.toString(\"utf8\");\n }\n\n clear(): void {\n this.buffer = Buffer.alloc(0);\n }\n}\n\nexport type TestStdout = TestWriteStream & NodeJS.WriteStream;\n\nexport class TestReadStream extends Readable {\n public readonly isTTY = true;\n\n constructor() {\n super({ read() {} });\n }\n\n emitData(data: string | Buffer): void {\n this.push(Buffer.from(data));\n }\n}\n\nexport type TestStdin = TestReadStream & NodeJS.ReadStream;\n\nexport function createTestStdin(): TestStdin {\n return new TestReadStream() as TestStdin;\n}\n\nexport function createTestStdout(columns = 80, rows = 24): TestStdout {\n return new TestWriteStream(columns, rows) as TestStdout;\n}\n","import type { CliRenderer, CliRendererOptions } from \"../platform/cliRenderer\";\nimport { CliRenderer as CliRendererClass, createCliRenderer } from \"../platform/cliRenderer\";\nimport { createMockKeys } from \"./mockKeys\";\nimport { createMockMouse } from \"./mockMouse\";\nimport { createTestStdin, createTestStdout } from \"./testStreams\";\nimport type { TestStdin, TestStdout } from \"./testStreams\";\n\nexport interface TestRendererOptions extends CliRendererOptions {\n width?: number;\n height?: number;\n kittyKeyboard?: boolean;\n}\n\nexport type TestRenderer = CliRenderer;\nexport type MockInput = ReturnType<typeof createMockKeys>;\nexport type MockMouse = ReturnType<typeof createMockMouse>;\n\nexport interface TestRendererSetup {\n renderer: TestRenderer;\n mockInput: MockInput;\n mockMouse: MockMouse;\n stdin: TestStdin;\n stdout: TestStdout;\n renderOnce: () => void;\n captureFrame: () => string;\n resize: (width: number, height: number) => void;\n cleanup: () => void;\n}\n\nexport async function createTestRenderer(\n options: TestRendererOptions = {},\n): Promise<TestRendererSetup> {\n const width = options.width ?? 80;\n const height = options.height ?? 24;\n\n const stdin = createTestStdin();\n const stdout = createTestStdout(width, height);\n\n const originalStdin = process.stdin;\n const originalStdout = process.stdout;\n\n Object.defineProperty(process, \"stdin\", { value: stdin, writable: true, configurable: true });\n Object.defineProperty(process, \"stdout\", { value: stdout, writable: true, configurable: true });\n\n const renderer = await createCliRenderer({\n width,\n height,\n ...options,\n });\n\n const mockInput = createMockKeys(renderer, { kittyKeyboard: options.kittyKeyboard });\n const mockMouse = createMockMouse();\n\n const renderOnce = (): void => {\n renderer.render();\n };\n\n const captureFrame = (): string => {\n return stdout.getOutput();\n };\n\n const resize = (newWidth: number, newHeight: number): void => {\n stdout.columns = newWidth;\n stdout.rows = newHeight;\n renderer.resize(newWidth, newHeight);\n };\n\n const cleanup = (): void => {\n renderer.stop();\n Object.defineProperty(process, \"stdin\", {\n value: originalStdin,\n writable: true,\n configurable: true,\n });\n Object.defineProperty(process, \"stdout\", {\n value: originalStdout,\n writable: true,\n configurable: true,\n });\n stdout.clear();\n };\n\n return {\n renderer,\n mockInput,\n mockMouse,\n stdin,\n stdout,\n renderOnce,\n captureFrame,\n resize,\n cleanup,\n };\n}\n\nexport function createTestRendererSync(options: TestRendererOptions = {}): TestRendererSetup {\n const width = options.width ?? 80;\n const height = options.height ?? 24;\n\n const stdin = createTestStdin();\n const stdout = createTestStdout(width, height);\n\n const originalStdin = process.stdin;\n const originalStdout = process.stdout;\n\n Object.defineProperty(process, \"stdin\", { value: stdin, writable: true, configurable: true });\n Object.defineProperty(process, \"stdout\", { value: stdout, writable: true, configurable: true });\n\n const renderer = new CliRendererClass({\n width,\n height,\n ...options,\n });\n\n const mockInput = createMockKeys(renderer, { kittyKeyboard: options.kittyKeyboard });\n const mockMouse = createMockMouse();\n\n const renderOnce = (): void => {\n renderer.render();\n };\n\n const captureFrame = (): string => {\n return stdout.getOutput();\n };\n\n const resize = (newWidth: number, newHeight: number): void => {\n stdout.columns = newWidth;\n stdout.rows = newHeight;\n renderer.resize(newWidth, newHeight);\n };\n\n const cleanup = (): void => {\n renderer.stop();\n Object.defineProperty(process, \"stdin\", {\n value: originalStdin,\n writable: true,\n configurable: true,\n });\n Object.defineProperty(process, \"stdout\", {\n value: originalStdout,\n writable: true,\n configurable: true,\n });\n stdout.clear();\n };\n\n return {\n renderer,\n mockInput,\n mockMouse,\n stdin,\n stdout,\n renderOnce,\n captureFrame,\n resize,\n cleanup,\n };\n}\n","export interface Spy {\n (...args: unknown[]): void;\n calls: unknown[][];\n callCount: () => number;\n calledWith: (...expected: unknown[]) => boolean;\n lastCall: () => unknown[] | undefined;\n reset: () => void;\n}\n\nexport function createSpy(): Spy {\n const calls: unknown[][] = [];\n const spy = (...args: unknown[]): void => {\n calls.push(args);\n };\n spy.calls = calls;\n spy.callCount = () => calls.length;\n spy.calledWith = (...expected: unknown[]): boolean => {\n return calls.some((call) => JSON.stringify(call) === JSON.stringify(expected));\n };\n spy.lastCall = (): unknown[] | undefined =>\n calls.length > 0 ? calls[calls.length - 1] : undefined;\n spy.reset = (): void => {\n calls.length = 0;\n };\n return spy;\n}\n","import type { TerminalCapabilities } from \"../platform/binding\";\n\nexport interface TerminalCapabilitiesOptions {\n trueColor?: boolean;\n kittyKeyboard?: boolean;\n csiU?: boolean;\n bracketedPaste?: boolean;\n focusEvents?: boolean;\n mouse?: boolean;\n osc52?: boolean;\n osc8?: boolean;\n sync?: boolean;\n sgrPixel?: boolean;\n underlineColor?: boolean;\n strikethrough?: boolean;\n cursorStyle?: boolean;\n alternateScroll?: boolean;\n inlineImages?: boolean;\n sixel?: boolean;\n columns?: number;\n rows?: number;\n brand?: string;\n}\n\nexport function createTerminalCapabilities(\n options: TerminalCapabilitiesOptions = {},\n): TerminalCapabilities {\n return {\n brand: options.brand ?? \"Test\",\n true_color: options.trueColor ?? true,\n kitty_keyboard: options.kittyKeyboard ?? false,\n csi_u: options.csiU ?? false,\n bracketed_paste: options.bracketedPaste ?? true,\n focus_events: options.focusEvents ?? true,\n mouse: options.mouse ?? true,\n osc52: options.osc52 ?? false,\n osc52_support: options.osc52 ?? false,\n osc8: options.osc8 ?? false,\n sync: options.sync ?? true,\n sgr_pixel: options.sgrPixel ?? false,\n underline_color: options.underlineColor ?? true,\n strikethrough: options.strikethrough ?? true,\n cursor_style: options.cursorStyle ?? true,\n alternate_scroll: options.alternateScroll ?? true,\n inline_images: options.inlineImages ?? false,\n sixel: options.sixel ?? false,\n columns: options.columns ?? 80,\n rows: options.rows ?? 24,\n };\n}\n\nexport function createMinimalTerminalCapabilities(): TerminalCapabilities {\n return createTerminalCapabilities({\n trueColor: false,\n kittyKeyboard: false,\n csiU: false,\n bracketedPaste: false,\n focusEvents: false,\n mouse: false,\n osc52: false,\n osc8: false,\n sync: false,\n sgrPixel: false,\n underlineColor: false,\n strikethrough: false,\n cursorStyle: false,\n alternateScroll: false,\n inlineImages: false,\n sixel: false,\n });\n}\n\nexport function createFullTerminalCapabilities(): TerminalCapabilities {\n return createTerminalCapabilities({\n trueColor: true,\n kittyKeyboard: true,\n csiU: true,\n bracketedPaste: true,\n focusEvents: true,\n mouse: true,\n osc52: true,\n osc8: true,\n sync: true,\n sgrPixel: true,\n underlineColor: true,\n strikethrough: true,\n cursorStyle: true,\n alternateScroll: true,\n inlineImages: true,\n sixel: true,\n });\n}\n\nexport function createKittyTerminalCapabilities(): TerminalCapabilities {\n return createTerminalCapabilities({\n brand: \"Kitty\",\n trueColor: true,\n kittyKeyboard: true,\n csiU: true,\n bracketedPaste: true,\n focusEvents: true,\n mouse: true,\n osc52: true,\n osc8: true,\n sync: true,\n sgrPixel: true,\n underlineColor: true,\n strikethrough: true,\n cursorStyle: true,\n alternateScroll: true,\n inlineImages: true,\n sixel: false,\n });\n}\n\nexport function createITerm2TerminalCapabilities(): TerminalCapabilities {\n return createTerminalCapabilities({\n brand: \"iTerm2\",\n trueColor: true,\n kittyKeyboard: false,\n csiU: true,\n bracketedPaste: true,\n focusEvents: true,\n mouse: true,\n osc52: true,\n osc8: true,\n sync: true,\n sgrPixel: false,\n underlineColor: true,\n strikethrough: true,\n cursorStyle: true,\n alternateScroll: true,\n inlineImages: true,\n sixel: false,\n });\n}\n","import { Keymap } from \"../lib/keybinding\";\nimport type { KeymapOptions } from \"../lib/keybinding\";\nimport type { NapiKeymap } from \"../platform/binding\";\nimport type { BindingInfo } from \"../platform/platform.types\";\n\nexport interface TestBinding {\n layer: string;\n id: string;\n keys: string;\n command: string;\n description: string | null;\n priority: number;\n enabled: boolean;\n}\n\ninterface PendingState {\n keys: string[];\n command: string | null;\n}\n\nexport function createMockNativeKeymap(): NapiKeymap {\n const bindings: TestBinding[] = [];\n const parsedKeys = new Map<string, string>();\n let currentModeStr = \"\";\n let pending: PendingState | null = null;\n let history: string[] = [];\n\n function parseKey(keyStr: string): string {\n let cached = parsedKeys.get(keyStr);\n if (cached) return cached;\n cached = keyStr.trim().toLowerCase();\n parsedKeys.set(keyStr, cached);\n return cached;\n }\n\n // Mirror Rust KeyParser::parse_sequence semantics:\n // - Repeated single-char (e.g. \"dd\") → chord of same key\n // - Comma-separated (e.g. \"ctrl+x,ctrl+s\") → sequence\n // - Single token → single key\n function parseSequence(keysStr: string): string[] {\n const trimmed = keysStr.trim();\n if (trimmed.includes(\",\")) {\n return trimmed.split(\",\").map((s) => parseKey(s));\n }\n if (\n trimmed.length === 2 &&\n !trimmed.includes(\"+\") &&\n !trimmed.includes(\"<\") &&\n trimmed[0] === trimmed[1]\n ) {\n return [parseKey(trimmed[0] as string), parseKey(trimmed[1] as string)];\n }\n return [parseKey(trimmed)];\n }\n\n return {\n addBinding(\n layer: string,\n id: string,\n keys: string,\n command: string,\n description: string | null,\n priority: number,\n ): boolean {\n bindings.push({ layer, id, keys, command, description, priority, enabled: true });\n return true;\n },\n\n setMode(mode: string): void {\n currentModeStr = mode;\n },\n currentMode(): string {\n return currentModeStr;\n },\n\n handleKey(keyStr: string): string {\n const parsed = parseKey(keyStr);\n\n // Check pending sequence first\n if (pending) {\n const expectedKey = pending.keys[0];\n if (parsed === expectedKey) {\n pending.keys.shift();\n if (pending.keys.length === 0) {\n const cmd = pending.command;\n pending = null;\n if (cmd) {\n history.push(cmd);\n return cmd;\n }\n return \"\";\n }\n return \"\";\n }\n pending = null;\n }\n\n // Find matching binding\n for (const b of bindings) {\n if (!b.enabled) continue;\n const seq = parseSequence(b.keys);\n if (seq.length === 0) continue;\n if (seq[0] !== parsed) continue;\n\n if (seq.length === 1) {\n history.push(b.command);\n return b.command;\n }\n\n pending = { keys: seq.slice(1), command: b.command };\n return \"\";\n }\n\n return \"\";\n },\n\n hasPending(): boolean {\n return pending !== null;\n },\n clearPending(): void {\n pending = null;\n },\n clearMode(): void {\n currentModeStr = \"\";\n },\n removeLayer(_name: string): boolean {\n return true;\n },\n setChordTimeout(_ms: number): void {},\n chordTimeout(): number {\n return 0;\n },\n pendingKeys(): string[] {\n return [];\n },\n activeBindings(): BindingInfo[] {\n return [];\n },\n allBindings(): BindingInfo[] {\n return [];\n },\n commandHistory(): string[] {\n return history;\n },\n clearHistory(): void {\n history = [];\n },\n parseKey(keyStr: string): string {\n return parseKey(keyStr);\n },\n parseSequence(keyStr: string): string[] {\n return [parseKey(keyStr)];\n },\n };\n}\n\nexport function createTestKeymap(\n bindings?: Array<{\n layer?: string;\n id?: string;\n keys: string;\n command: string;\n description?: string;\n priority?: number;\n }>,\n options?: KeymapOptions,\n): Keymap {\n const keymap = new Keymap(createMockNativeKeymap(), options);\n\n if (bindings) {\n for (const b of bindings) {\n keymap.addBinding(\n b.layer ?? \"test\",\n b.id ?? b.command,\n b.keys,\n b.command,\n b.description,\n b.priority ?? 0,\n );\n }\n }\n\n return keymap;\n}\n","/**\n * Animation utilities: easing functions, Tween, Spring, and interpolation helpers.\n *\n * @example\n * ```ts\n * import { easing, Tween, Spring, lerp } from \"@bettertui/core\"\n *\n * const tw = new Tween({ from: 0, to: 100, duration: 1, onUpdate: v => setX(v) })\n * tw.play()\n * tw.tick(deltaSeconds)\n * ```\n */\n\n// ── Easing functions ──────────────────────────────────────────────────────────\n\n/**\n * Standard easing functions operating on [0, 1].\n * Each function takes a normalised time `t` (0 = start, 1 = end) and returns\n * the eased value.\n */\nexport const easing = {\n linear: (t: number) => t,\n\n // Quadratic\n easeInQuad: (t: number) => t * t,\n easeOutQuad: (t: number) => t * (2 - t),\n easeInOutQuad: (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),\n\n // Cubic\n easeInCubic: (t: number) => t * t * t,\n easeOutCubic: (t: number) => {\n const tt = t - 1;\n return tt * tt * tt + 1;\n },\n easeInOutCubic: (t: number) =>\n t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,\n\n // Quartic\n easeInQuart: (t: number) => t * t * t * t,\n easeOutQuart: (t: number) => {\n const tt = t - 1;\n return 1 - tt * tt * tt * tt;\n },\n easeInOutQuart: (t: number) => {\n if (t < 0.5) return 8 * t * t * t * t;\n const tt = t - 1;\n return 1 - 8 * tt * tt * tt * tt;\n },\n\n // Sine\n easeInSine: (t: number) => 1 - Math.cos((t * Math.PI) / 2),\n easeOutSine: (t: number) => Math.sin((t * Math.PI) / 2),\n easeInOutSine: (t: number) => -(Math.cos(Math.PI * t) - 1) / 2,\n\n // Exponential\n easeInExpo: (t: number) => (t === 0 ? 0 : 2 ** (10 * t - 10)),\n easeOutExpo: (t: number) => (t === 1 ? 1 : 1 - 2 ** (-10 * t)),\n easeInOutExpo: (t: number) => {\n if (t === 0) return 0;\n if (t === 1) return 1;\n return t < 0.5 ? 2 ** (20 * t - 10) / 2 : (2 - 2 ** (-20 * t + 10)) / 2;\n },\n\n // Circular\n easeInCirc: (t: number) => 1 - Math.sqrt(1 - t * t),\n easeOutCirc: (t: number) => Math.sqrt(1 - (t - 1) ** 2),\n easeInOutCirc: (t: number) =>\n t < 0.5 ? (1 - Math.sqrt(1 - 4 * t * t)) / 2 : (Math.sqrt(1 - (-2 * t + 2) ** 2) + 1) / 2,\n\n // Back (overshoot)\n easeInBack: (t: number, s = 1.70158) => t * t * ((s + 1) * t - s),\n easeOutBack: (t: number, s = 1.70158) => {\n const tt = t - 1;\n return tt * tt * ((s + 1) * tt + s) + 1;\n },\n\n // Elastic\n easeInElastic: (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : -(2 ** (10 * t - 10)) * Math.sin((t * 10 - 10.75) * c4);\n },\n easeOutElastic: (t: number) => {\n const c4 = (2 * Math.PI) / 3;\n return t === 0 ? 0 : t === 1 ? 1 : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;\n },\n\n // Bounce\n easeOutBounce: (t: number): number => {\n const n1 = 7.5625;\n const d1 = 2.75;\n if (t < 1 / d1) return n1 * t * t;\n if (t < 2 / d1) {\n const t2 = t - 1.5 / d1;\n return n1 * t2 * t2 + 0.75;\n }\n if (t < 2.5 / d1) {\n const t2 = t - 2.25 / d1;\n return n1 * t2 * t2 + 0.9375;\n }\n const t2 = t - 2.625 / d1;\n return n1 * t2 * t2 + 0.984375;\n },\n easeInBounce: (t: number): number => 1 - easing.easeOutBounce(1 - t),\n} as const;\n\nexport type EasingName = keyof typeof easing;\n\n// ── Interpolation helpers ─────────────────────────────────────────────────────\n\n/** Linear interpolation between `a` and `b` by factor `t` (clamped to [0,1]). */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * Math.max(0, Math.min(1, t));\n}\n\n/** Inverse lerp: returns how far `value` is between `a` and `b` (0–1). */\nexport function inverseLerp(a: number, b: number, value: number): number {\n if (a === b) return 0;\n return Math.max(0, Math.min(1, (value - a) / (b - a)));\n}\n\n/** Smoothly interpolate between `a` and `b` using Hermite smoothstep. */\nexport function smoothstep(a: number, b: number, t: number): number {\n const x = Math.max(0, Math.min(1, (t - a) / (b - a)));\n return x * x * (3 - 2 * x);\n}\n\n/** Clamp `value` to [min, max]. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n// ── Imperative tween ──────────────────────────────────────────────────────────\n\nexport interface TweenOptions {\n from: number;\n to: number;\n duration: number;\n easing?: EasingName;\n onUpdate?: (value: number) => void;\n onComplete?: () => void;\n}\n\n/**\n * A simple imperative tween driven manually with `tick(dt)`.\n * Does NOT require a Timeline — useful for one-shot or procedural animations.\n *\n * @example\n * ```ts\n * const tw = new Tween({ from: 0, to: 255, duration: 1, onUpdate: v => setAlpha(v) })\n * tw.play()\n * tw.tick(deltaSeconds)\n * ```\n */\nexport class Tween {\n private _time = 0;\n private _playing = false;\n private readonly _options: TweenOptions;\n\n constructor(options: TweenOptions) {\n this._options = { ...options };\n }\n\n get value(): number {\n const { from, to, duration, easing: easingName = \"linear\" } = this._options;\n if (duration <= 0) return to;\n const t = clamp(this._time / duration, 0, 1);\n const easeFn = easing[easingName];\n return lerp(from, to, easeFn(t));\n }\n\n get progress(): number {\n return clamp(this._time / (this._options.duration || 1), 0, 1);\n }\n\n get isComplete(): boolean {\n return this._time >= this._options.duration;\n }\n\n play(): this {\n this._playing = true;\n return this;\n }\n\n pause(): this {\n this._playing = false;\n return this;\n }\n\n reset(): this {\n this._time = 0;\n this._playing = false;\n return this;\n }\n\n tick(dt: number): void {\n if (!this._playing) return;\n this._time = Math.min(this._time + dt, this._options.duration);\n this._options.onUpdate?.(this.value);\n if (this.isComplete) {\n this._playing = false;\n this._options.onComplete?.();\n }\n }\n}\n\n// ── Spring simulation ─────────────────────────────────────────────────────────\n\nexport interface SpringOptions {\n /** Natural frequency (stiffness). Higher = faster. Default: 10. */\n frequency?: number;\n /** Damping ratio. 1.0 = critically damped. Default: 0.8. */\n damping?: number;\n /** Initial position. Default: 0. */\n initial?: number;\n /** Target position. */\n target: number;\n}\n\n/**\n * Simple critically-damped spring for smooth follow animations.\n *\n * @example\n * ```ts\n * const spring = new Spring({ target: 100, frequency: 8, damping: 0.75 })\n * spring.tick(dt)\n * const x = spring.position\n * ```\n */\nexport class Spring {\n private _pos: number;\n private _vel = 0;\n private _target: number;\n private readonly _frequency: number;\n private readonly _damping: number;\n\n constructor(options: SpringOptions) {\n this._target = options.target;\n this._pos = options.initial ?? 0;\n this._frequency = options.frequency ?? 10;\n this._damping = options.damping ?? 0.8;\n }\n\n get position(): number {\n return this._pos;\n }\n\n get velocity(): number {\n return this._vel;\n }\n\n set target(t: number) {\n this._target = t;\n }\n\n /** Advance the spring simulation by `dt` seconds. */\n tick(dt: number): void {\n const omega = 2 * Math.PI * this._frequency;\n const zeta = this._damping;\n const x0 = this._pos - this._target;\n const v0 = this._vel;\n\n if (Math.abs(zeta - 1) < 1e-6) {\n // Critically damped\n const e = Math.exp(-omega * dt);\n const c2 = v0 + omega * x0;\n const newX = (x0 + c2 * dt) * e;\n const newV = c2 * e + (x0 + c2 * dt) * -omega * e;\n this._pos = newX + this._target;\n this._vel = newV;\n } else if (zeta < 1) {\n // Under-damped\n const omegaD = omega * Math.sqrt(1 - zeta * zeta);\n const e = Math.exp(-zeta * omega * dt);\n const cosD = Math.cos(omegaD * dt);\n const sinD = Math.sin(omegaD * dt);\n const newX = e * (x0 * cosD + ((v0 + zeta * omega * x0) / omegaD) * sinD);\n const newV =\n e *\n ((v0 + zeta * omega * x0) * cosD -\n (x0 * omegaD + (v0 + zeta * omega * x0) * ((zeta * omega) / omegaD)) * sinD) -\n zeta * omega * newX;\n this._pos = newX + this._target;\n this._vel = newV;\n } else {\n // Over-damped\n const alpha = omega * (zeta - Math.sqrt(zeta * zeta - 1));\n const beta = omega * (zeta + Math.sqrt(zeta * zeta - 1));\n const denom = beta - alpha;\n const c1 = (v0 + beta * x0) / denom;\n const c2 = -(v0 + alpha * x0) / denom;\n this._pos = c1 * Math.exp(-alpha * dt) + c2 * Math.exp(-beta * dt) + this._target;\n this._vel = -c1 * alpha * Math.exp(-alpha * dt) - c2 * beta * Math.exp(-beta * dt);\n }\n }\n\n /** Instantly snap to the target. */\n snap(): void {\n this._pos = this._target;\n this._vel = 0;\n }\n\n /** Returns true when the spring has essentially settled. */\n isSettled(tolerance = 0.01): boolean {\n return Math.abs(this._pos - this._target) < tolerance && Math.abs(this._vel) < tolerance;\n }\n}\n","/**\n * Terminal graphics utilities: pixel buffer, canvas, ANSI color helpers,\n * and gradient generation.\n *\n * @example\n * ```ts\n * import { Canvas, parseHex } from \"@bettertui/core\"\n *\n * const canvas = new Canvas(40, 20)\n * canvas.fill(parseHex(\"#1a1a2e\"))\n * canvas.drawRect(5, 2, 10, 6, { r: 255, g: 64, b: 0 })\n * process.stdout.write(canvas.render())\n * ```\n */\n\n// ── Color types ───────────────────────────────────────────────────────────────\n\nexport interface RGB {\n r: number;\n g: number;\n b: number;\n}\n\nexport interface RGBA extends RGB {\n a: number;\n}\n\n/** Parse a CSS hex color string (`#rgb`, `#rrggbb`, `#rrggbbaa`) to RGBA. */\nexport function parseHex(hex: string): RGBA {\n const h = hex.replace(\"#\", \"\");\n const p = (s: string) => Number.parseInt(s, 16) || 0;\n if (h.length === 3) {\n const r = h[0] ?? \"0\";\n const g = h[1] ?? \"0\";\n const b = h[2] ?? \"0\";\n return { r: p(r + r), g: p(g + g), b: p(b + b), a: 255 };\n }\n if (h.length === 6) {\n return { r: p(h.slice(0, 2)), g: p(h.slice(2, 4)), b: p(h.slice(4, 6)), a: 255 };\n }\n if (h.length === 8) {\n return {\n r: p(h.slice(0, 2)),\n g: p(h.slice(2, 4)),\n b: p(h.slice(4, 6)),\n a: p(h.slice(6, 8)),\n };\n }\n return { r: 0, g: 0, b: 0, a: 255 };\n}\n\n/** Convert RGB to a 24-bit ANSI truecolor foreground escape sequence. */\nexport function rgbFg(color: RGB): string {\n return `\\x1b[38;2;${color.r};${color.g};${color.b}m`;\n}\n\n/** Convert RGB to a 24-bit ANSI truecolor background escape sequence. */\nexport function rgbBg(color: RGB): string {\n return `\\x1b[48;2;${color.r};${color.g};${color.b}m`;\n}\n\n/** ANSI reset sequence. */\nexport const RESET = \"\\x1b[0m\";\n\n// ── PixelBuffer ───────────────────────────────────────────────────────────────\n\n/** A mutable RGBA pixel buffer. Each pixel is 4 bytes: R, G, B, A. */\nexport class PixelBuffer {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8ClampedArray;\n\n constructor(width: number, height: number, fill?: RGBA) {\n this.width = width;\n this.height = height;\n this.data = new Uint8ClampedArray(width * height * 4);\n if (fill) this.fill(fill);\n }\n\n private _offset(x: number, y: number): number {\n return (y * this.width + x) * 4;\n }\n\n getPixel(x: number, y: number): RGBA {\n const o = this._offset(x, y);\n return {\n r: this.data[o] ?? 0,\n g: this.data[o + 1] ?? 0,\n b: this.data[o + 2] ?? 0,\n a: this.data[o + 3] ?? 255,\n };\n }\n\n setPixel(x: number, y: number, color: RGB | RGBA): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n const o = this._offset(x, y);\n this.data[o] = color.r;\n this.data[o + 1] = color.g;\n this.data[o + 2] = color.b;\n this.data[o + 3] = \"a\" in color ? color.a : 255;\n }\n\n fill(color: RGB | RGBA): void {\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n this.setPixel(x, y, color);\n }\n }\n }\n\n /** Convert this pixel buffer to a Node.js Buffer containing raw RGB bytes. */\n toRgbBuffer(): Buffer {\n const out = Buffer.allocUnsafe(this.width * this.height * 3);\n let oi = 0;\n for (let i = 0; i < this.data.length; i += 4) {\n out[oi++] = this.data[i] ?? 0;\n out[oi++] = this.data[i + 1] ?? 0;\n out[oi++] = this.data[i + 2] ?? 0;\n }\n return out;\n }\n\n /** Convert this pixel buffer to a Node.js Buffer containing raw RGBA bytes. */\n toRgbaBuffer(): Buffer {\n return Buffer.from(this.data.buffer);\n }\n}\n\n// ── Canvas ────────────────────────────────────────────────────────────────────\n\n/**\n * A terminal \"canvas\" that renders RGBA pixels as Unicode half-block\n * characters (`▀`, `▄`), achieving 1×2 sub-cell pixel resolution.\n * Each character cell covers one column × 2 rows of pixels.\n *\n * @example\n * ```ts\n * const canvas = new Canvas(40, 20)\n * canvas.fill({ r: 0, g: 0, b: 0 })\n * canvas.setPixel(10, 5, { r: 255, g: 64, b: 0 })\n * process.stdout.write(canvas.render())\n * ```\n */\nexport class Canvas {\n readonly pixelWidth: number;\n readonly pixelHeight: number;\n private _buffer: PixelBuffer;\n\n /**\n * @param pixelWidth Width in pixels (each char column = 1 pixel wide).\n * @param pixelHeight Height in pixels (each char row = 2 pixels tall).\n */\n constructor(pixelWidth: number, pixelHeight: number) {\n this.pixelWidth = pixelWidth;\n // Ensure even height for ▀ / ▄ encoding\n this.pixelHeight = pixelHeight % 2 === 0 ? pixelHeight : pixelHeight + 1;\n this._buffer = new PixelBuffer(this.pixelWidth, this.pixelHeight);\n }\n\n get buffer(): PixelBuffer {\n return this._buffer;\n }\n\n setPixel(x: number, y: number, color: RGB | RGBA): void {\n this._buffer.setPixel(x, y, color);\n }\n\n getPixel(x: number, y: number): RGBA {\n return this._buffer.getPixel(x, y);\n }\n\n fill(color: RGB | RGBA): void {\n this._buffer.fill(color);\n }\n\n /**\n * Render the canvas to a string using upper-half block `▀` characters.\n * Each character encodes two pixel rows: foreground = top pixel, background = bottom pixel.\n */\n render(): string {\n let out = \"\";\n for (let y = 0; y < this.pixelHeight; y += 2) {\n for (let x = 0; x < this.pixelWidth; x++) {\n const top = this._buffer.getPixel(x, y);\n const bottom = this._buffer.getPixel(x, y + 1);\n out += `${rgbFg(top)}${rgbBg(bottom)}▀`;\n }\n out += `${RESET}\\n`;\n }\n return out;\n }\n\n /** Draw a filled rectangle. */\n drawRect(x: number, y: number, w: number, h: number, color: RGB | RGBA): void {\n for (let dy = 0; dy < h; dy++) {\n for (let dx = 0; dx < w; dx++) {\n this._buffer.setPixel(x + dx, y + dy, color);\n }\n }\n }\n\n /** Draw a 1-pixel-wide rectangle outline. */\n drawRectOutline(x: number, y: number, w: number, h: number, color: RGB | RGBA): void {\n for (let dx = 0; dx < w; dx++) {\n this._buffer.setPixel(x + dx, y, color);\n this._buffer.setPixel(x + dx, y + h - 1, color);\n }\n for (let dy = 1; dy < h - 1; dy++) {\n this._buffer.setPixel(x, y + dy, color);\n this._buffer.setPixel(x + w - 1, y + dy, color);\n }\n }\n\n /** Draw a line using Bresenham's algorithm. */\n drawLine(x0: number, y0: number, x1: number, y1: number, color: RGB | RGBA): void {\n const dx = Math.abs(x1 - x0);\n const dy = Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx - dy;\n let cx = x0;\n let cy = y0;\n\n while (true) {\n this._buffer.setPixel(cx, cy, color);\n if (cx === x1 && cy === y1) break;\n const e2 = 2 * err;\n if (e2 > -dy) {\n err -= dy;\n cx += sx;\n }\n if (e2 < dx) {\n err += dx;\n cy += sy;\n }\n }\n }\n\n /** Draw a filled or outline circle using midpoint circle algorithm. */\n drawCircle(cx: number, cy: number, radius: number, color: RGB | RGBA, filled = true): void {\n const r2 = radius * radius;\n for (let y = -radius; y <= radius; y++) {\n for (let x = -radius; x <= radius; x++) {\n const dist2 = x * x + y * y;\n if (filled ? dist2 <= r2 : Math.abs(dist2 - r2) <= radius) {\n this._buffer.setPixel(cx + x, cy + y, color);\n }\n }\n }\n }\n\n /** Build a PixelBuffer image suitable for passing to the Image widget. */\n toPixelBuffer(): PixelBuffer {\n return this._buffer;\n }\n}\n\n// ── Gradient helpers ──────────────────────────────────────────────────────────\n\n/** Generate a horizontal gradient between two RGB colors across `steps` stops. */\nexport function gradientH(from: RGB, to: RGB, steps: number): RGB[] {\n return Array.from({ length: steps }, (_, i) => {\n const t = steps <= 1 ? 0 : i / (steps - 1);\n return {\n r: Math.round(from.r + (to.r - from.r) * t),\n g: Math.round(from.g + (to.g - from.g) * t),\n b: Math.round(from.b + (to.b - from.b) * t),\n };\n });\n}\n","/**\n * Audio API stubs for BetterTUI.\n *\n * These provide the full TypeScript interface for audio so\n * that examples compile and run without crashing. Actual playback requires\n * the native audio engine which is not yet implemented.\n */\n\nimport { EventEmitter } from \"node:events\";\n\n// ── Type aliases ──────────────────────────────────────────────────────────────\n\nexport type AudioGroup = number;\n\n// ── Error class ───────────────────────────────────────────────────────────────\n\nexport type AudioStreamAction =\n | \"connect\"\n | \"read\"\n | \"decode\"\n | \"play\"\n | \"reconnect\"\n | \"stop\"\n | \"dispose\";\n\nexport interface AudioStreamErrorContext {\n action: AudioStreamAction;\n status?: number;\n errorCode?: number;\n attempt?: number;\n}\n\nexport class AudioStreamError extends Error {\n readonly context: AudioStreamErrorContext;\n\n constructor(message: string, context: AudioStreamErrorContext, cause?: unknown) {\n super(message, cause ? { cause } : undefined);\n this.name = \"AudioStreamError\";\n this.context = context;\n }\n}\n\n// ── Audio stream types ────────────────────────────────────────────────────────\n\nexport type AudioStreamState =\n | \"initializing\"\n | \"buffering\"\n | \"playing\"\n | \"reconnecting\"\n | \"ended\"\n | \"errored\"\n | \"disposed\"\n | \"idle\";\n\nexport interface AudioStreamStats {\n state: AudioStreamState;\n sampleRate: number;\n channels: number;\n bufferedFrames: number;\n capacityFrames: number;\n bufferedDurationMs: number;\n bytesReceived: bigint;\n framesDecoded: bigint;\n framesPlayed: bigint;\n underruns: number;\n reconnectAttempts: number;\n}\n\nexport type AudioStreamMetadataFormat = \"icy\" | string;\n\nexport interface AudioStreamMetadata {\n readonly format: AudioStreamMetadataFormat;\n readonly headers: Readonly<Record<string, string>>;\n readonly fields: Readonly<Record<string, string>>;\n}\n\nexport interface AudioStreamReconnectEvent {\n attempt: number;\n delayMs: number;\n error: AudioStreamError;\n}\n\nexport interface AudioStreamUrlOptions {\n format?: \"mp3\" | \"flac\" | string;\n signal?: AbortSignal;\n volume?: number;\n pan?: number;\n groupId?: number;\n buffer?: { capacityMs?: number; startupMs?: number; resumeMs?: number };\n reconnect?: {\n maxRetries?: number;\n retryOnEnd?: boolean;\n initialDelayMs?: number;\n maxDelayMs?: number;\n backoffFactor?: number;\n };\n}\n\nexport class AudioStream<M = AudioStreamMetadata> extends EventEmitter {\n private _state: AudioStreamState = \"disposed\";\n\n get state(): AudioStreamState {\n return this._state;\n }\n\n getStats(): AudioStreamStats {\n return {\n state: this._state,\n sampleRate: 0,\n channels: 0,\n bufferedFrames: 0,\n capacityFrames: 0,\n bufferedDurationMs: 0,\n bytesReceived: 0n,\n framesDecoded: 0n,\n framesPlayed: 0n,\n underruns: 0,\n reconnectAttempts: 0,\n };\n }\n\n getMetadata(): M | null {\n return null;\n }\n\n setVolume(_volume: number): boolean {\n return false;\n }\n\n setPan(_pan: number): boolean {\n return false;\n }\n\n setGroup(_groupId: number): boolean {\n return false;\n }\n\n dispose(): void {\n this._state = \"disposed\";\n this.emit(\"disposed\");\n this.removeAllListeners();\n }\n}\n\n// ── Native audio types ────────────────────────────────────────────────────────\n\nexport interface AudioPlaybackDevice {\n name: string;\n id: string;\n isDefault: boolean;\n}\n\nexport interface AudioSound {\n id: string;\n duration: number;\n}\n\nexport interface AudioVoice {\n id: string;\n sound: AudioSound;\n}\n\nexport interface AudioSetupOptions {\n autoStart?: boolean;\n sampleRate?: number;\n channels?: number;\n bufferSize?: number;\n}\n\nexport interface AudioStartOptions {\n deviceId?: string;\n}\n\nexport interface AudioPlayOptions {\n volume?: number;\n pan?: number;\n loop?: boolean;\n groupId?: number;\n}\n\nexport interface AudioStats {\n lastPeak: number;\n lastRms: number;\n framesProcessed: bigint;\n}\n\nexport interface AudioTapResult {\n framesRead: number;\n frames: Float32Array;\n}\n\n// ── Audio class ───────────────────────────────────────────────────────────────\n\nexport class Audio extends EventEmitter {\n readonly sampleRate: number;\n private _started = false;\n private _mixerStarted = false;\n private _disposed = false;\n\n private constructor(options: AudioSetupOptions = {}) {\n super();\n this.sampleRate = options.sampleRate ?? 48_000;\n }\n\n /** Factory — creates a new Audio instance. */\n static create(options: AudioSetupOptions = {}): Audio {\n return new Audio(options);\n }\n\n start(_options?: AudioStartOptions): boolean {\n // Native audio not available; report graceful failure\n return false;\n }\n\n startMixer(): boolean {\n if (this._disposed) return false;\n this._mixerStarted = true;\n return true;\n }\n\n stop(): boolean {\n this._started = false;\n this._mixerStarted = false;\n return true;\n }\n\n isStarted(): boolean {\n return this._started;\n }\n\n isMixerStarted(): boolean {\n return this._mixerStarted;\n }\n\n /**\n * Create an audio group. Returns the group id (a small integer starting at 1).\n */\n private _groupCounter = 0;\n\n group(_name: string): AudioGroup {\n return ++this._groupCounter;\n }\n\n createGroup(_name: string): AudioGroup {\n return ++this._groupCounter;\n }\n\n setGroupVolume(_group: AudioGroup, _volume: number): boolean {\n return true;\n }\n\n setMasterVolume(_volume: number): boolean {\n return true;\n }\n\n enableTap(_bufferSize: number): void {}\n\n disableTap(): void {}\n\n readTapFrames(_frameCount: number, _channels: number): AudioTapResult | null {\n return null;\n }\n\n mixFrames(_frameCount: number, _channels: number): void {}\n\n getStats(): AudioStats | null {\n return null;\n }\n\n loadSound(_data: Uint8Array | ArrayBuffer): AudioSound | null {\n return null;\n }\n\n async loadSoundFile(_path: string): Promise<AudioSound | null> {\n return null;\n }\n\n unloadSound(_sound: AudioSound): boolean {\n return false;\n }\n\n play(_sound: AudioSound, _options?: AudioPlayOptions): AudioVoice | null {\n return null;\n }\n\n stopVoice(_voice: AudioVoice): boolean {\n return false;\n }\n\n setVoiceGroup(_voice: AudioVoice, _group: AudioGroup): boolean {\n return false;\n }\n\n async playStreamUrl(_url: string | URL, _options?: AudioStreamUrlOptions): Promise<AudioStream> {\n const stream = new AudioStream();\n // Immediately end the stream since audio is not available\n setImmediate(() => {\n stream.emit(\"ended\");\n });\n return stream;\n }\n\n dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._started = false;\n this._mixerStarted = false;\n this.emit(\"disposed\");\n this.removeAllListeners();\n }\n}\n","/**\n * ScrollBox — a scrollable container widget with a proportional scrollbar.\n *\n * Internal layout (flexDirection: \"row\"):\n * ├── viewport (flexGrow: 1, overflow: \"hidden\")\n * │ └── content (flexDirection: \"column\")\n * └── verticalScrollBar (width: 1)\n * ├── topSpacer (flexGrow: scrollTop)\n * ├── thumb (flexGrow: viewLines, min-height: 1)\n * └── bottomSpacer (flexGrow: maxScroll - scrollTop)\n *\n * The three-section flex approach means the thumb size and position are\n * always proportional to the content/viewport ratio without needing\n * the absolute track height.\n */\n\nimport type { KeyEvent } from \"../lib/keyHandler\";\nimport { RenderableEvents } from \"../lib/renderableEvents\";\nimport type { ColorInput } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\nexport interface ScrollBarOptions extends BoxOptions {\n orientation?: \"vertical\" | \"horizontal\";\n showArrows?: boolean;\n thumbColor?: ColorInput;\n trackColor?: ColorInput;\n trackOptions?: {\n foregroundColor?: ColorInput;\n backgroundColor?: ColorInput;\n };\n}\n\nexport class ScrollBar extends Box {\n private _orientation: \"vertical\" | \"horizontal\";\n private _showArrows: boolean;\n private _scrollPosition = 0;\n private _scrollSize = 0;\n private _viewSize = 0;\n\n private readonly _topSpacer: Box;\n private readonly _thumb: Box;\n private readonly _bottomSpacer: Box;\n\n constructor(renderer: CliRenderer, options: ScrollBarOptions = {}) {\n const trackColor = options.trackColor ?? options.backgroundColor ?? \"#1e2030\";\n const thumbColor = options.thumbColor ?? \"#565f89\";\n\n super(renderer, {\n ...options,\n backgroundColor: trackColor,\n flexDirection: options.orientation === \"horizontal\" ? \"row\" : \"column\",\n });\n\n this._orientation = options.orientation ?? \"vertical\";\n this._showArrows = options.showArrows !== false;\n\n this._topSpacer = new Box(renderer, {\n id: `${this._id}-top`,\n flexGrow: 0,\n flexBasis: 0,\n flexShrink: 0,\n });\n this.add(this._topSpacer);\n\n this._thumb = new Box(renderer, {\n id: `${this._id}-thumb`,\n flexGrow: 1,\n flexBasis: 0,\n flexShrink: 0,\n minHeight: 1,\n minWidth: 1,\n backgroundColor: thumbColor,\n });\n this.add(this._thumb);\n\n this._bottomSpacer = new Box(renderer, {\n id: `${this._id}-bottom`,\n flexGrow: 0,\n flexBasis: 0,\n flexShrink: 0,\n });\n this.add(this._bottomSpacer);\n }\n\n get showArrows(): boolean {\n return this._showArrows;\n }\n\n set showArrows(v: boolean) {\n this._showArrows = v;\n }\n\n get scrollPosition(): number {\n return this._scrollPosition;\n }\n\n set scrollPosition(v: number) {\n this._scrollPosition = Math.max(0, v);\n }\n\n get scrollSize(): number {\n return this._scrollSize;\n }\n\n set scrollSize(v: number) {\n this._scrollSize = v;\n }\n\n get viewSize(): number {\n return this._viewSize;\n }\n\n set viewSize(v: number) {\n this._viewSize = v;\n }\n\n /**\n * Update thumb position and size using proportional flex-grow weights.\n *\n * Total flex weight always equals `totalLines`, so the thumb proportion\n * (viewLines / totalLines) is constant regardless of scroll position.\n */\n updateScrollBar(scrollTop: number, totalLines: number, viewLines: number): void {\n if (totalLines <= viewLines || totalLines <= 0) {\n this._topSpacer.flexGrow = 0;\n this._thumb.flexGrow = 1;\n this._bottomSpacer.flexGrow = 0;\n return;\n }\n const maxScroll = totalLines - viewLines;\n const clamped = Math.max(0, Math.min(scrollTop, maxScroll));\n const below = Math.max(0, maxScroll - clamped);\n this._topSpacer.flexGrow = clamped;\n this._thumb.flexGrow = viewLines;\n this._bottomSpacer.flexGrow = below;\n }\n}\n\nexport interface ScrollBoxOptions extends BoxOptions {\n rootOptions?: BoxOptions;\n wrapperOptions?: BoxOptions;\n viewportOptions?: BoxOptions;\n contentOptions?: BoxOptions;\n scrollbarOptions?: ScrollBarOptions;\n verticalScrollbarOptions?: ScrollBarOptions;\n horizontalScrollbarOptions?: ScrollBarOptions;\n stickyScroll?: boolean;\n stickyStart?: \"bottom\" | \"top\" | \"left\" | \"right\";\n scrollX?: boolean;\n scrollY?: boolean;\n viewportCulling?: boolean;\n}\n\nlet _scrollBoxCounter = 0;\n\nexport class ScrollBox extends Box {\n public readonly content: Box;\n public readonly viewport: Box;\n public readonly verticalScrollBar: ScrollBar;\n public readonly horizontalScrollBar: ScrollBar;\n\n private _scrollTop = 0;\n private _scrollLeft = 0;\n private _stickyScroll: boolean;\n private _contentLines = 0;\n\n private _lastScrollTop = -1;\n private _lastContentLines = -1;\n private _lastViewLines = -1;\n\n private readonly _keyHandler: (key: KeyEvent) => void;\n private readonly _lifecyclePass: () => void;\n\n constructor(renderer: CliRenderer, options: ScrollBoxOptions = {}) {\n _scrollBoxCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `scrollbox-${_scrollBoxCounter}`,\n overflow: \"hidden\",\n focusable: true,\n flexDirection: \"row\",\n });\n\n this.viewport = new Box(renderer, {\n id: `${this._id}-viewport`,\n flexGrow: 1,\n flexShrink: 1,\n flexBasis: 0,\n minWidth: 0,\n minHeight: 0,\n overflow: \"hidden\",\n ...(options.viewportOptions ?? {}),\n });\n super.add(this.viewport);\n\n this.content = new Box(renderer, {\n id: `${this._id}-content`,\n flexDirection: \"column\",\n width: \"100%\",\n ...(options.contentOptions ?? {}),\n });\n this.viewport.add(this.content);\n\n this.verticalScrollBar = new ScrollBar(renderer, {\n id: `${this._id}-vscroll`,\n orientation: \"vertical\",\n width: 1,\n flexShrink: 0,\n visible: options.scrollY !== false,\n ...(options.verticalScrollbarOptions ?? options.scrollbarOptions ?? {}),\n });\n\n this.horizontalScrollBar = new ScrollBar(renderer, {\n id: `${this._id}-hscroll`,\n orientation: \"horizontal\",\n height: 1,\n flexShrink: 0,\n visible: options.scrollX === true,\n ...(options.horizontalScrollbarOptions ?? options.scrollbarOptions ?? {}),\n });\n\n if (options.scrollY !== false) {\n super.add(this.verticalScrollBar);\n }\n\n this._stickyScroll = options.stickyScroll ?? false;\n this._keyHandler = this._handleKey.bind(this);\n this._lifecyclePass = (): void => {\n if (!this._isDestroyed) this._updateScrollbar();\n };\n renderer.registerLifecyclePass(this._lifecyclePass);\n }\n\n get scrollTop(): number {\n return this._scrollTop;\n }\n\n set scrollTop(v: number) {\n this._scrollTop = Math.max(0, v);\n this._applyScroll();\n }\n\n get scrollLeft(): number {\n return this._scrollLeft;\n }\n\n set scrollLeft(v: number) {\n this._scrollLeft = Math.max(0, v);\n this._applyScroll();\n }\n\n get scrollHeight(): number {\n return this.verticalScrollBar.scrollSize;\n }\n\n get scrollWidth(): number {\n return this.horizontalScrollBar.scrollSize;\n }\n\n get stickyScroll(): boolean {\n return this._stickyScroll;\n }\n\n set stickyScroll(v: boolean) {\n this._stickyScroll = v;\n }\n\n override add(child: Box, index?: number): void {\n this.content.add(child, index);\n this._contentLines += child.getEstimatedHeight();\n this._updateScrollbar();\n }\n\n override remove(child: Box): void {\n this._contentLines = Math.max(0, this._contentLines - child.getEstimatedHeight());\n this.content.remove(child);\n this._updateScrollbar();\n }\n\n override getRenderable(id: string): Box | undefined {\n if (this._id === id) return this;\n return this.viewport.getRenderable(id) ?? super.getRenderable(id);\n }\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n this.emit(RenderableEvents.FOCUSED, this);\n this._applyStyle();\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n this._focused = false;\n this.emit(RenderableEvents.BLURRED, this);\n this._applyStyle();\n }\n\n scrollBy(delta: number, axis: \"x\" | \"y\" = \"y\"): void {\n if (axis === \"y\") {\n this.scrollTop += delta;\n } else {\n this.scrollLeft += delta;\n }\n }\n\n private _applyScroll(): void {\n // Use the engine's native scroll-offset mechanism on the viewport node.\n // The engine shifts all children of `viewport` by (-scrollX, -scrollY) during\n // render-tree building, and the viewport's overflow:hidden clip stops painting\n // outside its bounds. This avoids negative-margin hacks that were clamped to 0.\n this._renderer.setScrollOffset(this.viewport.nodeId, 0, this._scrollTop);\n this._updateScrollbar();\n }\n\n private _estimateViewLines(): number {\n const borderOverhead = this._options.border === true ? 2 : 0;\n return Math.max(1, this._renderer.viewportHeight - borderOverhead);\n }\n\n private _updateScrollbar(): void {\n const viewLines = this._estimateViewLines();\n if (\n this._lastScrollTop === this._scrollTop &&\n this._lastContentLines === this._contentLines &&\n this._lastViewLines === viewLines\n ) {\n return;\n }\n this._lastScrollTop = this._scrollTop;\n this._lastContentLines = this._contentLines;\n this._lastViewLines = viewLines;\n this.verticalScrollBar.updateScrollBar(this._scrollTop, this._contentLines, viewLines);\n }\n\n private _handleKey(key: KeyEvent): void {\n if (!this._focused || this._isDestroyed) return;\n\n if (key.name === \"up\" || (key.ctrl && key.name === \"p\")) {\n this.scrollBy(-1);\n } else if (key.name === \"down\" || (key.ctrl && key.name === \"n\")) {\n this.scrollBy(1);\n } else if (key.name === \"pageup\") {\n this.scrollBy(-10);\n } else if (key.name === \"pagedown\") {\n this.scrollBy(10);\n } else if (key.name === \"home\" || (key.ctrl && key.name === \"home\")) {\n this.scrollTop = 0;\n } else if (key.name === \"end\" || (key.ctrl && key.name === \"end\")) {\n this.scrollTop = Math.max(0, this._contentLines - this._estimateViewLines());\n }\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.unregisterLifecyclePass(this._lifecyclePass);\n this.viewport.destroyRecursively();\n this.verticalScrollBar.destroyRecursively();\n this.horizontalScrollBar.destroyRecursively();\n super.destroy();\n }\n}\n","/**\n * Textarea — a multi-line text editor widget.\n */\n\nimport type { KeyEvent } from \"../lib/keyHandler\";\nimport { InputEvents, RenderableEvents } from \"../lib/renderableEvents\";\nimport { type ColorInput, type RGBA, parseColor, rgbaToEngineColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\n/** Minimal extmarks controller stub for type compatibility. */\nexport interface ExtmarksController {\n create(opts: {\n start: number;\n end: number;\n virtual?: boolean;\n styleId?: number;\n data?: unknown;\n }): number;\n getAtOffset(\n offset: number,\n ): Array<{ start: number; end: number; styleId?: number; data?: unknown }>;\n getVirtual(): Array<{ start: number; end: number; styleId?: number; data?: unknown }>;\n destroy(): void;\n}\n\nexport class ExtmarksControllerStub implements ExtmarksController {\n create(_opts: {\n start: number;\n end: number;\n virtual?: boolean;\n styleId?: number;\n data?: unknown;\n }): number {\n return 0;\n }\n getAtOffset(\n _offset: number,\n ): Array<{ start: number; end: number; styleId?: number; data?: unknown }> {\n return [];\n }\n getVirtual(): Array<{ start: number; end: number; styleId?: number; data?: unknown }> {\n return [];\n }\n destroy(): void {}\n}\n\nexport interface TextareaOptions extends BoxOptions {\n initialValue?: string;\n placeholder?: string;\n placeholderColor?: ColorInput;\n textColor?: ColorInput;\n focusedTextColor?: ColorInput;\n cursorColor?: ColorInput;\n backgroundColor?: ColorInput;\n focusedBackgroundColor?: ColorInput;\n wrapMode?: \"none\" | \"char\" | \"word\";\n showCursor?: boolean;\n readonly?: boolean;\n selectionBg?: ColorInput;\n selectionFg?: ColorInput;\n syntaxStyle?: unknown;\n}\n\nlet _textareaCounter = 0;\n\nexport class Textarea extends Box {\n protected _text: string;\n protected _cursorLine = 0;\n protected _cursorCol = 0;\n private _placeholder: string;\n private _placeholderColor: RGBA;\n private _textColor: RGBA;\n private _focusedTextColor: RGBA;\n private _cursorColor: RGBA;\n private _focusedBgColor: RGBA | null = null;\n private _wrapMode: \"none\" | \"char\" | \"word\";\n private _showCursor: boolean;\n private _readonly: boolean;\n private _textNodeId: number;\n private _scrollOffset = 0;\n private readonly _keyHandler: (key: KeyEvent) => void;\n\n /** Extmarks controller stub — override or replace in subclasses for full functionality. */\n public extmarks: ExtmarksControllerStub = new ExtmarksControllerStub();\n\n /** Logical cursor position (line/col). */\n get logicalCursor(): { row: number; col: number } {\n return { row: this._cursorLine, col: this._cursorCol };\n }\n\n constructor(renderer: CliRenderer, options: TextareaOptions = {}) {\n _textareaCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `textarea-${_textareaCounter}`,\n focusable: true,\n });\n\n this._text = options.initialValue ?? \"\";\n this._placeholder = options.placeholder ?? \"\";\n this._placeholderColor = parseColor(options.placeholderColor ?? \"#666666\");\n this._textColor = parseColor(options.textColor ?? \"#ffffff\");\n this._focusedTextColor = parseColor(options.focusedTextColor ?? \"#ffffff\");\n this._cursorColor = parseColor(options.cursorColor ?? \"#ffff00\");\n this._wrapMode = options.wrapMode ?? \"char\";\n this._showCursor = options.showCursor !== false;\n this._readonly = options.readonly ?? false;\n\n if (options.focusedBackgroundColor) {\n this._focusedBgColor = parseColor(options.focusedBackgroundColor);\n }\n\n this._textNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._textNodeId);\n\n this._keyHandler = this._handleKey.bind(this);\n this._render();\n }\n\n get plainText(): string {\n return this._text;\n }\n\n set plainText(v: string) {\n this._text = v;\n this._render();\n }\n\n get cursorOffset(): number {\n // Linear offset from start\n const lines = this._text.split(\"\\n\");\n let offset = 0;\n for (let i = 0; i < this._cursorLine; i++) {\n offset += (lines[i]?.length ?? 0) + 1; // +1 for newline\n }\n return offset + this._cursorCol;\n }\n\n setText(text: string): void {\n this._text = text;\n this._cursorLine = 0;\n this._cursorCol = 0;\n this._render();\n }\n\n insertText(text: string): void {\n if (this._readonly) return;\n const lines = this._text.split(\"\\n\");\n const line = lines[this._cursorLine] ?? \"\";\n lines[this._cursorLine] = line.slice(0, this._cursorCol) + text + line.slice(this._cursorCol);\n this._text = lines.join(\"\\n\");\n this._cursorCol += text.length;\n this._render();\n this.emit(InputEvents.INPUT, this._text);\n }\n\n newLine(): boolean {\n if (this._readonly) return false;\n const lines = this._text.split(\"\\n\");\n const line = lines[this._cursorLine] ?? \"\";\n const before = line.slice(0, this._cursorCol);\n const after = line.slice(this._cursorCol);\n lines.splice(this._cursorLine, 1, before, after);\n this._text = lines.join(\"\\n\");\n this._cursorLine++;\n this._cursorCol = 0;\n this._render();\n this.emit(InputEvents.INPUT, this._text);\n return true;\n }\n\n submit(): boolean {\n const current = this._text;\n this.emit(InputEvents.CHANGE, current);\n this.emit(InputEvents.ENTER, current);\n return true;\n }\n\n // ── Focus ─────────────────────────────────────────────────────────────────────\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n if (this._focusedBgColor) {\n this._renderer.setNodeStyle(this._nodeId, {\n bg: rgbaToEngineColor(this._focusedBgColor),\n });\n }\n this._render();\n this.emit(RenderableEvents.FOCUSED, this);\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n const current = this._text;\n this._focused = false;\n if (this._focusedBgColor && this._backgroundColor) {\n this._renderer.setNodeStyle(this._nodeId, {\n bg: rgbaToEngineColor(this._backgroundColor),\n });\n }\n this._render();\n this.emit(InputEvents.CHANGE, current);\n this.emit(RenderableEvents.BLURRED, this);\n }\n\n // ── Key handling ──────────────────────────────────────────────────────────────\n\n protected _handleKey(key: KeyEvent): void {\n if (!this._focused || this._isDestroyed) return;\n\n const lines = this._text.split(\"\\n\");\n\n if (key.name === \"up\") {\n this._cursorLine = Math.max(0, this._cursorLine - 1);\n this._cursorCol = Math.min(this._cursorCol, lines[this._cursorLine]?.length ?? 0);\n this._render();\n return;\n }\n if (key.name === \"down\") {\n this._cursorLine = Math.min(lines.length - 1, this._cursorLine + 1);\n this._cursorCol = Math.min(this._cursorCol, lines[this._cursorLine]?.length ?? 0);\n this._render();\n return;\n }\n if (key.name === \"left\") {\n if (this._cursorCol > 0) {\n this._cursorCol--;\n } else if (this._cursorLine > 0) {\n this._cursorLine--;\n this._cursorCol = lines[this._cursorLine]?.length ?? 0;\n }\n this._render();\n return;\n }\n if (key.name === \"right\") {\n const lineLen = lines[this._cursorLine]?.length ?? 0;\n if (this._cursorCol < lineLen) {\n this._cursorCol++;\n } else if (this._cursorLine < lines.length - 1) {\n this._cursorLine++;\n this._cursorCol = 0;\n }\n this._render();\n return;\n }\n\n if (key.name === \"return\" || key.name === \"linefeed\") {\n if (!this._readonly) this.newLine();\n return;\n }\n\n if (key.name === \"backspace\") {\n if (this._readonly) return;\n if (this._cursorCol > 0) {\n const line = lines[this._cursorLine] ?? \"\";\n lines[this._cursorLine] = line.slice(0, this._cursorCol - 1) + line.slice(this._cursorCol);\n this._text = lines.join(\"\\n\");\n this._cursorCol--;\n this._render();\n this.emit(InputEvents.INPUT, this._text);\n } else if (this._cursorLine > 0) {\n const prevLine = lines[this._cursorLine - 1] ?? \"\";\n const curLine = lines[this._cursorLine] ?? \"\";\n const newCol = prevLine.length;\n lines.splice(this._cursorLine - 1, 2, prevLine + curLine);\n this._text = lines.join(\"\\n\");\n this._cursorLine--;\n this._cursorCol = newCol;\n this._render();\n this.emit(InputEvents.INPUT, this._text);\n }\n return;\n }\n\n // Regular character\n if (key.sequence && !key.ctrl && !key.alt && !key.meta && !this._readonly) {\n const char = key.sequence;\n if (char.length === 1 && char.charCodeAt(0) >= 32) {\n this.insertText(char);\n }\n }\n }\n\n protected _render(): void {\n if (this._isDestroyed) return;\n\n const lines = this._text.split(\"\\n\");\n const textColor = this._focused ? this._focusedTextColor : this._textColor;\n const tc = `${textColor.r};${textColor.g};${textColor.b}`;\n\n const rendered: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n if (this._focused && this._showCursor && i === this._cursorLine) {\n const before = line.slice(0, this._cursorCol);\n const cursorChar = line[this._cursorCol] ?? \" \";\n const after = line.slice(this._cursorCol + 1);\n const cc = `${this._cursorColor.r};${this._cursorColor.g};${this._cursorColor.b}`;\n rendered.push(\n `\\x1b[38;2;${tc}m${before}\\x1b[38;2;${cc}m\\x1b[7m${cursorChar}\\x1b[0m\\x1b[38;2;${tc}m${after}\\x1b[0m`,\n );\n } else {\n rendered.push(`\\x1b[38;2;${tc}m${line}\\x1b[0m`);\n }\n }\n\n this._renderer.setText(this._textNodeId, rendered.join(\"\\n\"));\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n try {\n this._renderer.removeNode(this._textNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n}\n\nexport { InputEvents };\n","/**\n * Slider — a horizontal or vertical slider widget.\n */\n\nimport type { KeyEvent } from \"../lib/keyHandler\";\nimport { RenderableEvents, SliderEvents } from \"../lib/renderableEvents\";\nimport { type ColorInput, type RGBA, parseColor } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box, type BoxOptions } from \"./Box\";\n\nexport interface SliderOptions extends BoxOptions {\n orientation?: \"horizontal\" | \"vertical\";\n min?: number;\n max?: number;\n value?: number;\n step?: number;\n viewPortSize?: number;\n trackColor?: ColorInput;\n thumbColor?: ColorInput;\n activeTrackColor?: ColorInput;\n onChange?: (value: number) => void;\n}\n\nexport type SliderRenderableOptions = SliderOptions;\n\nlet _sliderCounter = 0;\n\nexport class Slider extends Box {\n private _orientation: \"horizontal\" | \"vertical\";\n private _min: number;\n private _max: number;\n private _value: number;\n private _step: number;\n private _viewPortSize: number;\n private _trackColor: RGBA;\n private _thumbColor: RGBA;\n private _activeTrackColor: RGBA;\n private _onChange: ((value: number) => void) | undefined;\n private _contentNodeId: number;\n private readonly _keyHandler: (key: KeyEvent) => void;\n\n constructor(renderer: CliRenderer, options: SliderOptions = {}) {\n _sliderCounter++;\n super(renderer, {\n ...options,\n id: options.id ?? `slider-${_sliderCounter}`,\n focusable: true,\n });\n\n this._orientation = options.orientation ?? \"horizontal\";\n this._min = options.min ?? 0;\n this._max = options.max ?? 100;\n this._value = Math.max(this._min, Math.min(this._max, options.value ?? this._min));\n this._step = options.step ?? 1;\n this._viewPortSize = options.viewPortSize ?? 1;\n this._trackColor = parseColor(options.trackColor ?? \"#333333\");\n this._thumbColor = parseColor(options.thumbColor ?? \"#0088ff\");\n this._activeTrackColor = parseColor(options.activeTrackColor ?? \"#0055cc\");\n this._onChange = options.onChange;\n\n this._contentNodeId = renderer.createNode(\"Text\");\n renderer.appendChild(this._nodeId, this._contentNodeId);\n\n this._keyHandler = this._handleKey.bind(this);\n this._render();\n }\n\n get value(): number {\n return this._value;\n }\n\n set value(v: number) {\n const clamped = Math.max(this._min, Math.min(this._max, v));\n if (this._value !== clamped) {\n this._value = clamped;\n this._render();\n this._onChange?.(this._value);\n this.emit(SliderEvents.CHANGE, this._value);\n }\n }\n\n get min(): number {\n return this._min;\n }\n\n set min(v: number) {\n this._min = v;\n this._value = Math.max(v, this._value);\n this._render();\n }\n\n get max(): number {\n return this._max;\n }\n\n set max(v: number) {\n this._max = v;\n this._value = Math.min(v, this._value);\n this._render();\n }\n\n get step(): number {\n return this._step;\n }\n\n set step(v: number) {\n this._step = v;\n }\n\n get orientation(): \"horizontal\" | \"vertical\" {\n return this._orientation;\n }\n\n override focus(): void {\n if (this._isDestroyed || this._focused) return;\n this._focused = true;\n this._render();\n this.emit(RenderableEvents.FOCUSED, this);\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n this._renderer.keyHandler.onInternal(\"keypress\", this._keyHandler);\n }\n\n override blur(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n if (!this._focused) return;\n this._focused = false;\n this._render();\n this.emit(RenderableEvents.BLURRED, this);\n }\n\n private _handleKey(key: KeyEvent): void {\n if (!this._focused || this._isDestroyed) return;\n\n if (this._orientation === \"horizontal\") {\n if (key.name === \"left\") {\n this.value -= this._step;\n } else if (key.name === \"right\") {\n this.value += this._step;\n } else if (key.shift && key.name === \"left\") {\n this.value -= this._step * 10;\n } else if (key.shift && key.name === \"right\") {\n this.value += this._step * 10;\n }\n } else {\n if (key.name === \"up\") {\n this.value += this._step;\n } else if (key.name === \"down\") {\n this.value -= this._step;\n }\n }\n }\n\n private _render(): void {\n if (this._isDestroyed) return;\n\n const range = this._max - this._min;\n const progress = range === 0 ? 0 : (this._value - this._min) / range;\n\n if (this._orientation === \"horizontal\") {\n // Get width from options\n const width = typeof this._options.width === \"number\" ? this._options.width : 20;\n const trackWidth = Math.max(1, width - 2);\n const thumbPos = Math.round(progress * (trackWidth - 1));\n\n const tc = `${this._trackColor.r};${this._trackColor.g};${this._trackColor.b}`;\n const ac = `${this._activeTrackColor.r};${this._activeTrackColor.g};${this._activeTrackColor.b}`;\n const thumbC = `${this._thumbColor.r};${this._thumbColor.g};${this._thumbColor.b}`;\n\n let track = \"\";\n for (let i = 0; i < trackWidth; i++) {\n if (i === thumbPos) {\n track += `\\x1b[38;2;${thumbC}m█\\x1b[0m`;\n } else if (i < thumbPos) {\n track += `\\x1b[38;2;${ac}m─\\x1b[0m`;\n } else {\n track += `\\x1b[38;2;${tc}m─\\x1b[0m`;\n }\n }\n\n this._renderer.setText(this._contentNodeId, track);\n } else {\n // Vertical slider\n const height = typeof this._options.height === \"number\" ? this._options.height : 10;\n const trackHeight = Math.max(1, height - 2);\n const thumbPos = Math.round((1 - progress) * (trackHeight - 1));\n\n const tc = `${this._trackColor.r};${this._trackColor.g};${this._trackColor.b}`;\n const ac = `${this._activeTrackColor.r};${this._activeTrackColor.g};${this._activeTrackColor.b}`;\n const thumbC = `${this._thumbColor.r};${this._thumbColor.g};${this._thumbColor.b}`;\n\n const lines: string[] = [];\n for (let i = 0; i < trackHeight; i++) {\n if (i === thumbPos) {\n lines.push(`\\x1b[38;2;${thumbC}m█\\x1b[0m`);\n } else if (i > thumbPos) {\n lines.push(`\\x1b[38;2;${ac}m│\\x1b[0m`);\n } else {\n lines.push(`\\x1b[38;2;${tc}m│\\x1b[0m`);\n }\n }\n\n this._renderer.setText(this._contentNodeId, lines.join(\"\\n\"));\n }\n }\n\n override destroy(): void {\n if (this._isDestroyed) return;\n this._renderer.keyHandler.offInternal(\"keypress\", this._keyHandler);\n try {\n this._renderer.removeNode(this._contentNodeId);\n } catch {\n // ignore\n }\n super.destroy();\n }\n}\n\nexport { SliderEvents };\n","/**\n * Screen — full-terminal layout manager.\n *\n * Creates a full-viewport container with optional header/footer slots and a\n * body that always fills the remaining height. All layout is applied atomically\n * through Box constructor options to avoid the partial-setLayout reset issue.\n */\n\nimport { EventEmitter } from \"node:events\";\nimport { CliRenderEvents } from \"../lib/renderableEvents\";\nimport type { ColorInput } from \"../lib/rgba\";\nimport type { CliRenderer } from \"../platform/cliRenderer\";\nimport { Box } from \"./Box\";\nimport type { BorderSide, BorderStyleKind, BoxOptions } from \"./Box\";\n\n// ── Option interfaces ──────────────────────────────────────────────────────────\n\nexport interface CanvasHeaderOptions {\n id?: string;\n height?: number;\n backgroundColor?: ColorInput;\n border?: boolean | BorderSide[];\n borderStyle?: BorderStyleKind;\n borderColor?: ColorInput;\n title?: string;\n titleAlignment?: \"left\" | \"center\" | \"right\";\n alignItems?: BoxOptions[\"alignItems\"];\n justifyContent?: BoxOptions[\"justifyContent\"];\n padding?: number;\n paddingX?: number;\n paddingY?: number;\n paddingLeft?: number;\n paddingRight?: number;\n}\n\nexport type CanvasFooterOptions = CanvasHeaderOptions;\n\nexport interface CanvasBodyOptions {\n id?: string;\n backgroundColor?: ColorInput;\n flexDirection?: \"row\" | \"column\";\n alignItems?: BoxOptions[\"alignItems\"];\n justifyContent?: BoxOptions[\"justifyContent\"];\n overflow?: BoxOptions[\"overflow\"];\n gap?: number;\n padding?: number;\n paddingX?: number;\n paddingY?: number;\n}\n\nexport interface CanvasOptions {\n id?: string;\n backgroundColor?: ColorInput;\n header?: CanvasHeaderOptions;\n body?: CanvasBodyOptions;\n footer?: CanvasFooterOptions;\n}\n\n// ── Events ────────────────────────────────────────────────────────────────────\n\nexport interface ScreenResizeEvent {\n width: number;\n height: number;\n}\n\nexport const ScreenEvents = { RESIZE: \"resize\" } as const;\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\nfunction buildHeaderBoxOptions(opts: CanvasHeaderOptions): BoxOptions {\n return {\n id: opts.id,\n height: opts.height ?? 3,\n flexGrow: 0,\n flexShrink: 0,\n flexDirection: \"row\",\n alignItems: opts.alignItems ?? \"center\",\n justifyContent: opts.justifyContent ?? \"flex-start\",\n backgroundColor: opts.backgroundColor,\n border: opts.border,\n borderStyle: opts.borderStyle,\n borderColor: opts.borderColor,\n title: opts.title,\n titleAlignment: opts.titleAlignment,\n padding: opts.padding,\n paddingX: opts.paddingX,\n paddingY: opts.paddingY,\n paddingLeft: opts.paddingLeft,\n paddingRight: opts.paddingRight,\n };\n}\n\nfunction buildBodyBoxOptions(opts: CanvasBodyOptions): BoxOptions {\n return {\n id: opts.id,\n flexGrow: 1,\n flexShrink: 1,\n flexDirection: opts.flexDirection ?? \"column\",\n alignItems: opts.alignItems ?? \"stretch\",\n justifyContent: opts.justifyContent,\n overflow: opts.overflow,\n gap: opts.gap,\n backgroundColor: opts.backgroundColor,\n padding: opts.padding,\n paddingX: opts.paddingX,\n paddingY: opts.paddingY,\n position: \"relative\",\n };\n}\n\n// ── Screen ────────────────────────────────────────────────────────────────────\n\nexport class Screen extends EventEmitter {\n readonly container: Box;\n readonly header: Box | null;\n readonly body: Box;\n readonly footer: Box | null;\n\n private readonly _renderer: CliRenderer;\n private readonly _resizeHandler: (width: number, height: number) => void;\n\n constructor(renderer: CliRenderer, options: CanvasOptions = {}) {\n super();\n this._renderer = renderer;\n\n // Outer container — fills the full terminal viewport.\n this.container = new Box(renderer, {\n id: options.id,\n flexDirection: \"column\",\n width: \"100%\",\n height: \"100%\",\n backgroundColor: options.backgroundColor,\n });\n\n // Header slot (optional).\n this.header = options.header ? new Box(renderer, buildHeaderBoxOptions(options.header)) : null;\n\n // Body slot — always present; flexGrow: 1 ensures it fills remaining height.\n this.body = new Box(renderer, buildBodyBoxOptions(options.body ?? {}));\n\n // Footer slot (optional).\n this.footer = options.footer ? new Box(renderer, buildHeaderBoxOptions(options.footer)) : null;\n\n // Attach children in document order.\n if (this.header) this.container.add(this.header);\n this.container.add(this.body);\n if (this.footer) this.container.add(this.footer);\n\n // Mount the container into the renderer root.\n renderer.root.add(this.container);\n\n // Forward renderer resize events.\n this._resizeHandler = (width: number, height: number) => {\n this.emit(ScreenEvents.RESIZE, {\n width,\n height,\n } satisfies ScreenResizeEvent);\n };\n renderer.on(CliRenderEvents.RESIZE, this._resizeHandler);\n }\n\n // ── Accessors ────────────────────────────────────────────────────────────────\n\n get terminalWidth(): number {\n return this._renderer.terminalWidth;\n }\n\n get terminalHeight(): number {\n return this._renderer.terminalHeight;\n }\n\n // ── Layout helpers ────────────────────────────────────────────────────────────\n\n /** Re-apply body layout atomically. Always sets flexGrow: 1, flexShrink: 1. */\n setBodyLayout(opts: CanvasBodyOptions): void {\n this.body.setLayout(buildBodyBoxOptions(opts));\n }\n\n /** Re-apply header visual options (background / border color) after a theme change. */\n applyHeaderOptions(opts: Pick<CanvasHeaderOptions, \"backgroundColor\" | \"borderColor\">): void {\n if (!this.header) return;\n if (opts.backgroundColor !== undefined) this.header.backgroundColor = opts.backgroundColor;\n if (opts.borderColor !== undefined) this.header.borderColor = opts.borderColor;\n }\n\n /** Re-apply footer visual options (background / border color) after a theme change. */\n applyFooterOptions(opts: Pick<CanvasFooterOptions, \"backgroundColor\" | \"borderColor\">): void {\n if (!this.footer) return;\n if (opts.backgroundColor !== undefined) this.footer.backgroundColor = opts.backgroundColor;\n if (opts.borderColor !== undefined) this.footer.borderColor = opts.borderColor;\n }\n\n // ── Event helpers ─────────────────────────────────────────────────────────────\n\n onResize(cb: (e: ScreenResizeEvent) => void): this {\n this.on(ScreenEvents.RESIZE, cb);\n return this;\n }\n\n offResize(cb: (e: ScreenResizeEvent) => void): this {\n this.off(ScreenEvents.RESIZE, cb);\n return this;\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n destroy(): void {\n this._renderer.off(CliRenderEvents.RESIZE, this._resizeHandler);\n this.removeAllListeners();\n this.container.destroyRecursively();\n this._renderer.root.remove(this.container);\n }\n}\n","/**\n * Barrel export for all renderable classes.\n */\n\nexport { Box, Root, BORDER_CHARS } from \"./Box\";\nexport type { BoxOptions, BorderSide, BorderStyleKind } from \"./Box\";\n\nexport { Text } from \"./Text\";\nexport type { TextOptions } from \"./Text\";\n\nexport { Input } from \"./Input\";\nexport type { InputOptions, InputRenderableOptions } from \"./Input\";\n\nexport { Select } from \"./Select\";\nexport type {\n SelectOption,\n SelectOptions,\n SelectRenderableOptions,\n SelectAction,\n SelectKeyBinding,\n} from \"./Select\";\n\nexport { ScrollBox, ScrollBar } from \"./ScrollBox\";\nexport type { ScrollBoxOptions, ScrollBarOptions } from \"./ScrollBox\";\n\nexport { Textarea, ExtmarksControllerStub } from \"./Textarea\";\nexport type { TextareaOptions, ExtmarksController } from \"./Textarea\";\n\nexport { TabSelect } from \"./TabSelect\";\nexport type {\n TabOption,\n TabSelectOptions,\n TabSelectRenderableOptions,\n} from \"./TabSelect\";\n\nexport { Slider } from \"./Slider\";\nexport type { SliderOptions, SliderRenderableOptions } from \"./Slider\";\n\nexport { TextNode, RootTextNode } from \"./TextNode\";\n\nexport { Screen, ScreenEvents } from \"./Canvas\";\nexport type {\n CanvasOptions,\n CanvasHeaderOptions,\n CanvasFooterOptions,\n CanvasBodyOptions,\n ScreenResizeEvent,\n} from \"./Canvas\";\nexport type { TextNodeOptions } from \"./TextNode\";\n\nexport {\n ASCIIFont,\n FrameBuffer,\n Code,\n Diff,\n Markdown,\n TextTable,\n LineNumber,\n TimeToFirstDraw,\n} from \"./Stubs\";\nexport type {\n ASCIIFontKind,\n ASCIIFontOptions,\n FrameBufferOptions,\n FrameBufferLike,\n CodeOptions,\n DiffOptions,\n MarkdownOptions,\n TableColumn,\n TextTableOptions,\n TextTableColumnFitter,\n TextTableColumnWidthMode,\n TextTableContent,\n LineNumberOptions,\n TimeToFirstDrawOptions,\n} from \"./Stubs\";\n","// Curated re-export of shared types\nexport type {\n AlignItems,\n AlignSelf,\n BorderStyle,\n ColorValue,\n FlexDirection,\n Gap,\n Inset,\n JustifyContent,\n KeyEventSource,\n KeyEventType,\n LayoutConstraints,\n Margin,\n MouseButton,\n MouseEvent,\n Overflow,\n Padding,\n Position,\n Sizing,\n Style,\n Theme,\n ThemeColors,\n ThemeSpacing,\n} from \"@bettertui/shared\";\n\n// Geometry types (core-only: not needed by framework adapters)\nexport type { Point, Rect, Size } from \"./geometry.types\";\n\n// Command protocol, buffer, and tree operations\nexport * from \"./command\";\n\n// Reconciler (wraps tree ops with command emission)\nexport { createReconciler } from \"./reconciler\";\n\n// Command runtime (frame loop over CommandBuffer)\nexport { CommandRuntime } from \"./runtime\";\nexport type { CommandRuntimeOptions } from \"./runtime\";\n\nexport { Renderable } from \"./renderable\";\nexport type {\n WidgetContext,\n WidgetLifecycle,\n ImperativeContext,\n} from \"./renderable\";\n\n// Keymap, clock, and validation utilities (includes styled text, RGBA, events, etc.)\nexport * from \"./lib\";\n\n// Platform (native engine bridge, events, runtime)\nexport * from \"./platform\";\n\n// Testing utilities (explicit re-exports to avoid conflicts)\nexport {\n createTestRenderer,\n createTestRendererSync,\n createMockKeys,\n KeyCodes,\n createMockMouse,\n MouseButtons,\n createTestStdin,\n createTestStdout,\n TestReadStream,\n TestWriteStream,\n createSpy,\n createTerminalCapabilities,\n createMinimalTerminalCapabilities,\n createFullTerminalCapabilities,\n createKittyTerminalCapabilities,\n createITerm2TerminalCapabilities,\n createMockNativeKeymap,\n createTestKeymap,\n} from \"./testing\";\nexport type {\n TestRendererOptions,\n TestRenderer,\n MockInput,\n MockMouse,\n TestRendererSetup,\n TestKeyInput,\n MockKeysOptions,\n KeyModifiers,\n MousePosition,\n MouseModifiers,\n MouseEventType,\n MouseEventOptions,\n TestStdin,\n TestStdout,\n Spy,\n TerminalCapabilitiesOptions,\n TestBinding,\n} from \"./testing\";\n\n// Animation utilities: easing, Tween, Spring, lerp helpers\nexport * from \"./animations\";\n\n// Terminal graphics utilities: PixelBuffer, Canvas, color helpers\n// Note: Export specific items to avoid RGBA interface conflict (RGBA class exported from ./lib)\nexport {\n type RGB,\n parseHex,\n rgbFg,\n rgbBg,\n RESET,\n PixelBuffer,\n Canvas,\n gradientH,\n} from \"./graphics\";\n\n// In-core debug tooling (moved from the retired @bettertui/devtools package).\nexport * from \"./devtools\";\n\n// Audio API (stub implementations; native playback requires native engine)\nexport { Audio, AudioStream, AudioStreamError } from \"./audio\";\nexport type {\n AudioGroup,\n AudioStreamAction,\n AudioStreamErrorContext,\n AudioStreamState,\n AudioStreamStats,\n AudioStreamMetadata,\n AudioStreamMetadataFormat,\n AudioStreamReconnectEvent,\n AudioStreamUrlOptions,\n AudioPlaybackDevice,\n AudioSound,\n AudioVoice,\n AudioSetupOptions,\n AudioStartOptions,\n AudioPlayOptions,\n AudioStats,\n AudioTapResult,\n} from \"./audio\";\n\n// ── Renderable widgets (high-level CliRenderer-backed UI components) ──────────\n\nexport {\n // Core renderables (standard naming)\n Box,\n Root,\n Text,\n Input,\n Select,\n ScrollBox,\n ScrollBar,\n Textarea,\n ExtmarksControllerStub,\n TabSelect,\n Slider,\n TextNode,\n RootTextNode,\n Screen,\n ScreenEvents,\n ASCIIFont,\n FrameBuffer,\n Code,\n Diff,\n Markdown,\n TextTable,\n LineNumber,\n TimeToFirstDraw,\n} from \"./renderables\";\n\nexport type {\n BoxOptions,\n BorderSide,\n BorderStyleKind,\n TextOptions,\n InputOptions,\n InputRenderableOptions,\n SelectOption,\n SelectOptions,\n SelectRenderableOptions,\n ScrollBoxOptions,\n ScrollBarOptions,\n TextareaOptions,\n ExtmarksController,\n TabOption,\n TabSelectOptions,\n TabSelectRenderableOptions,\n SliderOptions,\n SliderRenderableOptions,\n TextNodeOptions,\n ASCIIFontKind,\n ASCIIFontOptions,\n FrameBufferOptions,\n FrameBufferLike,\n CodeOptions,\n DiffOptions,\n MarkdownOptions,\n TableColumn,\n TextTableOptions,\n TextTableColumnFitter,\n TextTableColumnWidthMode,\n TextTableContent,\n LineNumberOptions,\n TimeToFirstDrawOptions,\n CanvasOptions,\n CanvasHeaderOptions,\n CanvasFooterOptions,\n CanvasBodyOptions,\n ScreenResizeEvent,\n} from \"./renderables\";\n\n// ── Additional utility exports ─────────────────────────────────────────────────\n\nimport { measureFontText } from \"./lib/asciiFont\";\n\n/** Measure the display width and height of text. */\nexport function measureText(opts: { text: string; font?: string }): {\n width: number;\n height: number;\n} {\n const { text, font } = opts;\n if (font) {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require ESC character\n const stripped = text.replace(/\\x1b\\[[^m]*m/g, \"\");\n return measureFontText(stripped, font);\n }\n // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require ESC character\n const stripped = text.replace(/\\x1b\\[[^m]*m|\\x1b\\][^\\x07\\x1b]*[\\x07\\x1b\\\\]/g, \"\");\n return { width: stripped.length, height: 1 };\n}\n\nexport function decodePasteBytes(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"utf8\");\n}\n\nexport function resolveRenderLib(): { getArenaAllocatedBytes: () => number } {\n return { getArenaAllocatedBytes: () => 0 };\n}\n\n/** Strip ANSI escape sequences from a string. */\nexport function stripAnsiSequences(str: string): string {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require ESC character\n return str.replace(/\\x1b\\[[^m]*m|\\x1b\\][^\\x07\\x1b]*[\\x07\\x1b\\\\]/g, \"\");\n}\n\nexport type Selection = {\n start: { line: number; col: number };\n end: { line: number; col: number };\n text: string;\n getSelectedText(): string;\n isDragging: boolean;\n};\n\n/** HAST (Hypertext Abstract Syntax Tree) element type. */\nexport type HASTElement = {\n type: string;\n tagName?: string;\n value?: string;\n properties?: Record<string, unknown>;\n children?: HASTElement[];\n};\n\nexport class SyntaxStyle {\n fg?: string;\n bg?: string;\n bold?: boolean;\n italic?: boolean;\n private _styles: Map<string, Record<string, unknown>> = new Map();\n private _cache: Map<string, unknown> = new Map();\n\n constructor(opts?: {\n fg?: string;\n bg?: string;\n bold?: boolean;\n italic?: boolean;\n }) {\n Object.assign(this, opts ?? {});\n }\n\n /** Create a new SyntaxStyle instance. */\n static create(): SyntaxStyle {\n return new SyntaxStyle();\n }\n\n /** Create a SyntaxStyle from a record of style definitions. */\n static fromStyles(\n styles: Record<string, { fg?: unknown; bg?: unknown; bold?: boolean; italic?: boolean }>,\n ): SyntaxStyle {\n const s = new SyntaxStyle();\n for (const [name, style] of Object.entries(styles)) {\n s._styles.set(name, style as Record<string, unknown>);\n }\n return s;\n }\n\n /** Register a named style and return its numeric ID. */\n registerStyle(name: string, style: Record<string, unknown>): number {\n this._styles.set(name, style);\n return this._styles.size - 1;\n }\n\n /** Get the number of cached entries. */\n getCacheSize(): number {\n return this._cache.size;\n }\n\n /** Clear the style cache. */\n clearCache(): void {\n this._cache.clear();\n }\n\n destroy(): void {\n this._styles.clear();\n this._cache.clear();\n }\n}\n\n/** Convert a HAST tree to a StyledText string using the given SyntaxStyle. */\nexport function hastToStyledText(node: HASTElement, _style: SyntaxStyle): string {\n function traverse(n: HASTElement): string {\n if (n.type === \"text\") return n.value ?? \"\";\n if (n.children) return n.children.map(traverse).join(\"\");\n return \"\";\n }\n return traverse(node);\n}\n\nexport type RenderContext = {\n width: number;\n height: number;\n requestRender(): void;\n};\n\nexport type OptimizedBuffer = {\n width: number;\n height: number;\n buffers: {\n bg: Uint16Array;\n fg: Uint16Array;\n char: Uint32Array;\n attributes: Uint32Array;\n };\n setCell(x: number, y: number, char: string, fg?: unknown, bg?: unknown): void;\n drawText(\n text: string,\n x: number,\n y: number,\n fg?: unknown,\n bg?: unknown,\n attributes?: number,\n ): void;\n fillRect(x: number, y: number, w: number, h: number, color: unknown): void;\n};\n"],"mappings":";;;;;;;;;;AAEA,IAAa,gBAAb,MAA2B;CACzB,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