@xincli/opentui-core 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (476) hide show
  1. package/README.md +63 -0
  2. package/dev/keypress-debug-renderer.ts +148 -0
  3. package/dev/keypress-debug.ts +43 -0
  4. package/dev/print-env-vars.ts +32 -0
  5. package/dev/test-tmux-graphics-334.sh +68 -0
  6. package/dev/test-tmux-theme-queries.sh +151 -0
  7. package/dev/thai-debug-test.ts +68 -0
  8. package/dev/theme-mode.ts +290 -0
  9. package/docs/development.md +144 -0
  10. package/package.json +102 -0
  11. package/prebuilt/aarch64-android/libopentui.so +0 -0
  12. package/scripts/build-android.ts +226 -0
  13. package/scripts/build-native-termux.sh +525 -0
  14. package/scripts/build.ts +530 -0
  15. package/scripts/dist-test.ts +312 -0
  16. package/scripts/package-prebuilt.ts +110 -0
  17. package/scripts/publish.ts +60 -0
  18. package/scripts/test-node-hook.mjs +16 -0
  19. package/scripts/test-node.ts +241 -0
  20. package/scripts/vendor-deps.sh +73 -0
  21. package/src/NativeSpanFeed.ts +375 -0
  22. package/src/Renderable.ts +1878 -0
  23. package/src/__snapshots__/buffer.test.ts.snap +28 -0
  24. package/src/animation/Timeline.test.ts +2709 -0
  25. package/src/animation/Timeline.ts +598 -0
  26. package/src/ansi.ts +22 -0
  27. package/src/audio.ts +479 -0
  28. package/src/benchmark/attenuation-benchmark.ts +81 -0
  29. package/src/benchmark/audio-playback-benchmark.ts +344 -0
  30. package/src/benchmark/box-draw-benchmark.ts +1042 -0
  31. package/src/benchmark/colormatrix-benchmark.ts +123 -0
  32. package/src/benchmark/gain-benchmark.ts +80 -0
  33. package/src/benchmark/latest-all-bench-run.json +707 -0
  34. package/src/benchmark/latest-async-bench-run.json +336 -0
  35. package/src/benchmark/latest-default-bench-run.json +657 -0
  36. package/src/benchmark/latest-large-bench-run.json +707 -0
  37. package/src/benchmark/latest-quick-bench-run.json +207 -0
  38. package/src/benchmark/layout-benchmark.ts +2547 -0
  39. package/src/benchmark/markdown-benchmark.ts +1796 -0
  40. package/src/benchmark/native-span-feed-async-benchmark.ts +355 -0
  41. package/src/benchmark/native-span-feed-benchmark.md +56 -0
  42. package/src/benchmark/native-span-feed-benchmark.ts +596 -0
  43. package/src/benchmark/native-span-feed-compare.ts +280 -0
  44. package/src/benchmark/render-traversal-benchmark.ts +928 -0
  45. package/src/benchmark/text-buffer-render-benchmark.ts +874 -0
  46. package/src/benchmark/text-table-benchmark.ts +948 -0
  47. package/src/buffer.test.ts +292 -0
  48. package/src/buffer.ts +564 -0
  49. package/src/console.test.ts +629 -0
  50. package/src/console.ts +1253 -0
  51. package/src/edit-buffer.test.ts +1852 -0
  52. package/src/edit-buffer.ts +417 -0
  53. package/src/editor-view.test.ts +1056 -0
  54. package/src/editor-view.ts +290 -0
  55. package/src/index.ts +25 -0
  56. package/src/lib/KeyHandler.integration.test.ts +292 -0
  57. package/src/lib/KeyHandler.stopPropagation.test.ts +289 -0
  58. package/src/lib/KeyHandler.test.ts +662 -0
  59. package/src/lib/KeyHandler.ts +222 -0
  60. package/src/lib/RGBA.test.ts +60 -0
  61. package/src/lib/RGBA.ts +343 -0
  62. package/src/lib/ascii.font.ts +330 -0
  63. package/src/lib/border.test.ts +83 -0
  64. package/src/lib/border.ts +170 -0
  65. package/src/lib/bunfs.test.ts +27 -0
  66. package/src/lib/bunfs.ts +18 -0
  67. package/src/lib/clipboard.test.ts +63 -0
  68. package/src/lib/clipboard.ts +41 -0
  69. package/src/lib/clock.ts +35 -0
  70. package/src/lib/data-paths.test.ts +133 -0
  71. package/src/lib/data-paths.ts +109 -0
  72. package/src/lib/debounce.ts +106 -0
  73. package/src/lib/detect-links.test.ts +98 -0
  74. package/src/lib/detect-links.ts +56 -0
  75. package/src/lib/env.test.ts +228 -0
  76. package/src/lib/env.ts +209 -0
  77. package/src/lib/extmarks-history.ts +51 -0
  78. package/src/lib/extmarks-multiwidth.test.ts +324 -0
  79. package/src/lib/extmarks.test.ts +3547 -0
  80. package/src/lib/extmarks.ts +861 -0
  81. package/src/lib/fonts/block.json +405 -0
  82. package/src/lib/fonts/grid.json +265 -0
  83. package/src/lib/fonts/huge.json +741 -0
  84. package/src/lib/fonts/pallet.json +314 -0
  85. package/src/lib/fonts/shade.json +591 -0
  86. package/src/lib/fonts/slick.json +321 -0
  87. package/src/lib/fonts/tiny.json +69 -0
  88. package/src/lib/hast-styled-text.ts +59 -0
  89. package/src/lib/index.ts +22 -0
  90. package/src/lib/keybinding.internal.test.ts +342 -0
  91. package/src/lib/keybinding.internal.ts +182 -0
  92. package/src/lib/objects-in-viewport.test.ts +789 -0
  93. package/src/lib/objects-in-viewport.ts +153 -0
  94. package/src/lib/output.capture.ts +58 -0
  95. package/src/lib/parse.keypress-kitty.protocol.test.ts +347 -0
  96. package/src/lib/parse.keypress-kitty.test.ts +712 -0
  97. package/src/lib/parse.keypress-kitty.ts +470 -0
  98. package/src/lib/parse.keypress.test.ts +2020 -0
  99. package/src/lib/parse.keypress.ts +480 -0
  100. package/src/lib/parse.mouse.test.ts +552 -0
  101. package/src/lib/parse.mouse.ts +232 -0
  102. package/src/lib/paste.ts +18 -0
  103. package/src/lib/queue.ts +65 -0
  104. package/src/lib/render-geometry.ts +36 -0
  105. package/src/lib/renderable.validations.test.ts +87 -0
  106. package/src/lib/renderable.validations.ts +83 -0
  107. package/src/lib/scroll-acceleration.ts +98 -0
  108. package/src/lib/selection.ts +261 -0
  109. package/src/lib/singleton.ts +34 -0
  110. package/src/lib/stdin-parser.test.ts +2439 -0
  111. package/src/lib/stdin-parser.ts +2007 -0
  112. package/src/lib/styled-text.ts +178 -0
  113. package/src/lib/terminal-capability-detection.test.ts +226 -0
  114. package/src/lib/terminal-capability-detection.ts +98 -0
  115. package/src/lib/terminal-palette.test.ts +954 -0
  116. package/src/lib/terminal-palette.ts +441 -0
  117. package/src/lib/tree-sitter/assets/README.md +119 -0
  118. package/src/lib/tree-sitter/assets/javascript/highlights.scm +205 -0
  119. package/src/lib/tree-sitter/assets/javascript/tree-sitter-javascript.wasm +0 -0
  120. package/src/lib/tree-sitter/assets/markdown/highlights.scm +150 -0
  121. package/src/lib/tree-sitter/assets/markdown/injections.scm +27 -0
  122. package/src/lib/tree-sitter/assets/markdown/tree-sitter-markdown.wasm +0 -0
  123. package/src/lib/tree-sitter/assets/markdown_inline/highlights.scm +115 -0
  124. package/src/lib/tree-sitter/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  125. package/src/lib/tree-sitter/assets/typescript/highlights.scm +604 -0
  126. package/src/lib/tree-sitter/assets/typescript/tree-sitter-typescript.wasm +0 -0
  127. package/src/lib/tree-sitter/assets/update.ts +360 -0
  128. package/src/lib/tree-sitter/assets/zig/highlights.scm +284 -0
  129. package/src/lib/tree-sitter/assets/zig/tree-sitter-zig.wasm +0 -0
  130. package/src/lib/tree-sitter/assets.d.ts +9 -0
  131. package/src/lib/tree-sitter/cache.test.ts +291 -0
  132. package/src/lib/tree-sitter/client.test.ts +1434 -0
  133. package/src/lib/tree-sitter/client.ts +847 -0
  134. package/src/lib/tree-sitter/default-parsers.ts +133 -0
  135. package/src/lib/tree-sitter/download-utils.ts +148 -0
  136. package/src/lib/tree-sitter/index.ts +75 -0
  137. package/src/lib/tree-sitter/parser.worker.ts +1098 -0
  138. package/src/lib/tree-sitter/parsers-config.ts +81 -0
  139. package/src/lib/tree-sitter/resolve-ft.test.ts +55 -0
  140. package/src/lib/tree-sitter/resolve-ft.ts +189 -0
  141. package/src/lib/tree-sitter/types.ts +132 -0
  142. package/src/lib/tree-sitter/update-assets.ts +10 -0
  143. package/src/lib/tree-sitter-styled-text.test.ts +1253 -0
  144. package/src/lib/tree-sitter-styled-text.ts +314 -0
  145. package/src/lib/validate-dir-name.ts +55 -0
  146. package/src/lib/yoga.options.test.ts +628 -0
  147. package/src/lib/yoga.options.ts +346 -0
  148. package/src/native-event-worker-repro.test.ts +48 -0
  149. package/src/native-event-worker-repro.worker.ts +9 -0
  150. package/src/native-handle.test.ts +221 -0
  151. package/src/platform/ffi.test.ts +516 -0
  152. package/src/platform/ffi.ts +653 -0
  153. package/src/platform/runtime.test.ts +52 -0
  154. package/src/platform/runtime.ts +121 -0
  155. package/src/platform/test.ts +45 -0
  156. package/src/platform/worker-handler-cleanup.fixture.ts +12 -0
  157. package/src/platform/worker-onmessage-startup.fixture.ts +10 -0
  158. package/src/platform/worker-startup.fixture.ts +9 -0
  159. package/src/platform/worker.node-test.ts +153 -0
  160. package/src/platform/worker.ts +425 -0
  161. package/src/plugins/core-slot.ts +579 -0
  162. package/src/plugins/registry.ts +402 -0
  163. package/src/plugins/types.ts +46 -0
  164. package/src/post/effects.ts +948 -0
  165. package/src/post/filters.ts +512 -0
  166. package/src/post/matrices.ts +288 -0
  167. package/src/renderables/ASCIIFont.ts +219 -0
  168. package/src/renderables/Box.test.ts +474 -0
  169. package/src/renderables/Box.ts +353 -0
  170. package/src/renderables/Code.test.ts +2388 -0
  171. package/src/renderables/Code.ts +555 -0
  172. package/src/renderables/Diff.regression.test.ts +381 -0
  173. package/src/renderables/Diff.test.ts +3212 -0
  174. package/src/renderables/Diff.ts +1278 -0
  175. package/src/renderables/EditBufferRenderable.test.ts +288 -0
  176. package/src/renderables/EditBufferRenderable.ts +1152 -0
  177. package/src/renderables/FrameBuffer.ts +47 -0
  178. package/src/renderables/Input.test.ts +1310 -0
  179. package/src/renderables/Input.ts +273 -0
  180. package/src/renderables/LineNumberRenderable.ts +725 -0
  181. package/src/renderables/Markdown.ts +2144 -0
  182. package/src/renderables/ScrollBar.ts +423 -0
  183. package/src/renderables/ScrollBox.ts +903 -0
  184. package/src/renderables/Select.test.ts +1134 -0
  185. package/src/renderables/Select.ts +535 -0
  186. package/src/renderables/Slider.test.ts +456 -0
  187. package/src/renderables/Slider.ts +342 -0
  188. package/src/renderables/TabSelect.test.ts +238 -0
  189. package/src/renderables/TabSelect.ts +447 -0
  190. package/src/renderables/Text.selection-buffer.test.ts +118 -0
  191. package/src/renderables/Text.test.ts +2662 -0
  192. package/src/renderables/Text.ts +147 -0
  193. package/src/renderables/TextBufferRenderable.ts +504 -0
  194. package/src/renderables/TextNode.test.ts +1137 -0
  195. package/src/renderables/TextNode.ts +379 -0
  196. package/src/renderables/TextTable.test.ts +1411 -0
  197. package/src/renderables/TextTable.ts +1434 -0
  198. package/src/renderables/Textarea.ts +425 -0
  199. package/src/renderables/TimeToFirstDraw.ts +89 -0
  200. package/src/renderables/__snapshots__/Code.test.ts.snap +13 -0
  201. package/src/renderables/__snapshots__/Diff.test.ts.snap +785 -0
  202. package/src/renderables/__snapshots__/Text.test.ts.snap +421 -0
  203. package/src/renderables/__snapshots__/TextTable.test.ts.snap +215 -0
  204. package/src/renderables/__tests__/Code.test.ts +55 -0
  205. package/src/renderables/__tests__/LineNumberRenderable.scrollbox-simple.test.ts +144 -0
  206. package/src/renderables/__tests__/LineNumberRenderable.scrollbox.test.ts +827 -0
  207. package/src/renderables/__tests__/LineNumberRenderable.test.ts +1906 -0
  208. package/src/renderables/__tests__/LineNumberRenderable.wrapping.test.ts +85 -0
  209. package/src/renderables/__tests__/Markdown.code-colors.test.ts +288 -0
  210. package/src/renderables/__tests__/Markdown.test.ts +4175 -0
  211. package/src/renderables/__tests__/MultiRenderable.selection.test.ts +87 -0
  212. package/src/renderables/__tests__/Textarea.buffer.test.ts +683 -0
  213. package/src/renderables/__tests__/Textarea.destroyed-events.test.ts +675 -0
  214. package/src/renderables/__tests__/Textarea.editing.test.ts +2120 -0
  215. package/src/renderables/__tests__/Textarea.error-handling.test.ts +35 -0
  216. package/src/renderables/__tests__/Textarea.events.test.ts +738 -0
  217. package/src/renderables/__tests__/Textarea.highlights.test.ts +590 -0
  218. package/src/renderables/__tests__/Textarea.keybinding.test.ts +3275 -0
  219. package/src/renderables/__tests__/Textarea.paste.test.ts +357 -0
  220. package/src/renderables/__tests__/Textarea.rendering.test.ts +1927 -0
  221. package/src/renderables/__tests__/Textarea.scroll.test.ts +733 -0
  222. package/src/renderables/__tests__/Textarea.selection.test.ts +1589 -0
  223. package/src/renderables/__tests__/Textarea.stress.test.ts +670 -0
  224. package/src/renderables/__tests__/Textarea.undo-redo.test.ts +383 -0
  225. package/src/renderables/__tests__/Textarea.visual-lines.test.ts +310 -0
  226. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.code.test.ts.snap +221 -0
  227. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox-simple.test.ts.snap +89 -0
  228. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox.test.ts.snap +457 -0
  229. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.test.ts.snap +158 -0
  230. package/src/renderables/__tests__/__snapshots__/Textarea.rendering.test.ts.snap +387 -0
  231. package/src/renderables/__tests__/markdown-parser.test.ts +241 -0
  232. package/src/renderables/__tests__/renderable-test-utils.ts +60 -0
  233. package/src/renderables/composition/README.md +8 -0
  234. package/src/renderables/composition/VRenderable.ts +32 -0
  235. package/src/renderables/composition/constructs.ts +127 -0
  236. package/src/renderables/composition/vnode.ts +277 -0
  237. package/src/renderables/index.ts +23 -0
  238. package/src/renderables/markdown-parser.ts +79 -0
  239. package/src/renderer-theme-mode.ts +199 -0
  240. package/src/renderer.ts +4975 -0
  241. package/src/runtime-plugin-support-configure.ts +63 -0
  242. package/src/runtime-plugin-support.ts +13 -0
  243. package/src/runtime-plugin.ts +626 -0
  244. package/src/specs/terminal-startup.md +64 -0
  245. package/src/syntax-style.test.ts +841 -0
  246. package/src/syntax-style.ts +274 -0
  247. package/src/testing/README.md +219 -0
  248. package/src/testing/bun-test-node.ts +880 -0
  249. package/src/testing/capture-spans.test.ts +216 -0
  250. package/src/testing/integration.test.ts +276 -0
  251. package/src/testing/manual-clock.ts +117 -0
  252. package/src/testing/mock-keys.test.ts +1378 -0
  253. package/src/testing/mock-keys.ts +457 -0
  254. package/src/testing/mock-mouse.test.ts +218 -0
  255. package/src/testing/mock-mouse.ts +247 -0
  256. package/src/testing/mock-tree-sitter-client.ts +81 -0
  257. package/src/testing/spy.ts +13 -0
  258. package/src/testing/terminal-capabilities.ts +47 -0
  259. package/src/testing/test-recorder.test.ts +410 -0
  260. package/src/testing/test-recorder.ts +133 -0
  261. package/src/testing/test-renderer.ts +375 -0
  262. package/src/testing/test-renderer.wait.test.ts +278 -0
  263. package/src/testing/test-streams.ts +31 -0
  264. package/src/testing.ts +9 -0
  265. package/src/tests/__snapshots__/absolute-positioning.snapshot.test.ts.snap +481 -0
  266. package/src/tests/__snapshots__/renderable.snapshot.test.ts.snap +19 -0
  267. package/src/tests/__snapshots__/scrollbox.test.ts.snap +29 -0
  268. package/src/tests/absolute-positioning.snapshot.test.ts +638 -0
  269. package/src/tests/allocator-stats.test.ts +53 -0
  270. package/src/tests/audio.test.ts +303 -0
  271. package/src/tests/destroy-during-render.test.ts +200 -0
  272. package/src/tests/destroy-on-exit.fixture.ts +36 -0
  273. package/src/tests/destroy-on-exit.test.ts +62 -0
  274. package/src/tests/ffi-borrowed-pointer-callsites.test.ts +153 -0
  275. package/src/tests/hover-cursor.test.ts +98 -0
  276. package/src/tests/native-backed-measurement-lifecycle.test.ts +133 -0
  277. package/src/tests/native-backed-measurement-parity.test.ts +322 -0
  278. package/src/tests/native-span-feed-async.test.ts +173 -0
  279. package/src/tests/native-span-feed-close.test.ts +120 -0
  280. package/src/tests/native-span-feed-coverage.test.ts +227 -0
  281. package/src/tests/native-span-feed-edge-cases.test.ts +384 -0
  282. package/src/tests/native-span-feed-use-after-free.test.ts +45 -0
  283. package/src/tests/opacity.test.ts +123 -0
  284. package/src/tests/renderable.snapshot.test.ts +524 -0
  285. package/src/tests/renderable.test.ts +1851 -0
  286. package/src/tests/renderer.clock.test.ts +270 -0
  287. package/src/tests/renderer.console-startup.test.ts +2151 -0
  288. package/src/tests/renderer.control.test.ts +458 -0
  289. package/src/tests/renderer.core-slot-binding.test.ts +962 -0
  290. package/src/tests/renderer.cursor.test.ts +26 -0
  291. package/src/tests/renderer.custom-stdout.test.ts +1112 -0
  292. package/src/tests/renderer.destroy-during-render.test.ts +147 -0
  293. package/src/tests/renderer.focus-restore.test.ts +257 -0
  294. package/src/tests/renderer.focus.test.ts +329 -0
  295. package/src/tests/renderer.idle.test.ts +219 -0
  296. package/src/tests/renderer.input.test.ts +2615 -0
  297. package/src/tests/renderer.kitty-flags.test.ts +195 -0
  298. package/src/tests/renderer.lifecycle.test.ts +34 -0
  299. package/src/tests/renderer.mouse.test.ts +1315 -0
  300. package/src/tests/renderer.notifications.test.ts +27 -0
  301. package/src/tests/renderer.palette.test.ts +1199 -0
  302. package/src/tests/renderer.remote.test.ts +247 -0
  303. package/src/tests/renderer.render-stats.test.ts +146 -0
  304. package/src/tests/renderer.scrollback-surface.test.ts +474 -0
  305. package/src/tests/renderer.selection.test.ts +138 -0
  306. package/src/tests/renderer.slot-registry.test.ts +684 -0
  307. package/src/tests/renderer.tracker.test.ts +202 -0
  308. package/src/tests/renderer.useMouse.test.ts +83 -0
  309. package/src/tests/runtime-plugin-node-modules-cycle.fixture.ts +76 -0
  310. package/src/tests/runtime-plugin-node-modules-import-like-string.fixture.ts +48 -0
  311. package/src/tests/runtime-plugin-node-modules-mjs.fixture.ts +43 -0
  312. package/src/tests/runtime-plugin-node-modules-no-bare-rewrite.fixture.ts +67 -0
  313. package/src/tests/runtime-plugin-node-modules-package-type-cache.fixture.ts +72 -0
  314. package/src/tests/runtime-plugin-node-modules-runtime-specifier.fixture.ts +44 -0
  315. package/src/tests/runtime-plugin-node-modules-scoped-package-bare-rewrite.fixture.ts +85 -0
  316. package/src/tests/runtime-plugin-path-alias.fixture.ts +43 -0
  317. package/src/tests/runtime-plugin-resolve-roots.fixture.ts +65 -0
  318. package/src/tests/runtime-plugin-support-configure.fixture.ts +31 -0
  319. package/src/tests/runtime-plugin-support-late-addition.fixture.ts +17 -0
  320. package/src/tests/runtime-plugin-support.fixture.ts +11 -0
  321. package/src/tests/runtime-plugin-support.test.ts +54 -0
  322. package/src/tests/runtime-plugin-windows-file-url.fixture.ts +30 -0
  323. package/src/tests/runtime-plugin.fixture.ts +40 -0
  324. package/src/tests/runtime-plugin.test.ts +369 -0
  325. package/src/tests/scrollbox-culling-bug.test.ts +114 -0
  326. package/src/tests/scrollbox-hitgrid-resize.test.ts +136 -0
  327. package/src/tests/scrollbox-hitgrid.test.ts +909 -0
  328. package/src/tests/scrollbox.test.ts +1895 -0
  329. package/src/tests/wrap-resize-perf.test.ts +276 -0
  330. package/src/tests/yoga-api-coverage.test.ts +409 -0
  331. package/src/tests/yoga-callback-stress.test.ts +122 -0
  332. package/src/tests/yoga-ffi.test.ts +117 -0
  333. package/src/tests/yoga-setters.test.ts +921 -0
  334. package/src/tests/yoga-upstream/YGAlignBaselineTest.test.ts +124 -0
  335. package/src/tests/yoga-upstream/YGComputedBorderTest.test.ts +27 -0
  336. package/src/tests/yoga-upstream/YGComputedMarginTest.test.ts +27 -0
  337. package/src/tests/yoga-upstream/YGComputedPaddingTest.test.ts +27 -0
  338. package/src/tests/yoga-upstream/YGDirtiedTest.test.ts +157 -0
  339. package/src/tests/yoga-upstream/YGErrataTest.test.ts +40 -0
  340. package/src/tests/yoga-upstream/YGFlexBasisAuto.test.ts +23 -0
  341. package/src/tests/yoga-upstream/YGHasNewLayout.test.ts +81 -0
  342. package/src/tests/yoga-upstream/YGMeasureCacheTest.test.ts +31 -0
  343. package/src/tests/yoga-upstream/YGMeasureTest.test.ts +70 -0
  344. package/src/tests/yoga-upstream/generated/YGAbsolutePositionTest.test.ts +1864 -0
  345. package/src/tests/yoga-upstream/generated/YGAlignContentTest.test.ts +5829 -0
  346. package/src/tests/yoga-upstream/generated/YGAlignItemsTest.test.ts +2444 -0
  347. package/src/tests/yoga-upstream/generated/YGAlignSelfTest.test.ts +293 -0
  348. package/src/tests/yoga-upstream/generated/YGAndroidNewsFeed.test.ts +315 -0
  349. package/src/tests/yoga-upstream/generated/YGAspectRatioTest.test.ts +231 -0
  350. package/src/tests/yoga-upstream/generated/YGAutoTest.test.ts +347 -0
  351. package/src/tests/yoga-upstream/generated/YGBorderTest.test.ts +256 -0
  352. package/src/tests/yoga-upstream/generated/YGBoxSizingTest.test.ts +2747 -0
  353. package/src/tests/yoga-upstream/generated/YGDimensionTest.test.ts +129 -0
  354. package/src/tests/yoga-upstream/generated/YGDisplayContentsTest.test.ts +109 -0
  355. package/src/tests/yoga-upstream/generated/YGDisplayTest.test.ts +1097 -0
  356. package/src/tests/yoga-upstream/generated/YGFlexDirectionTest.test.ts +4562 -0
  357. package/src/tests/yoga-upstream/generated/YGFlexTest.test.ts +677 -0
  358. package/src/tests/yoga-upstream/generated/YGFlexWrapTest.test.ts +2071 -0
  359. package/src/tests/yoga-upstream/generated/YGGapTest.test.ts +3303 -0
  360. package/src/tests/yoga-upstream/generated/YGIntrinsicSizeTest.test.ts +582 -0
  361. package/src/tests/yoga-upstream/generated/YGJustifyContentTest.test.ts +2150 -0
  362. package/src/tests/yoga-upstream/generated/YGMarginTest.test.ts +1963 -0
  363. package/src/tests/yoga-upstream/generated/YGMinMaxDimensionTest.test.ts +1446 -0
  364. package/src/tests/yoga-upstream/generated/YGPaddingTest.test.ts +354 -0
  365. package/src/tests/yoga-upstream/generated/YGPercentageTest.test.ts +1760 -0
  366. package/src/tests/yoga-upstream/generated/YGRoundingTest.test.ts +1161 -0
  367. package/src/tests/yoga-upstream/generated/YGSizeOverflowTest.test.ts +207 -0
  368. package/src/tests/yoga-upstream/generated/YGStaticPositionTest.test.ts +6338 -0
  369. package/src/tests/yoga-upstream/tools/MeasureCounter.ts +54 -0
  370. package/src/tests/yoga-upstream/tools/utils.ts +81 -0
  371. package/src/text-buffer-view.test.ts +722 -0
  372. package/src/text-buffer-view.ts +193 -0
  373. package/src/text-buffer.test.ts +512 -0
  374. package/src/text-buffer.ts +250 -0
  375. package/src/types.ts +199 -0
  376. package/src/utils.ts +88 -0
  377. package/src/yoga.ts +1146 -0
  378. package/src/zig/ansi.zig +502 -0
  379. package/src/zig/audio.zig +1206 -0
  380. package/src/zig/bench/README.md +50 -0
  381. package/src/zig/bench/buffer-color-blending_bench.zig +350 -0
  382. package/src/zig/bench/buffer-draw-box_bench.zig +786 -0
  383. package/src/zig/bench/buffer-draw-text-buffer_bench.zig +894 -0
  384. package/src/zig/bench/edit-buffer_bench.zig +476 -0
  385. package/src/zig/bench/editor-view_bench.zig +169 -0
  386. package/src/zig/bench/native-span-feed_bench.zig +107 -0
  387. package/src/zig/bench/rope-markers_bench.zig +713 -0
  388. package/src/zig/bench/rope_bench.zig +514 -0
  389. package/src/zig/bench/styled-text_bench.zig +476 -0
  390. package/src/zig/bench/text-buffer-coords_bench.zig +362 -0
  391. package/src/zig/bench/text-buffer-view_bench.zig +459 -0
  392. package/src/zig/bench/text-chunk-graphemes_bench.zig +272 -0
  393. package/src/zig/bench/utf8_bench.zig +799 -0
  394. package/src/zig/bench-utils.zig +431 -0
  395. package/src/zig/bench.zig +223 -0
  396. package/src/zig/buffer-methods.zig +215 -0
  397. package/src/zig/buffer.zig +2515 -0
  398. package/src/zig/build.zig +700 -0
  399. package/src/zig/build.zig.zon +19 -0
  400. package/src/zig/edit-buffer.zig +900 -0
  401. package/src/zig/editor-view.zig +812 -0
  402. package/src/zig/event-bus.zig +28 -0
  403. package/src/zig/event-emitter.zig +65 -0
  404. package/src/zig/file-logger.zig +92 -0
  405. package/src/zig/grapheme.zig +838 -0
  406. package/src/zig/handles.zig +267 -0
  407. package/src/zig/lib.zig +2813 -0
  408. package/src/zig/link.zig +349 -0
  409. package/src/zig/logger.zig +43 -0
  410. package/src/zig/mem-registry.zig +126 -0
  411. package/src/zig/miniaudio_shim.c +21 -0
  412. package/src/zig/native-renderable.zig +112 -0
  413. package/src/zig/native-span-feed-bench-lib.zig +7 -0
  414. package/src/zig/native-span-feed.zig +747 -0
  415. package/src/zig/renderer-output.zig +677 -0
  416. package/src/zig/renderer.zig +2106 -0
  417. package/src/zig/rope.zig +1220 -0
  418. package/src/zig/split-scrollback.zig +88 -0
  419. package/src/zig/syntax-style.zig +174 -0
  420. package/src/zig/terminal.zig +1652 -0
  421. package/src/zig/test.zig +82 -0
  422. package/src/zig/tests/README.md +18 -0
  423. package/src/zig/tests/ansi_test.zig +18 -0
  424. package/src/zig/tests/audio_test.zig +439 -0
  425. package/src/zig/tests/buffer-methods_test.zig +1111 -0
  426. package/src/zig/tests/buffer_test.zig +2926 -0
  427. package/src/zig/tests/edit-buffer-history_test.zig +299 -0
  428. package/src/zig/tests/edit-buffer_test.zig +1688 -0
  429. package/src/zig/tests/editor-view_test.zig +3454 -0
  430. package/src/zig/tests/event-emitter_test.zig +249 -0
  431. package/src/zig/tests/grapheme_test.zig +1329 -0
  432. package/src/zig/tests/handles_test.zig +123 -0
  433. package/src/zig/tests/link_test.zig +220 -0
  434. package/src/zig/tests/mem-registry_test.zig +473 -0
  435. package/src/zig/tests/memory_leak_regression_test.zig +234 -0
  436. package/src/zig/tests/native-renderable_test.zig +16 -0
  437. package/src/zig/tests/native-span-feed_test.zig +1266 -0
  438. package/src/zig/tests/renderer_test.zig +2604 -0
  439. package/src/zig/tests/rope-nested_test.zig +712 -0
  440. package/src/zig/tests/rope_fuzz_test.zig +238 -0
  441. package/src/zig/tests/rope_test.zig +2362 -0
  442. package/src/zig/tests/segment-merge.test.zig +148 -0
  443. package/src/zig/tests/split-scrollback_test.zig +70 -0
  444. package/src/zig/tests/syntax-style_test.zig +558 -0
  445. package/src/zig/tests/terminal_test.zig +1489 -0
  446. package/src/zig/tests/test-renderer.zig +126 -0
  447. package/src/zig/tests/text-buffer-drawing_test.zig +3291 -0
  448. package/src/zig/tests/text-buffer-highlights_test.zig +706 -0
  449. package/src/zig/tests/text-buffer-iterators_test.zig +776 -0
  450. package/src/zig/tests/text-buffer-segment_test.zig +320 -0
  451. package/src/zig/tests/text-buffer-selection_test.zig +1056 -0
  452. package/src/zig/tests/text-buffer-selection_viewport_test.zig +358 -0
  453. package/src/zig/tests/text-buffer-view_test.zig +3672 -0
  454. package/src/zig/tests/text-buffer_test.zig +2191 -0
  455. package/src/zig/tests/unicode-width-map.zon +3909 -0
  456. package/src/zig/tests/utf8_no_zwj_test.zig +260 -0
  457. package/src/zig/tests/utf8_test.zig +4060 -0
  458. package/src/zig/tests/utf8_wcwidth_cursor_test.zig +267 -0
  459. package/src/zig/tests/utf8_wcwidth_test.zig +357 -0
  460. package/src/zig/tests/word-wrap-editing_test.zig +498 -0
  461. package/src/zig/tests/wrap-cache-perf_test.zig +113 -0
  462. package/src/zig/tests/yoga_test.zig +65 -0
  463. package/src/zig/text-buffer-iterators.zig +496 -0
  464. package/src/zig/text-buffer-segment.zig +403 -0
  465. package/src/zig/text-buffer-view.zig +1428 -0
  466. package/src/zig/text-buffer.zig +1272 -0
  467. package/src/zig/utf8.zig +1954 -0
  468. package/src/zig/utils.zig +12 -0
  469. package/src/zig/uucode-stub.zig +76 -0
  470. package/src/zig/vendor/miniaudio/miniaudio.h +93468 -0
  471. package/src/zig/yoga.zig +658 -0
  472. package/src/zig-structs.ts +381 -0
  473. package/src/zig.ts +5260 -0
  474. package/tsconfig.build.json +17 -0
  475. package/tsconfig.json +27 -0
  476. package/tsconfig.node-test.json +138 -0
