@visual-z/xeno 0.2.1 → 0.3.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.
Files changed (258) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +106 -26
  3. package/docs/install.md +51 -13
  4. package/docs/providers.md +11 -0
  5. package/package.json +5 -4
  6. package/src/apps/approve.ts +3 -3
  7. package/src/apps/commands.ts +38 -5
  8. package/src/apps/completions.ts +73 -19
  9. package/src/apps/image-draft.ts +46 -0
  10. package/src/apps/project-trust.ts +2 -42
  11. package/src/apps/provider-connect.ts +346 -0
  12. package/src/apps/render.ts +22 -47
  13. package/src/apps/resources.ts +5 -2
  14. package/src/apps/shell.ts +298 -1526
  15. package/src/apps/startup-input.ts +45 -9
  16. package/src/apps/startup.ts +128 -86
  17. package/src/apps/ui/app.ts +1383 -0
  18. package/src/apps/ui/extension-host.ts +194 -0
  19. package/src/apps/ui/image-cache.ts +78 -0
  20. package/src/apps/ui/palette.ts +88 -0
  21. package/src/apps/ui/project.ts +127 -0
  22. package/src/apps/ui/standalone.ts +146 -0
  23. package/src/apps/ui/status-model.ts +68 -0
  24. package/src/apps/ui/surface.ts +84 -0
  25. package/src/apps/ui/theme.ts +86 -0
  26. package/src/core/acceptance.ts +107 -0
  27. package/src/core/action-defaults.ts +47 -295
  28. package/src/core/benchmark.ts +2 -2
  29. package/src/core/branch-receipt.ts +24 -0
  30. package/src/core/checkpoints.ts +64 -0
  31. package/src/core/churn.ts +2 -0
  32. package/src/core/command-artifacts.ts +94 -0
  33. package/src/core/command-contract.ts +35 -0
  34. package/src/core/completion-review.ts +21 -5
  35. package/src/core/context-detail.ts +37 -0
  36. package/src/core/context-policy.ts +74 -1
  37. package/src/core/continuation.ts +17 -2
  38. package/src/core/derive.ts +29 -3
  39. package/src/core/draft-images.ts +56 -0
  40. package/src/core/environment.ts +145 -0
  41. package/src/core/evaluation-coverage.ts +74 -0
  42. package/src/core/event-validation.ts +80 -5
  43. package/src/core/events.ts +97 -3
  44. package/src/core/evidence-links.ts +7 -0
  45. package/src/core/evidence.ts +13 -3
  46. package/src/core/execution.ts +8 -2
  47. package/src/core/experiment.ts +133 -0
  48. package/src/core/export.ts +9 -0
  49. package/src/core/failure-recovery.ts +173 -0
  50. package/src/core/file-precondition.ts +72 -0
  51. package/src/core/handoff.ts +65 -4
  52. package/src/core/history-query.ts +38 -2
  53. package/src/core/history.ts +38 -1
  54. package/src/core/integration-health.ts +34 -0
  55. package/src/core/keymap.ts +8 -20
  56. package/src/core/model-picker.ts +64 -0
  57. package/src/core/native-eval.ts +25 -0
  58. package/src/core/note-guidance.ts +34 -0
  59. package/src/core/observation-view.ts +49 -8
  60. package/src/core/permissions.ts +24 -2
  61. package/src/core/process-receipt.ts +105 -0
  62. package/src/core/process-state.ts +37 -0
  63. package/src/core/project.ts +45 -18
  64. package/src/core/prompt-policy.ts +37 -0
  65. package/src/core/query-eval-contract.ts +14 -0
  66. package/src/core/read-observation.ts +82 -0
  67. package/src/core/recovery-corpus.ts +17 -0
  68. package/src/core/recovery-evaluation.ts +60 -0
  69. package/src/core/recovery-sources.ts +74 -0
  70. package/src/core/runtime-target.ts +94 -0
  71. package/src/core/search-observation.ts +97 -0
  72. package/src/core/session-tree.ts +147 -0
  73. package/src/core/settings.ts +26 -10
  74. package/src/core/skills.ts +44 -0
  75. package/src/core/sql-query.ts +211 -0
  76. package/src/core/theme.ts +36 -58
  77. package/src/core/tool-contract.ts +51 -2
  78. package/src/core/tool-discovery.ts +87 -0
  79. package/src/core/tool-failure.ts +60 -0
  80. package/src/core/tool-mode-protocol.ts +25 -0
  81. package/src/core/transcript.ts +19 -4
  82. package/src/core/trial-lifecycle.ts +14 -0
  83. package/src/core/tui-mode.ts +29 -0
  84. package/src/core/update-check.ts +97 -0
  85. package/src/core/version.ts +55 -0
  86. package/src/core/work-state.ts +49 -3
  87. package/src/core/working-set.ts +91 -0
  88. package/src/runtime/auth.ts +2 -2
  89. package/src/runtime/branch-jobs.ts +36 -0
  90. package/src/runtime/clipboard.ts +15 -4
  91. package/src/runtime/command-artifacts.ts +64 -0
  92. package/src/runtime/environment-tools.ts +60 -0
  93. package/src/runtime/evidence-notes.ts +4 -2
  94. package/src/runtime/exec-sessions.ts +206 -61
  95. package/src/runtime/execution-control.ts +1 -0
  96. package/src/runtime/extension-ui.ts +22 -30
  97. package/src/runtime/extensions.ts +95 -16
  98. package/src/runtime/harness-comparison.ts +27 -7
  99. package/src/runtime/harness-eval.ts +460 -0
  100. package/src/runtime/history-cache.ts +57 -0
  101. package/src/runtime/history-tools.ts +62 -12
  102. package/src/runtime/integrations.ts +210 -0
  103. package/src/runtime/loop.ts +1021 -268
  104. package/src/runtime/model-discovery.ts +208 -0
  105. package/src/runtime/native-eval-fixtures.ts +33 -0
  106. package/src/runtime/native-eval.ts +143 -0
  107. package/src/runtime/oauth.ts +1 -1
  108. package/src/runtime/provider-connect.ts +109 -0
  109. package/src/runtime/provider-presets.ts +87 -0
  110. package/src/runtime/query-eval-verifier.ts +28 -0
  111. package/src/runtime/recovery-coverage.ts +71 -0
  112. package/src/runtime/recovery-evidence.ts +76 -0
  113. package/src/runtime/recovery-fixtures.ts +116 -0
  114. package/src/runtime/runtime-target.ts +149 -0
  115. package/src/runtime/tool-broker.ts +137 -0
  116. package/src/runtime/tool-discovery.ts +57 -0
  117. package/src/runtime/tool-mode-eval.ts +146 -0
  118. package/src/runtime/tool-queue.ts +77 -0
  119. package/src/runtime/tools.ts +628 -183
  120. package/src/runtime/trial-control.ts +45 -0
  121. package/src/runtime/update-check.ts +47 -0
  122. package/src/runtime/window-trial.ts +2 -1
  123. package/src/runtime/working-notes.ts +33 -3
  124. package/src/runtime/workspace-lifecycle.ts +97 -0
  125. package/src/store/acceptance.ts +15 -0
  126. package/src/store/checkpoint-history.ts +43 -0
  127. package/src/store/command-artifacts.ts +96 -0
  128. package/src/store/command.ts +65 -37
  129. package/src/store/file-checkpoints.ts +104 -0
  130. package/src/store/file-index.ts +13 -1
  131. package/src/store/git-checkpoints.ts +67 -0
  132. package/src/store/observations.ts +61 -20
  133. package/src/store/process-receipts.ts +34 -0
  134. package/src/store/query-source.ts +13 -8
  135. package/src/store/recovery.ts +2 -3
  136. package/src/store/replay.ts +16 -4
  137. package/src/store/runtime-target.ts +64 -0
  138. package/src/store/search.ts +171 -132
  139. package/src/store/session-archive.ts +4 -0
  140. package/src/store/source-cancellation.ts +6 -0
  141. package/src/store/update-cache.ts +36 -0
  142. package/src/store/workspace-observation.ts +113 -0
  143. package/src/tui/ansi-spans.ts +126 -0
  144. package/src/tui/style.ts +19 -16
  145. package/src/tui/ui/atomic-draft.ts +121 -0
  146. package/src/tui/ui/canvas.ts +96 -0
  147. package/src/tui/ui/colors.ts +70 -0
  148. package/src/tui/ui/composer.ts +199 -0
  149. package/src/tui/ui/dialog.ts +379 -0
  150. package/src/tui/ui/draft.ts +23 -0
  151. package/src/tui/ui/edge.ts +186 -0
  152. package/src/tui/ui/image-size.ts +40 -0
  153. package/src/tui/ui/ink.ts +210 -0
  154. package/src/tui/ui/items.ts +40 -0
  155. package/src/tui/ui/keys.ts +40 -0
  156. package/src/tui/ui/layout.ts +74 -0
  157. package/src/tui/ui/list-model.ts +86 -0
  158. package/src/tui/ui/list-view.ts +172 -0
  159. package/src/tui/ui/mascot.ts +67 -0
  160. package/src/tui/ui/messages.ts +518 -0
  161. package/src/tui/ui/motion.ts +28 -0
  162. package/src/tui/ui/paths.ts +10 -0
  163. package/src/tui/ui/pictures.ts +78 -0
  164. package/src/tui/ui/screen.ts +421 -0
  165. package/src/tui/ui/status.ts +271 -0
  166. package/src/tui/ui/styled.ts +85 -0
  167. package/src/tui/ui/testing.ts +5 -0
  168. package/src/tui/ui/tool-card.ts +150 -0
  169. package/src/apps/extension-ui.ts +0 -330
  170. package/src/apps/resource-browser.ts +0 -75
  171. package/src/apps/session-browser.ts +0 -113
  172. package/src/apps/session-picker.ts +0 -55
  173. package/src/tui/ansi.ts +0 -67
  174. package/src/tui/autocomplete.ts +0 -29
  175. package/src/tui/chat-viewport.ts +0 -47
  176. package/src/tui/complete.ts +0 -87
  177. package/src/tui/editor.ts +0 -940
  178. package/src/tui/host.ts +0 -264
  179. package/src/tui/input.ts +0 -75
  180. package/src/tui/keys.ts +0 -378
  181. package/src/tui/markdown.ts +0 -17
  182. package/src/tui/render.ts +0 -153
  183. package/src/tui/select.ts +0 -258
  184. package/src/tui/settings.ts +0 -44
  185. package/src/tui/statusline.ts +0 -162
  186. package/src/tui/system-theme.ts +0 -700
  187. package/src/tui/terminal.ts +0 -30
  188. package/src/tui/text.ts +0 -52
  189. package/src/tui/toolview.ts +0 -386
  190. package/src/tui/transcript.ts +0 -123
  191. package/src/tui/tree.ts +0 -471
  192. package/src/vendor/pi-tui/LICENSE.upstream +0 -21
  193. package/src/vendor/pi-tui/UPSTREAM.json +0 -50
  194. package/src/vendor/pi-tui/VENDOR.md +0 -25
  195. package/src/vendor/pi-tui/alt-screen-search.ts +0 -327
  196. package/src/vendor/pi-tui/autocomplete.ts +0 -860
  197. package/src/vendor/pi-tui/colors.ts +0 -367
  198. package/src/vendor/pi-tui/components/alt-screen-flash.ts +0 -51
  199. package/src/vendor/pi-tui/components/box.ts +0 -166
  200. package/src/vendor/pi-tui/components/cancellable-loader.ts +0 -40
  201. package/src/vendor/pi-tui/components/editor.ts +0 -2472
  202. package/src/vendor/pi-tui/components/h-stack.ts +0 -44
  203. package/src/vendor/pi-tui/components/image.ts +0 -127
  204. package/src/vendor/pi-tui/components/input.ts +0 -494
  205. package/src/vendor/pi-tui/components/loader.ts +0 -101
  206. package/src/vendor/pi-tui/components/markdown.ts +0 -1021
  207. package/src/vendor/pi-tui/components/mouse-region.ts +0 -33
  208. package/src/vendor/pi-tui/components/scroll-view.ts +0 -224
  209. package/src/vendor/pi-tui/components/select-list.ts +0 -273
  210. package/src/vendor/pi-tui/components/settings-list.ts +0 -328
  211. package/src/vendor/pi-tui/components/spacer.ts +0 -28
  212. package/src/vendor/pi-tui/components/stack.ts +0 -154
  213. package/src/vendor/pi-tui/components/text.ts +0 -107
  214. package/src/vendor/pi-tui/components/truncated-text.ts +0 -65
  215. package/src/vendor/pi-tui/components/v-stack.ts +0 -33
  216. package/src/vendor/pi-tui/editor-component.ts +0 -74
  217. package/src/vendor/pi-tui/fuzzy.ts +0 -138
  218. package/src/vendor/pi-tui/index.ts +0 -186
  219. package/src/vendor/pi-tui/keybindings.ts +0 -320
  220. package/src/vendor/pi-tui/keys.ts +0 -1401
  221. package/src/vendor/pi-tui/kill-ring.ts +0 -46
  222. package/src/vendor/pi-tui/latex.ts +0 -1506
  223. package/src/vendor/pi-tui/layout-node.ts +0 -51
  224. package/src/vendor/pi-tui/layout.ts +0 -449
  225. package/src/vendor/pi-tui/native/UPSTREAM.json +0 -23
  226. package/src/vendor/pi-tui/native/clipboard.h +0 -208
  227. package/src/vendor/pi-tui/native/darwin/README.md +0 -22
  228. package/src/vendor/pi-tui/native/darwin/build.sh +0 -69
  229. package/src/vendor/pi-tui/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  230. package/src/vendor/pi-tui/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  231. package/src/vendor/pi-tui/native/darwin/src/darwin-platform.m +0 -132
  232. package/src/vendor/pi-tui/native/linux/README.md +0 -23
  233. package/src/vendor/pi-tui/native/linux/build.sh +0 -65
  234. package/src/vendor/pi-tui/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  235. package/src/vendor/pi-tui/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  236. package/src/vendor/pi-tui/native/linux/src/clipboard-worker.h +0 -70
  237. package/src/vendor/pi-tui/native/linux/src/linux-platform-x11.c +0 -274
  238. package/src/vendor/pi-tui/native/napi.h +0 -91
  239. package/src/vendor/pi-tui/native/win32/README.md +0 -31
  240. package/src/vendor/pi-tui/native/win32/build.mjs +0 -232
  241. package/src/vendor/pi-tui/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  242. package/src/vendor/pi-tui/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  243. package/src/vendor/pi-tui/native/win32/src/win32-platform.c +0 -241
  244. package/src/vendor/pi-tui/native-modifiers.ts +0 -13
  245. package/src/vendor/pi-tui/native-module-path.ts +0 -31
  246. package/src/vendor/pi-tui/native-platform.ts +0 -65
  247. package/src/vendor/pi-tui/oklab.ts +0 -233
  248. package/src/vendor/pi-tui/stdin-buffer.ts +0 -444
  249. package/src/vendor/pi-tui/terminal-colors.ts +0 -91
  250. package/src/vendor/pi-tui/terminal-image.ts +0 -731
  251. package/src/vendor/pi-tui/terminal.ts +0 -554
  252. package/src/vendor/pi-tui/tui-alt-screen.ts +0 -1750
  253. package/src/vendor/pi-tui/tui-main-screen.ts +0 -655
  254. package/src/vendor/pi-tui/tui.ts +0 -1493
  255. package/src/vendor/pi-tui/undo-stack.ts +0 -28
  256. package/src/vendor/pi-tui/utils.ts +0 -1385
  257. package/src/vendor/pi-tui/wheel-scroll.ts +0 -82
  258. package/src/vendor/pi-tui/word-navigation.ts +0 -117