package/src/console.ts ADDED
@@ -0,0 +1,1253 @@
1
+ import { EventEmitter } from "events"
2
+ import { Console } from "node:console"
3
+ import fs from "node:fs"
4
+ import path from "node:path"
5
+ import util from "node:util"
6
+ import type { CliRenderer, MouseEvent } from "./renderer.js"
7
+ import type { ColorInput } from "./lib/RGBA.js"
8
+ import { OptimizedBuffer } from "./buffer.js"
9
+ import { type Clock, SystemClock } from "./lib/clock.js"
10
+ import { Capture, CapturedWritableStream } from "./lib/output.capture.js"
11
+ import { parseColor, RGBA } from "./lib/RGBA.js"
12
+ import { singleton } from "./lib/singleton.js"
13
+ import { env, registerEnvVar } from "./lib/env.js"
14
+ import type { KeyEvent } from "./lib/KeyHandler.js"
15
+ import {
16
+ type KeyBinding as BaseKeyBinding,
17
+ mergeKeyBindings,
18
+ buildKeyBindingsMap,
19
+ getKeyBindingAction,
20
+ defaultKeyAliases,
21
+ mergeKeyAliases,
22
+ keyBindingToString,
23
+ } from "./lib/keybinding.internal.js"
24
+
25
+ type KeyAliasMap = Record<string, string>
26
+
27
+ interface CallerInfo {
28
+ functionName: string
29
+ fullPath: string
30
+ fileName: string
31
+ lineNumber: number
32
+ columnNumber: number
33
+ }
34
+
35
+ function getCallerInfo(): CallerInfo | null {
36
+ const err = new Error()
37
+ const stackLines = err.stack?.split("\n").slice(5) || []
38
+ if (!stackLines.length) return null
39
+
40
+ const callerLine = stackLines[0].trim()
41
+
42
+ const regex = /at\s+(?:([\w$.<>]+)\s+\()?((?:\/|[A-Za-z]:\\)[^:]+):(\d+):(\d+)\)?/
43
+ const match = callerLine.match(regex)
44
+
45
+ if (!match) return null
46
+
47
+ // Extract details from the match.
48
+ const functionName = match[1] || "<anonymous>"
49
+ const fullPath = match[2]
50
+ const fileName = fullPath.split(/[\\/]/).pop() || "<unknown>"
51
+ const lineNumber = parseInt(match[3], 10) || 0
52
+ const columnNumber = parseInt(match[4], 10) || 0
53
+
54
+ return { functionName, fullPath, fileName, lineNumber, columnNumber }
55
+ }
56
+
57
+ enum LogLevel {
58
+ LOG = "LOG",
59
+ INFO = "INFO",
60
+ WARN = "WARN",
61
+ ERROR = "ERROR",
62
+ DEBUG = "DEBUG",
63
+ }
64
+
65
+ export const capture = singleton("ConsoleCapture", () => new Capture())
66
+
67
+ registerEnvVar({
68
+ name: "OTUI_USE_CONSOLE",
69
+ description: "Whether to use the console. Will not capture console output if set to false.",
70
+ type: "boolean",
71
+ default: true,
72
+ })
73
+
74
+ registerEnvVar({
75
+ name: "SHOW_CONSOLE",
76
+ description: "Show the console at startup if set to true.",
77
+ type: "boolean",
78
+ default: false,
79
+ })
80
+
81
+ class TerminalConsoleCache extends EventEmitter {
82
+ private _cachedLogs: [Date, LogLevel, any[], CallerInfo | null][] = []
83
+ private readonly MAX_CACHE_SIZE = 1000
84
+ private _collectCallerInfo: boolean = false
85
+ private _cachingEnabled: boolean = true
86
+ private _originalConsole: typeof console | null = null
87
+
88
+ get cachedLogs(): [Date, LogLevel, any[], CallerInfo | null][] {
89
+ return this._cachedLogs
90
+ }
91
+
92
+ constructor() {
93
+ super()
94
+
95
+ // Note: Console activation will be handled by the renderer when needed
96
+ // Don't activate on import to avoid hiding console.log globally
97
+ }
98
+
99
+ public activate(): void {
100
+ if (!this._originalConsole) {
101
+ this._originalConsole = global.console
102
+ }
103
+ this.setupConsoleCapture()
104
+ this.overrideConsoleMethods()
105
+ }
106
+
107
+ private setupConsoleCapture(): void {
108
+ if (!env.OTUI_USE_CONSOLE) return
109
+
110
+ const mockStdout = new CapturedWritableStream("stdout", capture)
111
+ const mockStderr = new CapturedWritableStream("stderr", capture)
112
+
113
+ // TODO: The Console constructor doesn't return a full Console interface implementation,
114
+ // it only provides a subset of methods (log, info, warn, error, debug, etc.).
115
+ // TypeScript's Console interface requires all methods (assert, clear, count, etc.).
116
+ // Using 'as any' as a workaround since we override the methods we use immediately after.
117
+ global.console = new Console({
118
+ stdout: mockStdout,
119
+ stderr: mockStderr,
120
+ colorMode: true,
121
+ inspectOptions: {
122
+ compact: false,
123
+ breakLength: 80,
124
+ depth: 2,
125
+ },
126
+ }) as any
127
+ }
128
+
129
+ private overrideConsoleMethods(): void {
130
+ console.log = (...args: any[]) => {
131
+ this.appendToConsole(LogLevel.LOG, ...args)
132
+ }
133
+
134
+ console.info = (...args: any[]) => {
135
+ this.appendToConsole(LogLevel.INFO, ...args)
136
+ }
137
+
138
+ console.warn = (...args: any[]) => {
139
+ this.appendToConsole(LogLevel.WARN, ...args)
140
+ }
141
+
142
+ console.error = (...args: any[]) => {
143
+ this.appendToConsole(LogLevel.ERROR, ...args)
144
+ }
145
+
146
+ console.debug = (...args: any[]) => {
147
+ this.appendToConsole(LogLevel.DEBUG, ...args)
148
+ }
149
+
150
+ // React 19.2's reconciler calls console.timeStamp with a 6-arg Performance Tracks signature.
151
+ // The new Console instance from setupConsoleCapture lacks timeStamp, so provide a no-op
152
+ // unless the runtime already supplies one.
153
+ if (typeof console.timeStamp !== "function") {
154
+ console.timeStamp = () => {}
155
+ }
156
+ }
157
+
158
+ public setCollectCallerInfo(enabled: boolean): void {
159
+ this._collectCallerInfo = enabled
160
+ }
161
+
162
+ public clearConsole(): void {
163
+ this._cachedLogs = []
164
+ }
165
+
166
+ public setCachingEnabled(enabled: boolean): void {
167
+ this._cachingEnabled = enabled
168
+ }
169
+
170
+ public deactivate(): void {
171
+ this.restoreOriginalConsole()
172
+ }
173
+
174
+ private restoreOriginalConsole(): void {
175
+ if (this._originalConsole) {
176
+ global.console = this._originalConsole
177
+ }
178
+ }
179
+
180
+ public addLogEntry(level: LogLevel, ...args: any[]) {
181
+ const callerInfo = this._collectCallerInfo ? getCallerInfo() : null
182
+ const logEntry: [Date, LogLevel, any[], CallerInfo | null] = [new Date(), level, args, callerInfo]
183
+
184
+ if (this._cachingEnabled) {
185
+ if (this._cachedLogs.length >= this.MAX_CACHE_SIZE) {
186
+ this._cachedLogs.shift()
187
+ }
188
+ this._cachedLogs.push(logEntry)
189
+ }
190
+
191
+ return logEntry
192
+ }
193
+
194
+ private appendToConsole(level: LogLevel, ...args: any[]): void {
195
+ if (this._cachedLogs.length >= this.MAX_CACHE_SIZE) {
196
+ this._cachedLogs.shift()
197
+ }
198
+ const entry = this.addLogEntry(level, ...args)
199
+ this.emit("entry", entry)
200
+ }
201
+
202
+ public destroy(): void {
203
+ this.deactivate()
204
+ }
205
+ }
206
+
207
+ const terminalConsoleCache = singleton("TerminalConsoleCache", () => {
208
+ const terminalConsoleCache = new TerminalConsoleCache()
209
+ process.on("exit", () => {
210
+ terminalConsoleCache.destroy()
211
+ })
212
+ return terminalConsoleCache
213
+ })
214
+
215
+ export enum ConsolePosition {
216
+ TOP = "top",
217
+ BOTTOM = "bottom",
218
+ LEFT = "left",
219
+ RIGHT = "right",
220
+ }
221
+
222
+ interface ConsoleSelection {
223
+ startLine: number
224
+ startCol: number
225
+ endLine: number
226
+ endCol: number
227
+ }
228
+
229
+ export type ConsoleAction =
230
+ | "scroll-up"
231
+ | "scroll-down"
232
+ | "scroll-to-top"
233
+ | "scroll-to-bottom"
234
+ | "position-previous"
235
+ | "position-next"
236
+ | "size-increase"
237
+ | "size-decrease"
238
+ | "save-logs"
239
+ | "copy-selection"
240
+
241
+ export type ConsoleKeyBinding = BaseKeyBinding<ConsoleAction>
242
+
243
+ const defaultConsoleKeybindings: ConsoleKeyBinding[] = [
244
+ { name: "up", action: "scroll-up" },
245
+ { name: "down", action: "scroll-down" },
246
+ { name: "up", shift: true, action: "scroll-to-top" },
247
+ { name: "down", shift: true, action: "scroll-to-bottom" },
248
+ { name: "p", ctrl: true, action: "position-previous" },
249
+ { name: "o", ctrl: true, action: "position-next" },
250
+ { name: "+", action: "size-increase" },
251
+ { name: "=", shift: true, action: "size-increase" },
252
+ { name: "-", action: "size-decrease" },
253
+ { name: "s", ctrl: true, action: "save-logs" },
254
+ { name: "c", ctrl: true, shift: true, action: "copy-selection" },
255
+ ]
256
+
257
+ export interface ConsoleOptions {
258
+ position?: ConsolePosition
259
+ sizePercent?: number
260
+ zIndex?: number
261
+ colorInfo?: ColorInput
262
+ colorWarn?: ColorInput
263
+ colorError?: ColorInput
264
+ colorDebug?: ColorInput
265
+ colorDefault?: ColorInput
266
+ backgroundColor?: ColorInput
267
+ startInDebugMode?: boolean
268
+ title?: string
269
+ titleBarColor?: ColorInput
270
+ titleBarTextColor?: ColorInput
271
+ cursorColor?: ColorInput
272
+ maxStoredLogs?: number
273
+ maxDisplayLines?: number
274
+ onCopySelection?: (text: string) => void
275
+ keyBindings?: ConsoleKeyBinding[]
276
+ keyAliasMap?: KeyAliasMap
277
+ selectionColor?: ColorInput
278
+ copyButtonColor?: ColorInput
279
+ clock?: Clock
280
+ }
281
+
282
+ const DEFAULT_CONSOLE_OPTIONS: Required<
283
+ Omit<ConsoleOptions, "onCopySelection" | "keyBindings" | "keyAliasMap" | "clock">
284
+ > & {
285
+ onCopySelection?: (text: string) => void
286
+ keyBindings?: ConsoleKeyBinding[]
287
+ keyAliasMap?: KeyAliasMap
288
+ } = {
289
+ position: ConsolePosition.BOTTOM,
290
+ sizePercent: 30,
291
+ zIndex: Infinity,
292
+ colorInfo: "#00FFFF", // Cyan
293
+ colorWarn: "#FFFF00", // Yellow
294
+ colorError: "#FF0000", // Red
295
+ colorDebug: "#808080", // Gray
296
+ colorDefault: "#FFFFFF", // White
297
+ backgroundColor: RGBA.fromValues(0.1, 0.1, 0.1, 0.7),
298
+ startInDebugMode: false,
299
+ title: "Console",
300
+ titleBarColor: RGBA.fromValues(0.05, 0.05, 0.05, 0.7),
301
+ titleBarTextColor: "#FFFFFF",
302
+ cursorColor: "#00A0FF",
303
+ maxStoredLogs: 2000,
304
+ maxDisplayLines: 3000,
305
+ onCopySelection: undefined,
306
+ keyBindings: undefined,
307
+ keyAliasMap: undefined,
308
+ selectionColor: RGBA.fromValues(0.3, 0.5, 0.8, 0.5),
309
+ copyButtonColor: "#00A0FF",
310
+ }
311
+
312
+ const INDENT_WIDTH = 2
313
+
314
+ interface DisplayLine {
315
+ text: string
316
+ level: LogLevel
317
+ indent: boolean
318
+ }
319
+
320
+ export class TerminalConsole extends EventEmitter {
321
+ private isVisible: boolean = false
322
+ private isFocused: boolean = false
323
+ private renderer: CliRenderer
324
+ private keyHandler: (event: KeyEvent) => void
325
+ private options: Required<Omit<ConsoleOptions, "onCopySelection" | "keyBindings" | "keyAliasMap" | "clock">> & {
326
+ onCopySelection?: (text: string) => void
327
+ keyBindings?: ConsoleKeyBinding[]
328
+ keyAliasMap?: KeyAliasMap
329
+ }
330
+ private _debugModeEnabled: boolean = false
331
+
332
+ private frameBuffer: OptimizedBuffer | null = null
333
+ private consoleX: number = 0
334
+ private consoleY: number = 0
335
+ private consoleWidth: number = 0
336
+ private consoleHeight: number = 0
337
+ private scrollTopIndex: number = 0
338
+ private isScrolledToBottom: boolean = true
339
+ private currentLineIndex: number = 0
340
+ private _displayLines: DisplayLine[] = []
341
+ private _allLogEntries: [Date, LogLevel, any[], CallerInfo | null][] = []
342
+ private _needsFrameBufferUpdate: boolean = false
343
+ private _entryListener: (logEntry: [Date, LogLevel, any[], CallerInfo | null]) => void
344
+
345
+ private _selectionStart: { line: number; col: number } | null = null
346
+ private _selectionEnd: { line: number; col: number } | null = null
347
+ private _isDragging: boolean = false
348
+ private _copyButtonBounds: { x: number; y: number; width: number; height: number } = {
349
+ x: 0,
350
+ y: 0,
351
+ width: 0,
352
+ height: 0,
353
+ }
354
+ private _autoScrollInterval: ReturnType<Clock["setInterval"]> | null = null
355
+ private readonly clock: Clock
356
+
357
+ private _keyBindingsMap: Map<string, ConsoleAction>
358
+ private _keyAliasMap: KeyAliasMap
359
+ private _keyBindings: ConsoleKeyBinding[]
360
+ private _mergedKeyBindings: ConsoleKeyBinding[]
361
+ private _actionHandlers: Map<ConsoleAction, () => boolean>
362
+
363
+ private markNeedsRerender(): void {
364
+ this._needsFrameBufferUpdate = true
365
+ this.renderer.requestRender()
366
+ }
367
+
368
+ private getCopyButtonLabel(): string {
369
+ const copyBindings = this._mergedKeyBindings.filter((b) => b.action === "copy-selection")
370
+ const copyBinding = copyBindings[copyBindings.length - 1]
371
+ if (copyBinding) {
372
+ const shortcut = keyBindingToString(copyBinding)
373
+ return `[Copy (${shortcut})]`
374
+ }
375
+ return "[Copy]"
376
+ }
377
+
378
+ private _rgbaInfo: RGBA
379
+ private _rgbaWarn: RGBA
380
+ private _rgbaError: RGBA
381
+ private _rgbaDebug: RGBA
382
+ private _rgbaDefault: RGBA
383
+ private backgroundColor: RGBA
384
+ private _rgbaTitleBar: RGBA
385
+ private _rgbaTitleBarText: RGBA
386
+ private _title: string
387
+ private _rgbaCursor: RGBA
388
+ private _rgbaSelection: RGBA
389
+ private _rgbaCopyButton: RGBA
390
+
391
+ private _positions: ConsolePosition[] = [
392
+ ConsolePosition.TOP,
393
+ ConsolePosition.RIGHT,
394
+ ConsolePosition.BOTTOM,
395
+ ConsolePosition.LEFT,
396
+ ]
397
+
398
+ constructor(renderer: CliRenderer, options: ConsoleOptions = {}) {
399
+ super()
400
+ this.renderer = renderer
401
+ this.clock = options.clock ?? new SystemClock()
402
+ this.options = { ...DEFAULT_CONSOLE_OPTIONS, ...options }
403
+ this.keyHandler = this.handleKeyPress.bind(this)
404
+ this._debugModeEnabled = this.options.startInDebugMode
405
+ terminalConsoleCache.setCollectCallerInfo(this._debugModeEnabled)
406
+
407
+ this._rgbaInfo = parseColor(this.options.colorInfo)
408
+ this._rgbaWarn = parseColor(this.options.colorWarn)
409
+ this._rgbaError = parseColor(this.options.colorError)
410
+ this._rgbaDebug = parseColor(this.options.colorDebug)
411
+ this._rgbaDefault = parseColor(this.options.colorDefault)
412
+ this.backgroundColor = parseColor(this.options.backgroundColor)
413
+ this._rgbaTitleBar = parseColor(this.options.titleBarColor)
414
+ this._rgbaTitleBarText = parseColor(this.options.titleBarTextColor || this.options.colorDefault)
415
+ this._title = this.options.title
416
+ this._rgbaCursor = parseColor(this.options.cursorColor)
417
+ this._rgbaSelection = parseColor(this.options.selectionColor)
418
+ this._rgbaCopyButton = parseColor(this.options.copyButtonColor)
419
+
420
+ this._keyAliasMap = mergeKeyAliases(defaultKeyAliases, options.keyAliasMap || {})
421
+ this._keyBindings = options.keyBindings || []
422
+ this._mergedKeyBindings = mergeKeyBindings(defaultConsoleKeybindings, this._keyBindings)
423
+ this._keyBindingsMap = buildKeyBindingsMap(this._mergedKeyBindings, this._keyAliasMap)
424
+ this._actionHandlers = this.buildActionHandlers()
425
+
426
+ this._updateConsoleDimensions()
427
+ this._scrollToBottom(true)
428
+
429
+ this._entryListener = (logEntry: [Date, LogLevel, any[], CallerInfo | null]) => {
430
+ this._handleNewLog(logEntry)
431
+ }
432
+ terminalConsoleCache.on("entry", this._entryListener)
433
+
434
+ if (env.SHOW_CONSOLE) {
435
+ this.show()
436
+ }
437
+ }
438
+
439
+ private buildActionHandlers(): Map<ConsoleAction, () => boolean> {
440
+ return new Map([
441
+ ["scroll-up", () => this.scrollUp()],
442
+ ["scroll-down", () => this.scrollDown()],
443
+ ["scroll-to-top", () => this.scrollToTop()],
444
+ ["scroll-to-bottom", () => this.scrollToBottomAction()],
445
+ ["position-previous", () => this.positionPrevious()],
446
+ ["position-next", () => this.positionNext()],
447
+ ["size-increase", () => this.sizeIncrease()],
448
+ ["size-decrease", () => this.sizeDecrease()],
449
+ ["save-logs", () => this.saveLogsAction()],
450
+ ["copy-selection", () => this.triggerCopyAction()],
451
+ ])
452
+ }
453
+
454
+ public activate(): void {
455
+ terminalConsoleCache.activate()
456
+ }
457
+
458
+ public deactivate(): void {
459
+ terminalConsoleCache.deactivate()
460
+ }
461
+
462
+ // Handles a single new log entry *while the console is visible*
463
+ private _handleNewLog(logEntry: [Date, LogLevel, any[], CallerInfo | null]): void {
464
+ if (!this.isVisible) return
465
+
466
+ this._allLogEntries.push(logEntry)
467
+
468
+ if (this._allLogEntries.length > this.options.maxStoredLogs) {
469
+ this._allLogEntries.splice(0, this._allLogEntries.length - this.options.maxStoredLogs)
470
+ }
471
+
472
+ const newDisplayLines = this._processLogEntry(logEntry)
473
+ this._displayLines.push(...newDisplayLines)
474
+
475
+ if (this._displayLines.length > this.options.maxDisplayLines) {
476
+ this._displayLines.splice(0, this._displayLines.length - this.options.maxDisplayLines)
477
+ const linesRemoved = this._displayLines.length - this.options.maxDisplayLines
478
+ this.scrollTopIndex = Math.max(0, this.scrollTopIndex - linesRemoved)
479
+ }
480
+
481
+ if (this.isScrolledToBottom) {
482
+ this._scrollToBottom()
483
+ }
484
+ this.markNeedsRerender()
485
+ }
486
+
487
+ private _updateConsoleDimensions(termWidth?: number, termHeight?: number): void {
488
+ const width = termWidth ?? this.renderer.width
489
+ const height = termHeight ?? this.renderer.height
490
+ const sizePercent = this.options.sizePercent / 100
491
+
492
+ switch (this.options.position) {
493
+ case ConsolePosition.TOP:
494
+ this.consoleX = 0
495
+ this.consoleY = 0
496
+ this.consoleWidth = width
497
+ this.consoleHeight = Math.max(1, Math.floor(height * sizePercent))
498
+ break
499
+ case ConsolePosition.BOTTOM:
500
+ this.consoleHeight = Math.max(1, Math.floor(height * sizePercent))
501
+ this.consoleWidth = width
502
+ this.consoleX = 0
503
+ this.consoleY = height - this.consoleHeight
504
+ break
505
+ case ConsolePosition.LEFT:
506
+ this.consoleWidth = Math.max(1, Math.floor(width * sizePercent))
507
+ this.consoleHeight = height
508
+ this.consoleX = 0
509
+ this.consoleY = 0
510
+ break
511
+ case ConsolePosition.RIGHT:
512
+ this.consoleWidth = Math.max(1, Math.floor(width * sizePercent))
513
+ this.consoleHeight = height
514
+ this.consoleY = 0
515
+ this.consoleX = width - this.consoleWidth
516
+ break
517
+ }
518
+ this.currentLineIndex = Math.max(0, Math.min(this.currentLineIndex, this.consoleHeight - 1))
519
+ }
520
+
521
+ private handleKeyPress(event: KeyEvent): void {
522
+ if (event.name === "escape") {
523
+ this.blur()
524
+ return
525
+ }
526
+
527
+ const action = getKeyBindingAction(this._keyBindingsMap, event)
528
+
529
+ if (action) {
530
+ const handler = this._actionHandlers.get(action)
531
+ if (handler) {
532
+ handler()
533
+ return
534
+ }
535
+ }
536
+ }
537
+
538
+ private scrollUp(): boolean {
539
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
540
+
541
+ if (this.currentLineIndex > 0) {
542
+ this.currentLineIndex--
543
+ this.markNeedsRerender()
544
+ } else if (this.scrollTopIndex > 0) {
545
+ this.scrollTopIndex--
546
+ this.isScrolledToBottom = false
547
+ this.markNeedsRerender()
548
+ }
549
+ return true
550
+ }
551
+
552
+ private scrollDown(): boolean {
553
+ const displayLineCount = this._displayLines.length
554
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
555
+ const maxScrollTop = Math.max(0, displayLineCount - logAreaHeight)
556
+ const canCursorMoveDown =
557
+ this.currentLineIndex < logAreaHeight - 1 && this.scrollTopIndex + this.currentLineIndex < displayLineCount - 1
558
+
559
+ if (canCursorMoveDown) {
560
+ this.currentLineIndex++
561
+ this.markNeedsRerender()
562
+ } else if (this.scrollTopIndex < maxScrollTop) {
563
+ this.scrollTopIndex++
564
+ this.isScrolledToBottom = this.scrollTopIndex === maxScrollTop
565
+ this.markNeedsRerender()
566
+ }
567
+ return true
568
+ }
569
+
570
+ private scrollToTop(): boolean {
571
+ if (this.scrollTopIndex > 0 || this.currentLineIndex > 0) {
572
+ this.scrollTopIndex = 0
573
+ this.currentLineIndex = 0
574
+ this.isScrolledToBottom = this._displayLines.length <= Math.max(1, this.consoleHeight - 1)
575
+ this.markNeedsRerender()
576
+ }
577
+ return true
578
+ }
579
+
580
+ private scrollToBottomAction(): boolean {
581
+ const logAreaHeightForScroll = Math.max(1, this.consoleHeight - 1)
582
+ const maxScrollPossible = Math.max(0, this._displayLines.length - logAreaHeightForScroll)
583
+ if (this.scrollTopIndex < maxScrollPossible || !this.isScrolledToBottom) {
584
+ this._scrollToBottom(true)
585
+ this.markNeedsRerender()
586
+ }
587
+ return true
588
+ }
589
+
590
+ private positionPrevious(): boolean {
591
+ const currentPositionIndex = this._positions.indexOf(this.options.position)
592
+ const prevIndex = (currentPositionIndex - 1 + this._positions.length) % this._positions.length
593
+ this.options.position = this._positions[prevIndex]
594
+ this.resize(this.renderer.width, this.renderer.height)
595
+ return true
596
+ }
597
+
598
+ private positionNext(): boolean {
599
+ const currentPositionIndex = this._positions.indexOf(this.options.position)
600
+ const nextIndex = (currentPositionIndex + 1) % this._positions.length
601
+ this.options.position = this._positions[nextIndex]
602
+ this.resize(this.renderer.width, this.renderer.height)
603
+ return true
604
+ }
605
+
606
+ private sizeIncrease(): boolean {
607
+ this.options.sizePercent = Math.min(100, this.options.sizePercent + 5)
608
+ this.resize(this.renderer.width, this.renderer.height)
609
+ return true
610
+ }
611
+
612
+ private sizeDecrease(): boolean {
613
+ this.options.sizePercent = Math.max(10, this.options.sizePercent - 5)
614
+ this.resize(this.renderer.width, this.renderer.height)
615
+ return true
616
+ }
617
+
618
+ private saveLogsAction(): boolean {
619
+ this.saveLogsToFile()
620
+ return true
621
+ }
622
+
623
+ private triggerCopyAction(): boolean {
624
+ this.triggerCopy()
625
+ return true
626
+ }
627
+
628
+ private attachStdin(): void {
629
+ if (this.isFocused) return
630
+ this.renderer.keyInput.on("keypress", this.keyHandler)
631
+ this.isFocused = true
632
+ }
633
+
634
+ private detachStdin(): void {
635
+ if (!this.isFocused) return
636
+ this.renderer.keyInput.off("keypress", this.keyHandler)
637
+ this.isFocused = false
638
+ }
639
+
640
+ private formatTimestamp(date: Date): string {
641
+ return new Intl.DateTimeFormat("en-US", {
642
+ hour: "2-digit",
643
+ minute: "2-digit",
644
+ second: "2-digit",
645
+ hour12: false,
646
+ }).format(date)
647
+ }
648
+
649
+ private formatArguments(args: any[]): string {
650
+ return args
651
+ .map((arg) => {
652
+ if (arg instanceof Error) {
653
+ const errorProps = arg
654
+ return `Error: ${errorProps.message}\n` + (errorProps.stack ? `${errorProps.stack}\n` : "")
655
+ }
656
+ if (typeof arg === "object" && arg !== null) {
657
+ try {
658
+ return util.inspect(arg, { depth: 2 })
659
+ } catch (e) {
660
+ return String(arg)
661
+ }
662
+ }
663
+ try {
664
+ return util.inspect(arg, { depth: 2 })
665
+ } catch (e) {
666
+ return String(arg)
667
+ }
668
+ })
669
+ .join(" ")
670
+ }
671
+
672
+ public resize(width: number, height: number): void {
673
+ this._updateConsoleDimensions(width, height)
674
+
675
+ if (this.frameBuffer) {
676
+ this.frameBuffer.resize(this.consoleWidth, this.consoleHeight)
677
+
678
+ const displayLineCount = this._displayLines.length
679
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
680
+ const maxScrollTop = Math.max(0, displayLineCount - logAreaHeight)
681
+ this.scrollTopIndex = Math.min(this.scrollTopIndex, maxScrollTop)
682
+ this.isScrolledToBottom = this.scrollTopIndex === maxScrollTop
683
+ const visibleLineCount = Math.min(logAreaHeight, displayLineCount - this.scrollTopIndex)
684
+ this.currentLineIndex = Math.max(0, Math.min(this.currentLineIndex, visibleLineCount - 1))
685
+
686
+ if (this.isVisible) {
687
+ this.markNeedsRerender()
688
+ }
689
+ }
690
+ }
691
+
692
+ public clear(): void {
693
+ terminalConsoleCache.clearConsole()
694
+ this._allLogEntries = []
695
+ this._displayLines = []
696
+ this.markNeedsRerender()
697
+ }
698
+
699
+ public toggle(): void {
700
+ if (this.isVisible) {
701
+ if (this.isFocused) {
702
+ this.hide()
703
+ } else {
704
+ this.focus()
705
+ }
706
+ } else {
707
+ this.show()
708
+ }
709
+ if (!this.renderer.isRunning) {
710
+ this.renderer.requestRender()
711
+ }
712
+ }
713
+
714
+ public focus(): void {
715
+ this.attachStdin()
716
+ this._scrollToBottom(true)
717
+ this.markNeedsRerender()
718
+ }
719
+
720
+ public blur(): void {
721
+ this.detachStdin()
722
+ this.markNeedsRerender()
723
+ }
724
+
725
+ public show(): void {
726
+ if (!this.isVisible) {
727
+ this.isVisible = true
728
+ this._processCachedLogs()
729
+ terminalConsoleCache.setCachingEnabled(false)
730
+
731
+ if (!this.frameBuffer) {
732
+ this.frameBuffer = OptimizedBuffer.create(this.consoleWidth, this.consoleHeight, this.renderer.widthMethod, {
733
+ respectAlpha: this.backgroundColor.a < 1,
734
+ id: "console framebuffer",
735
+ })
736
+ }
737
+ const logCount = terminalConsoleCache.cachedLogs.length
738
+ const visibleLogLines = Math.min(this.consoleHeight, logCount)
739
+ this.currentLineIndex = Math.max(0, visibleLogLines - 1)
740
+ this.scrollTopIndex = 0
741
+ this._scrollToBottom(true)
742
+
743
+ this.focus()
744
+ this.markNeedsRerender()
745
+ }
746
+ }
747
+
748
+ public hide(): void {
749
+ if (this.isVisible) {
750
+ this.isVisible = false
751
+ this.blur()
752
+ terminalConsoleCache.setCachingEnabled(true)
753
+ }
754
+ }
755
+
756
+ public destroy(): void {
757
+ this.stopAutoScroll()
758
+ this.hide()
759
+ this.deactivate()
760
+ terminalConsoleCache.off("entry", this._entryListener)
761
+ }
762
+
763
+ public getCachedLogs(): string {
764
+ return terminalConsoleCache.cachedLogs
765
+ .map((logEntry) => logEntry[0].toISOString() + " " + logEntry.slice(1).join(" "))
766
+ .join("\n")
767
+ }
768
+
769
+ private updateFrameBuffer(): void {
770
+ if (!this.frameBuffer) return
771
+
772
+ this.frameBuffer.clear(this.backgroundColor)
773
+
774
+ const displayLines = this._displayLines
775
+ const displayLineCount = displayLines.length
776
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
777
+
778
+ // --- Draw Title Bar ---
779
+ this.frameBuffer.fillRect(0, 0, this.consoleWidth, 1, this._rgbaTitleBar)
780
+ const dynamicTitle = `${this._title}${this.isFocused ? " (Focused)" : ""}`
781
+ const titleX = Math.max(0, Math.floor((this.consoleWidth - dynamicTitle.length) / 2))
782
+ this.frameBuffer.drawText(dynamicTitle, titleX, 0, this._rgbaTitleBarText, this._rgbaTitleBar)
783
+
784
+ // --- Draw [Copy] Button ---
785
+ const copyLabel = this.getCopyButtonLabel()
786
+ const copyButtonX = this.consoleWidth - copyLabel.length - 1
787
+ if (copyButtonX >= 0) {
788
+ const copyButtonEnabled = this.hasSelection()
789
+ const disabledColor = RGBA.fromInts(100, 100, 100, 255)
790
+ const copyColor = copyButtonEnabled ? this._rgbaCopyButton : disabledColor
791
+ this.frameBuffer.drawText(copyLabel, copyButtonX, 0, copyColor, this._rgbaTitleBar)
792
+ this._copyButtonBounds = { x: copyButtonX, y: 0, width: copyLabel.length, height: 1 }
793
+ } else {
794
+ this._copyButtonBounds = { x: -1, y: -1, width: 0, height: 0 }
795
+ }
796
+
797
+ const startIndex = this.scrollTopIndex
798
+ const endIndex = Math.min(startIndex + logAreaHeight, displayLineCount)
799
+ const visibleDisplayLines = displayLines.slice(startIndex, endIndex)
800
+
801
+ let lineY = 1
802
+ for (let i = 0; i < visibleDisplayLines.length; i++) {
803
+ if (lineY >= this.consoleHeight) break
804
+
805
+ const displayLine = visibleDisplayLines[i]
806
+ const absoluteLineIndex = startIndex + i
807
+
808
+ let levelColor = this._rgbaDefault
809
+ switch (displayLine.level) {
810
+ case LogLevel.INFO:
811
+ levelColor = this._rgbaInfo
812
+ break
813
+ case LogLevel.WARN:
814
+ levelColor = this._rgbaWarn
815
+ break
816
+ case LogLevel.ERROR:
817
+ levelColor = this._rgbaError
818
+ break
819
+ case LogLevel.DEBUG:
820
+ levelColor = this._rgbaDebug
821
+ break
822
+ }
823
+
824
+ const linePrefix = displayLine.indent ? " ".repeat(INDENT_WIDTH) : ""
825
+ const textToDraw = displayLine.text
826
+ const textAvailableWidth = this.consoleWidth - 1 - (displayLine.indent ? INDENT_WIDTH : 0)
827
+ const showCursor = this.isFocused && lineY - 1 === this.currentLineIndex
828
+
829
+ if (showCursor) {
830
+ this.frameBuffer.drawText(">", 0, lineY, this._rgbaCursor, this.backgroundColor)
831
+ } else {
832
+ this.frameBuffer.drawText(" ", 0, lineY, this._rgbaDefault, this.backgroundColor)
833
+ }
834
+
835
+ const fullText = `${linePrefix}${textToDraw.substring(0, textAvailableWidth)}`
836
+ const selectionRange = this.getLineSelectionRange(absoluteLineIndex)
837
+
838
+ if (selectionRange) {
839
+ const adjustedStart = Math.max(0, selectionRange.start)
840
+ const adjustedEnd = Math.min(fullText.length, selectionRange.end)
841
+
842
+ if (adjustedStart > 0) {
843
+ this.frameBuffer.drawText(fullText.substring(0, adjustedStart), 1, lineY, levelColor)
844
+ }
845
+
846
+ if (adjustedStart < adjustedEnd) {
847
+ this.frameBuffer.fillRect(1 + adjustedStart, lineY, adjustedEnd - adjustedStart, 1, this._rgbaSelection)
848
+ this.frameBuffer.drawText(
849
+ fullText.substring(adjustedStart, adjustedEnd),
850
+ 1 + adjustedStart,
851
+ lineY,
852
+ levelColor,
853
+ this._rgbaSelection,
854
+ )
855
+ }
856
+
857
+ if (adjustedEnd < fullText.length) {
858
+ this.frameBuffer.drawText(fullText.substring(adjustedEnd), 1 + adjustedEnd, lineY, levelColor)
859
+ }
860
+ } else {
861
+ this.frameBuffer.drawText(fullText, 1, lineY, levelColor)
862
+ }
863
+
864
+ lineY++
865
+ }
866
+ }
867
+
868
+ public renderToBuffer(buffer: OptimizedBuffer): void {
869
+ if (!this.isVisible || !this.frameBuffer) return
870
+
871
+ if (this._needsFrameBufferUpdate) {
872
+ this.updateFrameBuffer()
873
+ this._needsFrameBufferUpdate = false
874
+ }
875
+
876
+ buffer.drawFrameBuffer(this.consoleX, this.consoleY, this.frameBuffer)
877
+ }
878
+
879
+ public setDebugMode(enabled: boolean): void {
880
+ this._debugModeEnabled = enabled
881
+ terminalConsoleCache.setCollectCallerInfo(enabled)
882
+ if (this.isVisible) {
883
+ this.markNeedsRerender()
884
+ }
885
+ }
886
+
887
+ public toggleDebugMode(): void {
888
+ this.setDebugMode(!this._debugModeEnabled)
889
+ }
890
+
891
+ public set keyBindings(bindings: ConsoleKeyBinding[]) {
892
+ this._keyBindings = bindings
893
+ this._mergedKeyBindings = mergeKeyBindings(defaultConsoleKeybindings, bindings)
894
+ this._keyBindingsMap = buildKeyBindingsMap(this._mergedKeyBindings, this._keyAliasMap)
895
+ this.markNeedsRerender()
896
+ }
897
+
898
+ public set keyAliasMap(aliases: KeyAliasMap) {
899
+ this._keyAliasMap = mergeKeyAliases(defaultKeyAliases, aliases)
900
+ this._mergedKeyBindings = mergeKeyBindings(defaultConsoleKeybindings, this._keyBindings)
901
+ this._keyBindingsMap = buildKeyBindingsMap(this._mergedKeyBindings, this._keyAliasMap)
902
+ this.markNeedsRerender()
903
+ }
904
+
905
+ public set onCopySelection(callback: ((text: string) => void) | undefined) {
906
+ this.options.onCopySelection = callback
907
+ }
908
+
909
+ public get onCopySelection(): ((text: string) => void) | undefined {
910
+ return this.options.onCopySelection
911
+ }
912
+
913
+ private _scrollToBottom(forceCursorToLastLine: boolean = false): void {
914
+ const displayLineCount = this._displayLines.length
915
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
916
+ const maxScrollTop = Math.max(0, displayLineCount - logAreaHeight)
917
+ this.scrollTopIndex = maxScrollTop
918
+ this.isScrolledToBottom = true
919
+
920
+ const visibleLineCount = Math.min(logAreaHeight, displayLineCount - this.scrollTopIndex)
921
+ if (forceCursorToLastLine || this.currentLineIndex >= visibleLineCount) {
922
+ this.currentLineIndex = Math.max(0, visibleLineCount - 1)
923
+ }
924
+ }
925
+
926
+ private _processLogEntry(logEntry: [Date, LogLevel, any[], CallerInfo | null]): DisplayLine[] {
927
+ const [date, level, args, callerInfo] = logEntry
928
+ const displayLines: DisplayLine[] = []
929
+
930
+ const timestamp = this.formatTimestamp(date)
931
+ const callerSource = callerInfo ? `${callerInfo.fileName}:${callerInfo.lineNumber}` : "unknown"
932
+ const prefix = `[${timestamp}] [${level}]` + (this._debugModeEnabled ? ` [${callerSource}]` : "") + " "
933
+
934
+ const formattedArgs = this.formatArguments(args)
935
+ const initialLines = formattedArgs.split("\n")
936
+
937
+ for (let i = 0; i < initialLines.length; i++) {
938
+ const lineText = initialLines[i]
939
+ const isFirstLineOfEntry = i === 0
940
+ const availableWidth = this.consoleWidth - 1 - (isFirstLineOfEntry ? 0 : INDENT_WIDTH)
941
+ const linePrefix = isFirstLineOfEntry ? prefix : " ".repeat(INDENT_WIDTH)
942
+ const textToWrap = isFirstLineOfEntry ? linePrefix + lineText : lineText
943
+
944
+ let currentPos = 0
945
+ while (currentPos < textToWrap.length || (isFirstLineOfEntry && currentPos === 0 && textToWrap.length === 0)) {
946
+ const segment = textToWrap.substring(currentPos, currentPos + availableWidth)
947
+ const isFirstSegmentOfLine = currentPos === 0
948
+
949
+ displayLines.push({
950
+ text: isFirstSegmentOfLine && !isFirstLineOfEntry ? linePrefix + segment : segment,
951
+ level: level,
952
+ indent: !isFirstLineOfEntry || !isFirstSegmentOfLine,
953
+ })
954
+
955
+ currentPos += availableWidth
956
+ if (isFirstLineOfEntry && currentPos === 0 && textToWrap.length === 0) break
957
+ }
958
+ }
959
+
960
+ return displayLines
961
+ }
962
+
963
+ private _processCachedLogs(): void {
964
+ const logsToProcess = [...terminalConsoleCache.cachedLogs]
965
+ terminalConsoleCache.clearConsole()
966
+
967
+ this._allLogEntries.push(...logsToProcess)
968
+
969
+ if (this._allLogEntries.length > this.options.maxStoredLogs) {
970
+ this._allLogEntries.splice(0, this._allLogEntries.length - this.options.maxStoredLogs)
971
+ }
972
+
973
+ for (const logEntry of logsToProcess) {
974
+ const processed = this._processLogEntry(logEntry)
975
+ this._displayLines.push(...processed)
976
+ }
977
+
978
+ if (this._displayLines.length > this.options.maxDisplayLines) {
979
+ this._displayLines.splice(0, this._displayLines.length - this.options.maxDisplayLines)
980
+ }
981
+ }
982
+
983
+ private hasSelection(): boolean {
984
+ if (this._selectionStart === null || this._selectionEnd === null) return false
985
+
986
+ return this._selectionStart.line !== this._selectionEnd.line || this._selectionStart.col !== this._selectionEnd.col
987
+ }
988
+
989
+ private normalizeSelection(): ConsoleSelection | null {
990
+ if (!this._selectionStart || !this._selectionEnd) return null
991
+
992
+ const start = this._selectionStart
993
+ const end = this._selectionEnd
994
+
995
+ const startBeforeEnd = start.line < end.line || (start.line === end.line && start.col <= end.col)
996
+
997
+ if (startBeforeEnd) {
998
+ return {
999
+ startLine: start.line,
1000
+ startCol: start.col,
1001
+ endLine: end.line,
1002
+ endCol: end.col,
1003
+ }
1004
+ } else {
1005
+ return {
1006
+ startLine: end.line,
1007
+ startCol: end.col,
1008
+ endLine: start.line,
1009
+ endCol: start.col,
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ private getSelectedText(): string {
1015
+ const selection = this.normalizeSelection()
1016
+ if (!selection) return ""
1017
+
1018
+ const lines: string[] = []
1019
+ for (let i = selection.startLine; i <= selection.endLine; i++) {
1020
+ if (i < 0 || i >= this._displayLines.length) continue
1021
+ const line = this._displayLines[i]
1022
+ const linePrefix = line.indent ? " ".repeat(INDENT_WIDTH) : ""
1023
+ const textAvailableWidth = this.consoleWidth - 1 - (line.indent ? INDENT_WIDTH : 0)
1024
+ const fullText = linePrefix + line.text.substring(0, textAvailableWidth)
1025
+ let text = fullText
1026
+
1027
+ if (i === selection.startLine && i === selection.endLine) {
1028
+ text = fullText.substring(selection.startCol, selection.endCol)
1029
+ } else if (i === selection.startLine) {
1030
+ text = fullText.substring(selection.startCol)
1031
+ } else if (i === selection.endLine) {
1032
+ text = fullText.substring(0, selection.endCol)
1033
+ }
1034
+
1035
+ lines.push(text)
1036
+ }
1037
+
1038
+ return lines.join("\n")
1039
+ }
1040
+
1041
+ private clearSelection(): void {
1042
+ this._selectionStart = null
1043
+ this._selectionEnd = null
1044
+ this._isDragging = false
1045
+ this.stopAutoScroll()
1046
+ }
1047
+
1048
+ private stopAutoScroll(): void {
1049
+ if (this._autoScrollInterval !== null) {
1050
+ this.clock.clearInterval(this._autoScrollInterval)
1051
+ this._autoScrollInterval = null
1052
+ }
1053
+ }
1054
+
1055
+ private startAutoScroll(direction: "up" | "down"): void {
1056
+ this.stopAutoScroll()
1057
+ this._autoScrollInterval = this.clock.setInterval(() => {
1058
+ if (direction === "up") {
1059
+ if (this.scrollTopIndex > 0) {
1060
+ this.scrollTopIndex--
1061
+ this.isScrolledToBottom = false
1062
+ if (this._selectionEnd) {
1063
+ this._selectionEnd = {
1064
+ line: this.scrollTopIndex,
1065
+ col: this._selectionEnd.col,
1066
+ }
1067
+ }
1068
+ this.markNeedsRerender()
1069
+ } else {
1070
+ this.stopAutoScroll()
1071
+ }
1072
+ } else {
1073
+ const displayLineCount = this._displayLines.length
1074
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
1075
+ const maxScrollTop = Math.max(0, displayLineCount - logAreaHeight)
1076
+ if (this.scrollTopIndex < maxScrollTop) {
1077
+ this.scrollTopIndex++
1078
+ this.isScrolledToBottom = this.scrollTopIndex === maxScrollTop
1079
+ if (this._selectionEnd) {
1080
+ const maxLine = this.scrollTopIndex + logAreaHeight - 1
1081
+ this._selectionEnd = {
1082
+ line: Math.min(maxLine, displayLineCount - 1),
1083
+ col: this._selectionEnd.col,
1084
+ }
1085
+ }
1086
+ this.markNeedsRerender()
1087
+ } else {
1088
+ this.stopAutoScroll()
1089
+ }
1090
+ }
1091
+ }, 50)
1092
+ }
1093
+
1094
+ private triggerCopy(): void {
1095
+ if (!this.hasSelection()) return
1096
+ const text = this.getSelectedText()
1097
+ if (text && this.options.onCopySelection) {
1098
+ try {
1099
+ this.options.onCopySelection(text)
1100
+ } catch {}
1101
+ this.clearSelection()
1102
+ this.markNeedsRerender()
1103
+ }
1104
+ }
1105
+
1106
+ private getLineSelectionRange(lineIndex: number): { start: number; end: number } | null {
1107
+ const selection = this.normalizeSelection()
1108
+ if (!selection) return null
1109
+
1110
+ if (lineIndex < selection.startLine || lineIndex > selection.endLine) {
1111
+ return null
1112
+ }
1113
+
1114
+ const line = this._displayLines[lineIndex]
1115
+ if (!line) return null
1116
+
1117
+ const linePrefix = line.indent ? " ".repeat(INDENT_WIDTH) : ""
1118
+ const textAvailableWidth = this.consoleWidth - 1 - (line.indent ? INDENT_WIDTH : 0)
1119
+ const fullTextLength = linePrefix.length + Math.min(line.text.length, textAvailableWidth)
1120
+
1121
+ let start = 0
1122
+ let end = fullTextLength
1123
+
1124
+ if (lineIndex === selection.startLine) {
1125
+ start = Math.max(0, selection.startCol)
1126
+ }
1127
+ if (lineIndex === selection.endLine) {
1128
+ end = Math.min(fullTextLength, selection.endCol)
1129
+ }
1130
+
1131
+ if (start >= end) return null
1132
+ return { start, end }
1133
+ }
1134
+
1135
+ public handleMouse(event: MouseEvent): boolean {
1136
+ if (!this.isVisible) return false
1137
+
1138
+ const localX = event.x - this.consoleX
1139
+ const localY = event.y - this.consoleY
1140
+
1141
+ if (localX < 0 || localX >= this.consoleWidth || localY < 0 || localY >= this.consoleHeight) {
1142
+ return false
1143
+ }
1144
+
1145
+ if (event.type === "scroll" && event.scroll) {
1146
+ if (event.scroll.direction === "up") {
1147
+ this.scrollUp()
1148
+ } else if (event.scroll.direction === "down") {
1149
+ this.scrollDown()
1150
+ }
1151
+ return true
1152
+ }
1153
+
1154
+ if (localY === 0) {
1155
+ if (
1156
+ event.type === "down" &&
1157
+ event.button === 0 &&
1158
+ localX >= this._copyButtonBounds.x &&
1159
+ localX < this._copyButtonBounds.x + this._copyButtonBounds.width
1160
+ ) {
1161
+ this.triggerCopy()
1162
+ return true
1163
+ }
1164
+ return true
1165
+ }
1166
+
1167
+ const lineIndex = this.scrollTopIndex + (localY - 1)
1168
+ const colIndex = Math.max(0, localX - 1)
1169
+
1170
+ if (event.type === "down" && event.button === 0) {
1171
+ this.clearSelection()
1172
+ this._selectionStart = { line: lineIndex, col: colIndex }
1173
+ this._selectionEnd = { line: lineIndex, col: colIndex }
1174
+ this._isDragging = true
1175
+ this.markNeedsRerender()
1176
+ return true
1177
+ }
1178
+
1179
+ if (event.type === "drag" && this._isDragging) {
1180
+ this._selectionEnd = { line: lineIndex, col: colIndex }
1181
+
1182
+ // Check if drag is at the edge and trigger auto-scroll
1183
+ const logAreaHeight = Math.max(1, this.consoleHeight - 1)
1184
+ const relativeY = localY - 1 // Subtract 1 for title bar
1185
+
1186
+ if (relativeY <= 0) {
1187
+ // Dragging at top edge
1188
+ this.startAutoScroll("up")
1189
+ } else if (relativeY >= logAreaHeight - 1) {
1190
+ // Dragging at bottom edge
1191
+ this.startAutoScroll("down")
1192
+ } else {
1193
+ // Not at edge, stop auto-scrolling
1194
+ this.stopAutoScroll()
1195
+ }
1196
+
1197
+ this.markNeedsRerender()
1198
+ return true
1199
+ }
1200
+
1201
+ if (event.type === "up") {
1202
+ if (this._isDragging) {
1203
+ this._selectionEnd = { line: lineIndex, col: colIndex }
1204
+ this._isDragging = false
1205
+ this.stopAutoScroll()
1206
+ this.markNeedsRerender()
1207
+ }
1208
+ return true
1209
+ }
1210
+
1211
+ return true
1212
+ }
1213
+
1214
+ public get visible(): boolean {
1215
+ return this.isVisible
1216
+ }
1217
+
1218
+ public get bounds(): { x: number; y: number; width: number; height: number } {
1219
+ return {
1220
+ x: this.consoleX,
1221
+ y: this.consoleY,
1222
+ width: this.consoleWidth,
1223
+ height: this.consoleHeight,
1224
+ }
1225
+ }
1226
+
1227
+ private saveLogsToFile(): void {
1228
+ try {
1229
+ const timestamp = Date.now()
1230
+ const filename = `_console_${timestamp}.log`
1231
+ const filepath = path.join(process.cwd(), filename)
1232
+
1233
+ const allLogEntries = [...this._allLogEntries, ...terminalConsoleCache.cachedLogs]
1234
+
1235
+ const logLines: string[] = []
1236
+
1237
+ for (const [date, level, args, callerInfo] of allLogEntries) {
1238
+ const timestampStr = this.formatTimestamp(date)
1239
+ const callerSource = callerInfo ? `${callerInfo.fileName}:${callerInfo.lineNumber}` : "unknown"
1240
+ const prefix = `[${timestampStr}] [${level}]` + (this._debugModeEnabled ? ` [${callerSource}]` : "") + " "
1241
+ const formattedArgs = this.formatArguments(args)
1242
+ logLines.push(prefix + formattedArgs)
1243
+ }
1244
+
1245
+ const content = logLines.join("\n")
1246
+ fs.writeFileSync(filepath, content, "utf8")
1247
+
1248
+ console.info(`Console logs saved to: ${filename}`)
1249
+ } catch (error) {
1250
+ console.error(`Failed to save console logs:`, error)
1251
+ }
1252
+ }
1253
+ }