@@ -1,1021 +0,0 @@
1
- import { Marked, type Token, Tokenizer, type TokenizerExtension, type Tokens } from "marked";
2
- import { renderLatex } from "../latex.ts";
3
- import { getCapabilities, hyperlink, isImageLine } from "../terminal-image.ts";
4
- import type { Component } from "../tui.ts";
5
- import { applyBackgroundToLine, visibleWidth, wrapTextWithAnsi } from "../utils.ts";
6
-
7
- const STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
8
-
9
- class StrictStrikethroughTokenizer extends Tokenizer {
10
- override del(src: string): Tokens.Del | undefined {
11
- const match = STRICT_STRIKETHROUGH_REGEX.exec(src);
12
- if (!match) {
13
- return undefined;
14
- }
15
-
16
- const text = match[2];
17
- return {
18
- type: "del",
19
- raw: match[0],
20
- text,
21
- tokens: this.lexer.inlineTokens(text),
22
- };
23
- }
24
- }
25
-
26
- interface LatexToken extends Tokens.Generic {
27
- type: "latex" | "latexBlock";
28
- text: string;
29
- pending?: boolean;
30
- }
31
-
32
- function isEscaped(source: string, index: number): boolean {
33
- let backslashes = 0;
34
- for (let position = index - 1; position >= 0 && source[position] === "\\"; position--) {
35
- backslashes++;
36
- }
37
- return backslashes % 2 === 1;
38
- }
39
-
40
- function findClosingDelimiter(source: string, closing: string, start: number): number {
41
- let index = source.indexOf(closing, start);
42
- while (index >= 0 && isEscaped(source, index)) {
43
- index = source.indexOf(closing, index + closing.length);
44
- }
45
- return index;
46
- }
47
-
48
- function looksLikePendingDollarMath(source: string): boolean {
49
- return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source);
50
- }
51
-
52
- function tokenizeInlineLatex(source: string): LatexToken | undefined {
53
- let opening = "";
54
- let closing = "";
55
- if (source.startsWith("$$")) {
56
- opening = "$$";
57
- closing = "$$";
58
- } else if (source.startsWith("\\(")) {
59
- opening = "\\(";
60
- closing = "\\)";
61
- } else if (source.startsWith("\\[")) {
62
- opening = "\\[";
63
- closing = "\\]";
64
- } else if (source.startsWith("$") && !/^\$\s/.test(source)) {
65
- opening = "$";
66
- closing = "$";
67
- } else {
68
- return undefined;
69
- }
70
-
71
- const closingIndex = findClosingDelimiter(source, closing, opening.length);
72
- if (
73
- closingIndex >= 0 &&
74
- opening === "$" &&
75
- (/\s$/.test(source.slice(opening.length, closingIndex)) ||
76
- /^\d/.test(source.slice(closingIndex + 1)) ||
77
- (/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length, closingIndex)) &&
78
- /^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex + 1))) ||
79
- source.slice(opening.length, closingIndex).includes("`"))
80
- ) {
81
- return undefined;
82
- }
83
-
84
- if (closingIndex < 0) {
85
- const pendingSource = source.slice(opening.length);
86
- if (opening.startsWith("\\") || looksLikePendingDollarMath(pendingSource)) {
87
- return { type: "latex", raw: source, text: pendingSource, pending: true };
88
- }
89
- return undefined;
90
- }
91
-
92
- const text = source.slice(opening.length, closingIndex);
93
- if (!text || text.includes("\n")) {
94
- return undefined;
95
- }
96
-
97
- const raw = source.slice(0, closingIndex + closing.length);
98
- return { type: "latex", raw, text };
99
- }
100
-
101
- function tokenizeBlockLatex(source: string): LatexToken | undefined {
102
- const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);
103
- if (dollarMatch?.[1]) {
104
- return { type: "latexBlock", raw: dollarMatch[0], text: dollarMatch[1].trim() };
105
- }
106
-
107
- const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);
108
- if (bracketMatch?.[1]) {
109
- return { type: "latexBlock", raw: bracketMatch[0], text: bracketMatch[1].trim() };
110
- }
111
-
112
- const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
113
- if (pendingBracket) {
114
- return { type: "latexBlock", raw: pendingBracket[0], text: pendingBracket[1], pending: true };
115
- }
116
- const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
117
- if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1])) {
118
- return { type: "latexBlock", raw: pendingDollar[0], text: pendingDollar[1], pending: true };
119
- }
120
- return undefined;
121
- }
122
-
123
- const LATEX_MARKDOWN_EXTENSIONS: readonly TokenizerExtension[] = [
124
- {
125
- name: "latexBlock",
126
- level: "block",
127
- start(source) {
128
- const match = /(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);
129
- return match ? match.index + (match[0].startsWith("\n") ? 1 : 0) : undefined;
130
- },
131
- tokenizer: tokenizeBlockLatex,
132
- },
133
- {
134
- name: "latex",
135
- level: "inline",
136
- start(source) {
137
- const indices = [source.indexOf("$"), source.indexOf("\\("), source.indexOf("\\[")].filter(
138
- (index) => index >= 0,
139
- );
140
- return indices.length > 0 ? Math.min(...indices) : undefined;
141
- },
142
- tokenizer: tokenizeInlineLatex,
143
- },
144
- ];
145
-
146
- function trimPartialClosingFences(tokens: readonly Token[]): void {
147
- const token = tokens[tokens.length - 1];
148
- if (token?.type === "list") {
149
- trimPartialClosingFences(token.items[token.items.length - 1]?.tokens ?? []);
150
- return;
151
- }
152
- if (token?.type === "blockquote") {
153
- trimPartialClosingFences(token.tokens ?? []);
154
- return;
155
- }
156
- if (token?.type !== "code") {
157
- return;
158
- }
159
-
160
- // Trim streamed partial closing fences so code blocks do not shrink/flicker
161
- // when the final fence character arrives. See https://github.com/earendil-works/pi/issues/5825.
162
- const marker = /^(`{3,}|~{3,})/.exec(token.raw)?.[1];
163
- const lastLine = token.raw.split("\n").pop();
164
- if (!marker || !lastLine || lastLine.length >= marker.length || lastLine !== marker[0]?.repeat(lastLine.length)) {
165
- return;
166
- }
167
-
168
- token.text = token.text.slice(0, -lastLine.length).replace(/\n$/, "");
169
- }
170
-
171
- const markdownParser = new Marked();
172
- markdownParser.setOptions({
173
- tokenizer: new StrictStrikethroughTokenizer(),
174
- });
175
- markdownParser.use({ extensions: [...LATEX_MARKDOWN_EXTENSIONS] });
176
-
177
- /**
178
- * Default text styling for markdown content.
179
- * Applied to all text unless overridden by markdown formatting.
180
- */
181
- export interface DefaultTextStyle {
182
- /** Foreground color function */
183
- color?: (text: string) => string;
184
- /** Background color function */
185
- bgColor?: (text: string) => string;
186
- /** Bold text */
187
- bold?: boolean;
188
- /** Italic text */
189
- italic?: boolean;
190
- /** Strikethrough text */
191
- strikethrough?: boolean;
192
- /** Underline text */
193
- underline?: boolean;
194
- }
195
-
196
- /**
197
- * Theme functions for markdown elements.
198
- * Each function takes text and returns styled text with ANSI codes.
199
- */
200
- export interface MarkdownTheme {
201
- heading: (text: string) => string;
202
- link: (text: string) => string;
203
- linkUrl: (text: string) => string;
204
- code: (text: string) => string;
205
- codeBlock: (text: string) => string;
206
- codeBlockBorder: (text: string) => string;
207
- quote: (text: string) => string;
208
- quoteBorder: (text: string) => string;
209
- hr: (text: string) => string;
210
- listBullet: (text: string) => string;
211
- bold: (text: string) => string;
212
- italic: (text: string) => string;
213
- strikethrough: (text: string) => string;
214
- underline: (text: string) => string;
215
- highlightCode?: (code: string, lang?: string) => string[];
216
- /** Prefix applied to each rendered code block line (default: " ") */
217
- codeBlockIndent?: string;
218
- }
219
-
220
- export interface MarkdownOptions {
221
- /** Preserve source list markers instead of normalizing them. */
222
- preserveOrderedListMarkers?: boolean;
223
- /** Preserve source backslash escapes instead of normalizing escaped punctuation. */
224
- preserveBackslashEscapes?: boolean;
225
- /** Transform source Markdown before parsing, with the exact width available for content. */
226
- transform?: (markdown: string, availableWidth: number) => string;
227
- /** Render supported LaTeX math expressions as Unicode text (default: true). */
228
- renderLatex?: boolean;
229
- }
230
-
231
- interface InlineStyleContext {
232
- applyText: (text: string) => string;
233
- stylePrefix: string;
234
- }
235
-
236
- export class Markdown implements Component {
237
- private text: string;
238
- private paddingX: number; // Left/right padding
239
- private paddingY: number; // Top/bottom padding
240
- private defaultTextStyle?: DefaultTextStyle;
241
- private theme: MarkdownTheme;
242
- private options: MarkdownOptions;
243
- private defaultStylePrefix?: string;
244
-
245
- // Cache for rendered output
246
- private cachedText?: string;
247
- private cachedWidth?: number;
248
- private cachedLines?: string[];
249
- // Parsed tokens depend only on the source, so they survive theme and width invalidation.
250
- private cachedTokens?: { source: string; tokens: Token[] };
251
-
252
- constructor(
253
- text: string,
254
- paddingX: number,
255
- paddingY: number,
256
- theme: MarkdownTheme,
257
- defaultTextStyle?: DefaultTextStyle,
258
- options?: MarkdownOptions,
259
- ) {
260
- this.text = text;
261
- this.paddingX = paddingX;
262
- this.paddingY = paddingY;
263
- this.theme = theme;
264
- this.defaultTextStyle = defaultTextStyle;
265
- this.options = options ? { ...options } : {};
266
- }
267
-
268
- setText(text: string): void {
269
- this.text = text;
270
- this.invalidate();
271
- }
272
-
273
- invalidate(): void {
274
- this.cachedText = undefined;
275
- this.cachedWidth = undefined;
276
- this.cachedLines = undefined;
277
- }
278
-
279
- render(width: number): string[] {
280
- // Check cache
281
- if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
282
- return this.cachedLines;
283
- }
284
-
285
- // Calculate available width for content (subtract horizontal padding)
286
- const contentWidth = Math.max(1, width - this.paddingX * 2);
287
- const text = this.options.transform?.(this.text, contentWidth) ?? this.text;
288
-
289
- // Don't render anything if there's no actual text
290
- if (!text || text.trim() === "") {
291
- const result: string[] = [];
292
- // Update cache
293
- this.cachedText = this.text;
294
- this.cachedWidth = width;
295
- this.cachedLines = result;
296
- return result;
297
- }
298
-
299
- // Replace tabs with 3 spaces for consistent rendering
300
- const normalizedText = text.replace(/\t/g, " ");
301
-
302
- // Parse markdown to HTML-like tokens
303
- let tokens = this.cachedTokens?.source === normalizedText ? this.cachedTokens.tokens : undefined;
304
- if (!tokens) {
305
- tokens = markdownParser.lexer(normalizedText);
306
- trimPartialClosingFences(tokens);
307
- this.cachedTokens = { source: normalizedText, tokens };
308
- }
309
-
310
- // Convert tokens to styled terminal output
311
- const renderedLines: string[] = [];
312
-
313
- for (let i = 0; i < tokens.length; i++) {
314
- const token = tokens[i];
315
- const nextToken = tokens[i + 1];
316
- const tokenLines = this.renderToken(token, contentWidth, nextToken?.type);
317
- for (const tokenLine of tokenLines) {
318
- renderedLines.push(tokenLine);
319
- }
320
- }
321
-
322
- // Wrap lines (NO padding, NO background yet)
323
- const wrappedLines: string[] = [];
324
- for (const line of renderedLines) {
325
- if (isImageLine(line)) {
326
- wrappedLines.push(line);
327
- } else {
328
- for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) {
329
- wrappedLines.push(wrappedLine);
330
- }
331
- }
332
- }
333
-
334
- // Add margins and background to each wrapped line
335
- const leftMargin = " ".repeat(this.paddingX);
336
- const rightMargin = " ".repeat(this.paddingX);
337
- const bgFn = this.defaultTextStyle?.bgColor;
338
- const contentLines: string[] = [];
339
-
340
- for (const line of wrappedLines) {
341
- if (isImageLine(line)) {
342
- contentLines.push(line);
343
- continue;
344
- }
345
-
346
- const lineWithMargins = leftMargin + line + rightMargin;
347
-
348
- if (bgFn) {
349
- contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
350
- } else {
351
- // No background - just pad to width
352
- const visibleLen = visibleWidth(lineWithMargins);
353
- const paddingNeeded = Math.max(0, width - visibleLen);
354
- contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
355
- }
356
- }
357
-
358
- // Add top/bottom padding (empty lines)
359
- const emptyLine = " ".repeat(width);
360
- const emptyLines: string[] = [];
361
- for (let i = 0; i < this.paddingY; i++) {
362
- const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
363
- emptyLines.push(line);
364
- }
365
-
366
- // Combine top padding, content, and bottom padding
367
- const result = emptyLines.concat(contentLines, emptyLines);
368
-
369
- // Update cache
370
- this.cachedText = this.text;
371
- this.cachedWidth = width;
372
- this.cachedLines = result;
373
-
374
- return result.length > 0 ? result : [""];
375
- }
376
-
377
- /**
378
- * Apply default text style to a string.
379
- * This is the base styling applied to all text content.
380
- * NOTE: Background color is NOT applied here - it's applied at the padding stage
381
- * to ensure it extends to the full line width.
382
- */
383
- private applyDefaultStyle(text: string): string {
384
- if (!this.defaultTextStyle) {
385
- return text;
386
- }
387
-
388
- let styled = text;
389
-
390
- // Apply foreground color (NOT background - that's applied at padding stage)
391
- if (this.defaultTextStyle.color) {
392
- styled = this.defaultTextStyle.color(styled);
393
- }
394
-
395
- // Apply text decorations using this.theme
396
- if (this.defaultTextStyle.bold) {
397
- styled = this.theme.bold(styled);
398
- }
399
- if (this.defaultTextStyle.italic) {
400
- styled = this.theme.italic(styled);
401
- }
402
- if (this.defaultTextStyle.strikethrough) {
403
- styled = this.theme.strikethrough(styled);
404
- }
405
- if (this.defaultTextStyle.underline) {
406
- styled = this.theme.underline(styled);
407
- }
408
-
409
- return styled;
410
- }
411
-
412
- private getDefaultStylePrefix(): string {
413
- if (!this.defaultTextStyle) {
414
- return "";
415
- }
416
-
417
- if (this.defaultStylePrefix !== undefined) {
418
- return this.defaultStylePrefix;
419
- }
420
-
421
- const sentinel = "\u0000";
422
- let styled = sentinel;
423
-
424
- if (this.defaultTextStyle.color) {
425
- styled = this.defaultTextStyle.color(styled);
426
- }
427
-
428
- if (this.defaultTextStyle.bold) {
429
- styled = this.theme.bold(styled);
430
- }
431
- if (this.defaultTextStyle.italic) {
432
- styled = this.theme.italic(styled);
433
- }
434
- if (this.defaultTextStyle.strikethrough) {
435
- styled = this.theme.strikethrough(styled);
436
- }
437
- if (this.defaultTextStyle.underline) {
438
- styled = this.theme.underline(styled);
439
- }
440
-
441
- const sentinelIndex = styled.indexOf(sentinel);
442
- this.defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
443
- return this.defaultStylePrefix;
444
- }
445
-
446
- private getStylePrefix(styleFn: (text: string) => string): string {
447
- const sentinel = "\u0000";
448
- const styled = styleFn(sentinel);
449
- const sentinelIndex = styled.indexOf(sentinel);
450
- return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
451
- }
452
-
453
- private getDefaultInlineStyleContext(): InlineStyleContext {
454
- return {
455
- applyText: (text: string) => this.applyDefaultStyle(text),
456
- stylePrefix: this.getDefaultStylePrefix(),
457
- };
458
- }
459
-
460
- private renderToken(
461
- token: Token,
462
- width: number,
463
- nextTokenType?: string,
464
- styleContext?: InlineStyleContext,
465
- ): string[] {
466
- const lines: string[] = [];
467
-
468
- switch (token.type) {
469
- case "heading": {
470
- const headingLevel = token.depth;
471
- const headingPrefix = `${"#".repeat(headingLevel)} `;
472
-
473
- // Build a heading-specific style context so inline tokens (codespan, bold, etc.)
474
- // restore heading styling after their own ANSI resets instead of falling back to
475
- // the default text style.
476
- let headingStyleFn: (text: string) => string;
477
- if (headingLevel === 1) {
478
- headingStyleFn = (text: string) => this.theme.heading(this.theme.bold(this.theme.underline(text)));
479
- } else {
480
- headingStyleFn = (text: string) => this.theme.heading(this.theme.bold(text));
481
- }
482
-
483
- const headingStyleContext: InlineStyleContext = {
484
- applyText: headingStyleFn,
485
- stylePrefix: this.getStylePrefix(headingStyleFn),
486
- };
487
-
488
- const headingText = this.renderInlineTokens(token.tokens || [], headingStyleContext);
489
- const styledHeading = headingLevel >= 3 ? headingStyleFn(headingPrefix) + headingText : headingText;
490
- lines.push(styledHeading);
491
- if (nextTokenType && nextTokenType !== "space") {
492
- lines.push(""); // Add spacing after headings (unless space token follows)
493
- }
494
- break;
495
- }
496
-
497
- case "paragraph": {
498
- const paragraphText = this.renderInlineTokens(token.tokens || [], styleContext);
499
- lines.push(paragraphText);
500
- // Don't add spacing if next token is space or list
501
- if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
502
- lines.push("");
503
- }
504
- break;
505
- }
506
-
507
- case "text":
508
- lines.push(this.renderInlineTokens([token], styleContext));
509
- break;
510
-
511
- case "latexBlock": {
512
- const latexToken = token as LatexToken;
513
- const rendered =
514
- !latexToken.pending && this.options.renderLatex !== false
515
- ? (renderLatex(latexToken.text, { display: true }) ?? latexToken.raw.trim())
516
- : latexToken.raw.trim();
517
- for (const line of rendered.split("\n")) {
518
- lines.push(this.applyDefaultStyle(line));
519
- }
520
- if (nextTokenType && nextTokenType !== "space") {
521
- lines.push("");
522
- }
523
- break;
524
- }
525
-
526
- case "code": {
527
- const indent = this.theme.codeBlockIndent ?? " ";
528
- lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
529
- if (this.theme.highlightCode) {
530
- const highlightedLines = this.theme.highlightCode(token.text, token.lang);
531
- for (const hlLine of highlightedLines) {
532
- lines.push(`${indent}${hlLine}`);
533
- }
534
- } else {
535
- // Split code by newlines and style each line
536
- const codeLines = token.text.split("\n");
537
- for (const codeLine of codeLines) {
538
- lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
539
- }
540
- }
541
- lines.push(this.theme.codeBlockBorder("```"));
542
- if (nextTokenType && nextTokenType !== "space") {
543
- lines.push(""); // Add spacing after code blocks (unless space token follows)
544
- }
545
- break;
546
- }
547
-
548
- case "list": {
549
- const listLines = this.renderList(token as Tokens.List, 0, width, styleContext);
550
- lines.push(...listLines);
551
- // Don't add spacing after lists if a space token follows
552
- // (the space token will handle it)
553
- break;
554
- }
555
-
556
- case "table": {
557
- const tableLines = this.renderTable(token as Tokens.Table, width, nextTokenType, styleContext);
558
- lines.push(...tableLines);
559
- break;
560
- }
561
-
562
- case "blockquote": {
563
- const quoteStyle = (text: string) => this.theme.quote(this.theme.italic(text));
564
- const quoteStylePrefix = this.getStylePrefix(quoteStyle);
565
- const applyQuoteStyle = (line: string): string => {
566
- if (!quoteStylePrefix) {
567
- return quoteStyle(line);
568
- }
569
- const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1b[0m${quoteStylePrefix}`);
570
- return quoteStyle(lineWithReappliedStyle);
571
- };
572
-
573
- // Calculate available width for quote content (subtract border "│ " = 2 chars)
574
- const quoteContentWidth = Math.max(1, width - 2);
575
-
576
- // Blockquotes contain block-level tokens (paragraph, list, code, etc.), so render
577
- // children with renderToken() instead of renderInlineTokens().
578
- // Default message style should not apply inside blockquotes.
579
- const quoteInlineStyleContext: InlineStyleContext = {
580
- applyText: (text: string) => text,
581
- stylePrefix: quoteStylePrefix,
582
- };
583
- const quoteTokens = token.tokens || [];
584
- const renderedQuoteLines: string[] = [];
585
- for (let i = 0; i < quoteTokens.length; i++) {
586
- const quoteToken = quoteTokens[i];
587
- const nextQuoteToken = quoteTokens[i + 1];
588
- renderedQuoteLines.push(
589
- ...this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext),
590
- );
591
- }
592
-
593
- // Avoid rendering an extra empty quote line before the outer blockquote spacing.
594
- while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") {
595
- renderedQuoteLines.pop();
596
- }
597
-
598
- for (const quoteLine of renderedQuoteLines) {
599
- const styledLine = applyQuoteStyle(quoteLine);
600
- const wrappedLines = wrapTextWithAnsi(styledLine, quoteContentWidth);
601
- for (const wrappedLine of wrappedLines) {
602
- lines.push(this.theme.quoteBorder("│ ") + wrappedLine);
603
- }
604
- }
605
- if (nextTokenType && nextTokenType !== "space") {
606
- lines.push(""); // Add spacing after blockquotes (unless space token follows)
607
- }
608
- break;
609
- }
610
-
611
- case "hr":
612
- lines.push(this.theme.hr("─".repeat(Math.min(width, 80))));
613
- if (nextTokenType && nextTokenType !== "space") {
614
- lines.push(""); // Add spacing after horizontal rules (unless space token follows)
615
- }
616
- break;
617
-
618
- case "html":
619
- // Render HTML as plain text (escaped for terminal)
620
- if ("raw" in token && typeof token.raw === "string") {
621
- lines.push(this.applyDefaultStyle(token.raw.trim()));
622
- }
623
- break;
624
-
625
- case "space":
626
- // Space tokens represent blank lines in markdown
627
- lines.push("");
628
- break;
629
-
630
- default:
631
- // Handle any other token types as plain text
632
- if ("text" in token && typeof token.text === "string") {
633
- lines.push(token.text);
634
- }
635
- }
636
-
637
- return lines;
638
- }
639
-
640
- private renderInlineTokens(tokens: Token[], styleContext?: InlineStyleContext): string {
641
- let result = "";
642
- const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext();
643
- const { applyText, stylePrefix } = resolvedStyleContext;
644
- const applyTextWithNewlines = (text: string): string => {
645
- const segments: string[] = text.split("\n");
646
- return segments.map((segment: string) => applyText(segment)).join("\n");
647
- };
648
-
649
- for (const token of tokens) {
650
- switch (token.type) {
651
- case "latex": {
652
- const latexToken = token as LatexToken;
653
- const rendered =
654
- !latexToken.pending && this.options.renderLatex !== false
655
- ? (renderLatex(latexToken.text) ?? latexToken.raw)
656
- : latexToken.raw;
657
- result += applyTextWithNewlines(rendered);
658
- break;
659
- }
660
-
661
- case "escape":
662
- result += applyTextWithNewlines(this.options.preserveBackslashEscapes ? token.raw : token.text);
663
- break;
664
-
665
- case "text":
666
- // Text tokens in list items can have nested tokens for inline formatting
667
- if (token.tokens && token.tokens.length > 0) {
668
- result += this.renderInlineTokens(token.tokens, resolvedStyleContext);
669
- } else {
670
- result += applyTextWithNewlines(token.text);
671
- }
672
- break;
673
-
674
- case "paragraph":
675
- // Paragraph tokens contain nested inline tokens
676
- result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
677
- break;
678
-
679
- case "strong": {
680
- const boldContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
681
- result += this.theme.bold(boldContent) + stylePrefix;
682
- break;
683
- }
684
-
685
- case "em": {
686
- const italicContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
687
- result += this.theme.italic(italicContent) + stylePrefix;
688
- break;
689
- }
690
-
691
- case "codespan":
692
- result += this.theme.code(token.text) + stylePrefix;
693
- break;
694
-
695
- case "link": {
696
- const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
697
- const styledLink = this.theme.link(this.theme.underline(linkText));
698
- if (getCapabilities().hyperlinks) {
699
- // OSC 8: render as a clickable hyperlink. The URL is not printed inline,
700
- // so we always show only the link text regardless of whether it matches href.
701
- result += hyperlink(styledLink, token.href) + stylePrefix;
702
- } else {
703
- // Fallback: print URL in parentheses when text differs from href.
704
- // Compare raw token.text (not styled) against href for the equality check.
705
- // For mailto: links strip the prefix (autolinked emails use text="foo@bar.com"
706
- // but href="mailto:foo@bar.com").
707
- const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;
708
- if (token.text === token.href || token.text === hrefForComparison) {
709
- result += styledLink + stylePrefix;
710
- } else {
711
- result += styledLink + this.theme.linkUrl(` (${token.href})`) + stylePrefix;
712
- }
713
- }
714
- break;
715
- }
716
-
717
- case "br":
718
- result += "\n";
719
- break;
720
-
721
- case "del": {
722
- const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
723
- result += this.theme.strikethrough(delContent) + stylePrefix;
724
- break;
725
- }
726
-
727
- case "html":
728
- // Render inline HTML as plain text
729
- if ("raw" in token && typeof token.raw === "string") {
730
- result += applyTextWithNewlines(token.raw);
731
- }
732
- break;
733
-
734
- default:
735
- // Handle any other inline token types as plain text
736
- if ("text" in token && typeof token.text === "string") {
737
- result += applyTextWithNewlines(token.text);
738
- }
739
- }
740
- }
741
-
742
- while (stylePrefix && result.endsWith(stylePrefix)) {
743
- result = result.slice(0, -stylePrefix.length);
744
- }
745
-
746
- return result;
747
- }
748
-
749
- private getOrderedListMarker(item: Tokens.ListItem): string | undefined {
750
- const match = /^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);
751
- return match ? `${match[1]} ` : undefined;
752
- }
753
-
754
- private getUnorderedListMarker(item: Tokens.ListItem): string | undefined {
755
- const match = /^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);
756
- return match ? `${match[1]} ` : undefined;
757
- }
758
-
759
- /**
760
- * Render a list with proper nesting support
761
- */
762
- private renderList(token: Tokens.List, depth: number, width: number, styleContext?: InlineStyleContext): string[] {
763
- const lines: string[] = [];
764
- const indent = " ".repeat(depth);
765
- // Use the list's start property (defaults to 1 for ordered lists)
766
- const startNumber = typeof token.start === "number" ? token.start : 1;
767
-
768
- for (let i = 0; i < token.items.length; i++) {
769
- const item = token.items[i];
770
- const isLastItem = i === token.items.length - 1;
771
- const bullet = token.ordered
772
- ? this.options.preserveOrderedListMarkers
773
- ? (this.getOrderedListMarker(item) ?? `${startNumber + i}. `)
774
- : `${startNumber + i}. `
775
- : this.options.preserveOrderedListMarkers
776
- ? (this.getUnorderedListMarker(item) ?? "- ")
777
- : "- ";
778
- const taskMarker = item.task ? `[${item.checked ? "x" : " "}] ` : "";
779
- const marker = bullet + taskMarker;
780
- const firstPrefix = indent + this.theme.listBullet(marker);
781
- const continuationPrefix = indent + " ".repeat(visibleWidth(marker));
782
- const itemWidth = Math.max(1, width - visibleWidth(firstPrefix));
783
- let renderedAnyLine = false;
784
-
785
- for (const itemToken of item.tokens) {
786
- if (itemToken.type === "list") {
787
- lines.push(...this.renderList(itemToken as Tokens.List, depth + 1, width, styleContext));
788
- renderedAnyLine = true;
789
- continue;
790
- }
791
-
792
- const itemLines = this.renderToken(itemToken, itemWidth, undefined, styleContext);
793
- for (const line of itemLines) {
794
- for (const wrappedLine of wrapTextWithAnsi(line, itemWidth)) {
795
- const linePrefix = renderedAnyLine ? continuationPrefix : firstPrefix;
796
- lines.push(linePrefix + wrappedLine);
797
- renderedAnyLine = true;
798
- }
799
- }
800
- }
801
-
802
- if (!renderedAnyLine) {
803
- lines.push(firstPrefix);
804
- }
805
-
806
- if (token.loose && !isLastItem) {
807
- lines.push("");
808
- }
809
- }
810
-
811
- return lines;
812
- }
813
-
814
- /**
815
- * Get the visible width of the longest word in a string.
816
- */
817
- private getLongestWordWidth(text: string, maxWidth?: number): number {
818
- const words = text.split(/\s+/).filter((word) => word.length > 0);
819
- let longest = 0;
820
- for (const word of words) {
821
- longest = Math.max(longest, visibleWidth(word));
822
- }
823
- if (maxWidth === undefined) {
824
- return longest;
825
- }
826
- return Math.min(longest, maxWidth);
827
- }
828
-
829
- /**
830
- * Wrap a table cell to fit into a column.
831
- *
832
- * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
833
- * consistently with the rest of the renderer.
834
- */
835
- private wrapCellText(text: string, maxWidth: number, stylePrefix = ""): string[] {
836
- const lines = wrapTextWithAnsi(text, Math.max(1, maxWidth));
837
- return lines.map((line, index) => {
838
- // Reset text styles after each non-final fragment, then restore the surrounding style before padding and borders.
839
- const styleReset = index < lines.length - 1 ? "\x1b[22;23;24;25;27;28;29;39m" : "";
840
- return `${line}${styleReset}${stylePrefix}`;
841
- });
842
- }
843
-
844
- /**
845
- * Render a table with width-aware cell wrapping.
846
- * Cells that don't fit are wrapped to multiple lines.
847
- */
848
- private renderTable(
849
- token: Tokens.Table,
850
- availableWidth: number,
851
- nextTokenType?: string,
852
- styleContext?: InlineStyleContext,
853
- ): string[] {
854
- const lines: string[] = [];
855
- const numCols = token.header.length;
856
-
857
- if (numCols === 0) {
858
- return lines;
859
- }
860
-
861
- // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
862
- // = 2 + (n-1) * 3 + 2 = 3n + 1
863
- const borderOverhead = 3 * numCols + 1;
864
- const availableForCells = availableWidth - borderOverhead;
865
- if (availableForCells < numCols) {
866
- // Too narrow to render a stable table. Fall back to raw markdown.
867
- const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
868
- if (nextTokenType && nextTokenType !== "space") {
869
- fallbackLines.push("");
870
- }
871
- return fallbackLines;
872
- }
873
-
874
- const maxUnbrokenWordWidth = 30;
875
-
876
- // Calculate natural column widths (what each column needs without constraints)
877
- const naturalWidths: number[] = [];
878
- const minWordWidths: number[] = [];
879
- for (let i = 0; i < numCols; i++) {
880
- const headerText = this.renderInlineTokens(token.header[i].tokens || [], styleContext);
881
- naturalWidths[i] = visibleWidth(headerText);
882
- minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth));
883
- }
884
- for (const row of token.rows) {
885
- for (let i = 0; i < row.length; i++) {
886
- const cellText = this.renderInlineTokens(row[i].tokens || [], styleContext);
887
- naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
888
- minWordWidths[i] = Math.max(
889
- minWordWidths[i] || 1,
890
- this.getLongestWordWidth(cellText, maxUnbrokenWordWidth),
891
- );
892
- }
893
- }
894
-
895
- let minColumnWidths = minWordWidths;
896
- let minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
897
-
898
- if (minCellsWidth > availableForCells) {
899
- minColumnWidths = new Array(numCols).fill(1);
900
- const remaining = availableForCells - numCols;
901
-
902
- if (remaining > 0) {
903
- const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
904
- const growth = minWordWidths.map((width) => {
905
- const weight = Math.max(0, width - 1);
906
- return totalWeight > 0 ? Math.floor((weight / totalWeight) * remaining) : 0;
907
- });
908
-
909
- for (let i = 0; i < numCols; i++) {
910
- minColumnWidths[i] += growth[i] ?? 0;
911
- }
912
-
913
- const allocated = growth.reduce((total, width) => total + width, 0);
914
- let leftover = remaining - allocated;
915
- for (let i = 0; leftover > 0 && i < numCols; i++) {
916
- minColumnWidths[i]++;
917
- leftover--;
918
- }
919
- }
920
-
921
- minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
922
- }
923
-
924
- // Calculate column widths that fit within available width
925
- const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
926
- let columnWidths: number[];
927
-
928
- if (totalNaturalWidth <= availableWidth) {
929
- // Everything fits naturally
930
- columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
931
- } else {
932
- // Need to shrink columns to fit
933
- const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
934
- return total + Math.max(0, width - minColumnWidths[index]);
935
- }, 0);
936
- const extraWidth = Math.max(0, availableForCells - minCellsWidth);
937
- columnWidths = minColumnWidths.map((minWidth, index) => {
938
- const naturalWidth = naturalWidths[index];
939
- const minWidthDelta = Math.max(0, naturalWidth - minWidth);
940
- let grow = 0;
941
- if (totalGrowPotential > 0) {
942
- grow = Math.floor((minWidthDelta / totalGrowPotential) * extraWidth);
943
- }
944
- return minWidth + grow;
945
- });
946
-
947
- // Adjust for rounding errors - distribute remaining space
948
- const allocated = columnWidths.reduce((a, b) => a + b, 0);
949
- let remaining = availableForCells - allocated;
950
- while (remaining > 0) {
951
- let grew = false;
952
- for (let i = 0; i < numCols && remaining > 0; i++) {
953
- if (columnWidths[i] < naturalWidths[i]) {
954
- columnWidths[i]++;
955
- remaining--;
956
- grew = true;
957
- }
958
- }
959
- if (!grew) {
960
- break;
961
- }
962
- }
963
- }
964
-
965
- // Render top border
966
- const topBorderCells = columnWidths.map((w) => "─".repeat(w));
967
- lines.push(`┌─${topBorderCells.join("─┬─")}─┐`);
968
-
969
- // Render header with wrapping
970
- const headerCellLines: string[][] = token.header.map((cell, i) => {
971
- const text = this.renderInlineTokens(cell.tokens || [], styleContext);
972
- return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix);
973
- });
974
- const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
975
-
976
- for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
977
- const rowParts = headerCellLines.map((cellLines, colIdx) => {
978
- const text = cellLines[lineIdx] || "";
979
- const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
980
- return this.theme.bold(padded);
981
- });
982
- lines.push(`│ ${rowParts.join(" │ ")} │`);
983
- }
984
-
985
- // Render separator
986
- const separatorCells = columnWidths.map((w) => "─".repeat(w));
987
- const separatorLine = `├─${separatorCells.join("─┼─")}─┤`;
988
- lines.push(separatorLine);
989
-
990
- // Render rows with wrapping
991
- for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
992
- const row = token.rows[rowIndex];
993
- const rowCellLines: string[][] = row.map((cell, i) => {
994
- const text = this.renderInlineTokens(cell.tokens || [], styleContext);
995
- return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix);
996
- });
997
- const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
998
-
999
- for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
1000
- const rowParts = rowCellLines.map((cellLines, colIdx) => {
1001
- const text = cellLines[lineIdx] || "";
1002
- return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
1003
- });
1004
- lines.push(`│ ${rowParts.join(" │ ")} │`);
1005
- }
1006
-
1007
- if (rowIndex < token.rows.length - 1) {
1008
- lines.push(separatorLine);
1009
- }
1010
- }
1011
-
1012
- // Render bottom border
1013
- const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
1014
- lines.push(`└─${bottomBorderCells.join("─┴─")}─┘`);
1015
-
1016
- if (nextTokenType && nextTokenType !== "space") {
1017
- lines.push(""); // Add spacing after table
1018
- }
1019
- return lines;
1020
- }
1021
- }