pi-syntax-highlight 0.0.0-stage → 0.1.1

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 (52) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/DEVELOPER.md +73 -0
  3. package/README.md +65 -2
  4. package/assets/icon.png +0 -0
  5. package/assets/icon.svg +36 -0
  6. package/extensions/index.ts +22 -0
  7. package/package.json +49 -4
  8. package/src/active-theme.ts +26 -0
  9. package/src/detect-language.ts +294 -0
  10. package/src/emphasis.ts +160 -0
  11. package/src/grep-parse.ts +42 -0
  12. package/src/highlight.ts +109 -0
  13. package/src/markdown-fence-lang.ts +180 -0
  14. package/src/markdown-style.ts +134 -0
  15. package/src/markdown-theme.ts +53 -0
  16. package/src/render-bash.ts +180 -0
  17. package/src/render-edit.ts +207 -0
  18. package/src/render-find.ts +64 -0
  19. package/src/render-generic.ts +86 -0
  20. package/src/render-grep.ts +142 -0
  21. package/src/render-ls.ts +66 -0
  22. package/src/render-path.ts +54 -0
  23. package/src/render-read.ts +277 -0
  24. package/src/render-utils.ts +219 -0
  25. package/src/render-write.ts +81 -0
  26. package/src/resolve-renderers.ts +406 -0
  27. package/src/style-path.ts +48 -0
  28. package/src/tokens.ts +114 -0
  29. package/test/unit/active-theme.test.ts +38 -0
  30. package/test/unit/bash-preview.test.ts +57 -0
  31. package/test/unit/detect-language.test.ts +124 -0
  32. package/test/unit/emphasis.test.ts +113 -0
  33. package/test/unit/extensions-index.test.ts +116 -0
  34. package/test/unit/grep-parse.test.ts +125 -0
  35. package/test/unit/highlight.test.ts +107 -0
  36. package/test/unit/markdown-fence-lang.test.ts +131 -0
  37. package/test/unit/markdown-pipeline.test.ts +153 -0
  38. package/test/unit/markdown-render-parity.test.ts +127 -0
  39. package/test/unit/markdown-style.test.ts +152 -0
  40. package/test/unit/markdown-theme.test.ts +86 -0
  41. package/test/unit/render-bash.test.ts +194 -0
  42. package/test/unit/render-edit.test.ts +214 -0
  43. package/test/unit/render-find.test.ts +139 -0
  44. package/test/unit/render-generic.test.ts +152 -0
  45. package/test/unit/render-grep.test.ts +338 -0
  46. package/test/unit/render-ls.test.ts +132 -0
  47. package/test/unit/render-read.test.ts +375 -0
  48. package/test/unit/render-utils.test.ts +324 -0
  49. package/test/unit/render-write.test.ts +143 -0
  50. package/test/unit/resolve-renderers.test.ts +474 -0
  51. package/test/unit/style-path.test.ts +74 -0
  52. package/tsconfig.json +15 -0
@@ -0,0 +1,180 @@
1
+ import type { MarkdownTransformer } from "@earendil-works/pi-coding-agent";
2
+ import { detectLanguage } from "./detect-language.ts";
3
+ import { markdownPalette, type MarkdownPalette } from "./markdown-theme.ts";
4
+ import { styleMarkdown } from "./markdown-style.ts";
5
+ import type { AnsiTheme } from "./tokens.ts";
6
+
7
+ // Fences the built-in mermaid transformer already consumed: by the
8
+ // time this transformer runs, that one has rewritten the block, and guessing a
9
+ // language from a diagram body would repaint it as something else entirely.
10
+ const RESERVED_INFO = new Set(["mermaid", "math", "latex", "katex"]);
11
+
12
+ // CommonMark allows up to three spaces of indentation; four spaces open an
13
+ // indented code block and a blockquote prefix is not a fence at all, so neither
14
+ // matches here and both are copied untouched.
15
+ const OPENING_FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
16
+
17
+ // Exported so the styling pass scans fences with the very same grammar instead of
18
+ // keeping a second copy of it: two scanners would eventually disagree about what a
19
+ // fence is, and the disagreement would paint body text as markdown.
20
+ export interface OpeningFence {
21
+ indent: string;
22
+ fence: string;
23
+ info: string;
24
+ }
25
+
26
+ // The info string carries either the language, an attribute list such as
27
+ // `{.ts}`, or the language followed by attributes such as `js title="a"`.
28
+ // A token the author wrote is returned as it is: rewriting a correctly labeled
29
+ // fence is a visible difference, and an unknown name is still their choice. Only
30
+ // an unlabeled fence is worth a guess.
31
+ export function normalizeInfoString(info: string, body: string): string {
32
+ return normalizeToken(cleanInfoToken(info), body);
33
+ }
34
+
35
+ // Only the opening line of a closed fence is rewritten; an open fence is still
36
+ // arriving, so its body is only a prefix of the final one.
37
+ export function transformFenceLanguages(markdown: string): string {
38
+ const lines = markdown.split("\n");
39
+ const output: string[] = [];
40
+ let index = 0;
41
+ while (index < lines.length) {
42
+ const opening = parseOpeningFence(lines[index]);
43
+ if (opening === undefined) {
44
+ appendLines(output, lines, index, index);
45
+ index += 1;
46
+ continue;
47
+ }
48
+ const closing = findClosingFence(lines, index + 1, opening);
49
+ if (closing === undefined) {
50
+ // An unclosed fence is a message still arriving, so its body is only a
51
+ // prefix of the final one and any guess would change as the stream grows.
52
+ // The missing closing line is the whole condition, and it stays true after
53
+ // the stream ends.
54
+ appendLines(output, lines, index, lines.length - 1);
55
+ break;
56
+ }
57
+ output.push(rewriteOpeningFence(lines[index], opening, lines.slice(index + 1, closing).join("\n")));
58
+ appendLines(output, lines, index + 1, closing);
59
+ index = closing + 1;
60
+ }
61
+ return output.join("\n");
62
+ }
63
+
64
+ export interface MarkdownTransformerOptions {
65
+ // Read at render time rather than captured at load time: the extension registers
66
+ // before any session exists, and the object the host hands out is a proxy whose
67
+ // reads resolve against the theme in effect, so one captured reference stays
68
+ // valid across a theme switch.
69
+ resolveTheme: () => AnsiTheme | undefined;
70
+ }
71
+
72
+ // `Markdown.render` invokes the transformer on every cache miss, and a resize or
73
+ // a theme change invalidates that cache, so the same markdown arrives again and
74
+ // again. One entry is enough: the transcript renders one message at a time. The
75
+ // key carries the palette signature because a theme switch changes the output
76
+ // without changing the input; the width is not part of it because no stage reads it.
77
+ export function createMarkdownTransformer(options: MarkdownTransformerOptions): MarkdownTransformer {
78
+ let memo: { input: string; signature: string; output: string } | undefined;
79
+ return (markdown, context) => {
80
+ // Only assistant prose is styled: a user message renders its backslash escapes
81
+ // verbatim (`user-message.js` sets `preserveBackslashEscapes`), which would make
82
+ // the restored code-span delimiters visible, and thinking text is painted with an
83
+ // italic default style this pass would degrade.
84
+ const palette = context.messageType === "assistant" ? paletteOrUndefined(options.resolveTheme) : undefined;
85
+ const signature = palette?.signature ?? "";
86
+ if (memo !== undefined && memo.input === markdown && memo.signature === signature) return memo.output;
87
+ let output = markdown;
88
+ try {
89
+ output = transformFenceLanguages(markdown);
90
+ } catch {
91
+ // A fence this module cannot parse must not take the message down: the
92
+ // original markdown still renders with flat colors.
93
+ output = markdown;
94
+ }
95
+ if (palette !== undefined) {
96
+ try {
97
+ output = styleMarkdown(output, palette);
98
+ } catch {
99
+ // Styling is the optional half of the pipeline: the fence labels above are
100
+ // already in `output` and stay, so a failure costs the colors and nothing else.
101
+ }
102
+ }
103
+ memo = { input: markdown, signature, output };
104
+ return output;
105
+ };
106
+ }
107
+
108
+ // The derivation is the one step that can fail: `resolveTheme` answers `undefined`
109
+ // before a theme is captured, and the host's theme throws while uninitialized
110
+ // (`theme.js` reads `globalThis` and throws when nothing is installed). Neither may
111
+ // reach the renderer, so no palette means no styling instead of no message.
112
+ function paletteOrUndefined(resolveTheme: () => AnsiTheme | undefined): MarkdownPalette | undefined {
113
+ try {
114
+ const theme = resolveTheme();
115
+ return theme === undefined ? undefined : markdownPalette(theme);
116
+ } catch {
117
+ return undefined;
118
+ }
119
+ }
120
+
121
+ function rewriteOpeningFence(line: string, opening: OpeningFence, body: string): string {
122
+ const token = cleanInfoToken(opening.info);
123
+ if (RESERVED_INFO.has(token.toLowerCase())) return line;
124
+ const language = normalizeToken(token, body);
125
+ if (language === opening.info) return line;
126
+ return `${opening.indent}${opening.fence}${language}`;
127
+ }
128
+
129
+ export function parseOpeningFence(line: string): OpeningFence | undefined {
130
+ const matched = OPENING_FENCE.exec(line);
131
+ if (matched === null) return undefined;
132
+ const fence = matched[2] ?? "";
133
+ const info = (matched[3] ?? "").trim();
134
+ // CommonMark forbids the fence character inside the info string of its own
135
+ // fence, so such a line opens nothing and the rest of the message is copied:
136
+ // it is prose that happens to start with three ticks or tildes.
137
+ if (info.includes(fence.charAt(0))) return undefined;
138
+ return { indent: matched[1] ?? "", fence, info };
139
+ }
140
+
141
+ function findClosingFence(lines: readonly string[], start: number, opening: OpeningFence): number | undefined {
142
+ for (let index = start; index < lines.length; index += 1) {
143
+ if (isClosingFence(lines[index], opening)) return index;
144
+ }
145
+ return undefined;
146
+ }
147
+
148
+ // A closing fence is the opening character repeated at least as many times as the
149
+ // opener, indented at most three spaces, with nothing but spaces after it.
150
+ export function isClosingFence(line: string, opening: OpeningFence): boolean {
151
+ return closingFencePattern(opening).test(line);
152
+ }
153
+
154
+ // The only fence characters are a backtick and a tilde (the opening pattern
155
+ // admits nothing else) and neither is special in a regular expression.
156
+ function closingFencePattern(opening: OpeningFence): RegExp {
157
+ const character = opening.fence.charAt(0);
158
+ return new RegExp(`^ {0,3}${character}{${opening.fence.length},} *$`);
159
+ }
160
+
161
+ // A loop instead of `push(...slice)` because a fence body can be arbitrarily
162
+ // long and spreading it would hit the argument limit.
163
+ function appendLines(target: string[], source: readonly string[], start: number, end: number): void {
164
+ for (const line of source.slice(start, end + 1)) target.push(line);
165
+ }
166
+
167
+ // Detection only fills a gap: a label the author wrote is returned whatever the
168
+ // body looks like.
169
+ function normalizeToken(token: string, body: string): string {
170
+ if (token !== "") return token;
171
+ return detectLanguage(body) ?? "";
172
+ }
173
+
174
+ function cleanInfoToken(info: string): string {
175
+ const first = info.trim().split(/\s+/)[0] ?? "";
176
+ // `{.ts}`, `{ts,}`, and a bare `.ts` name the same language; the attributes
177
+ // after the language (`js title="a"`) were cut by the split.
178
+ const unwrapped = first.startsWith("{") ? first.slice(1) : first;
179
+ return unwrapped.replace(/^\.+/, "").replace(/[`,}]+$/, "");
180
+ }
@@ -0,0 +1,134 @@
1
+ import { isClosingFence, parseOpeningFence, type OpeningFence } from "./markdown-fence-lang.ts";
2
+ import type { MarkdownPalette } from "./markdown-theme.ts";
3
+ import { FG_DEFAULT, ITALIC_OFF, ITALIC_ON, UNDERLINE_OFF, UNDERLINE_ON } from "./tokens.ts";
4
+
5
+ // CommonMark allows up to three spaces before a block marker. The text after the
6
+ // marker is required: a bare `## ` is a heading still arriving while the message
7
+ // streams, and wrapping an empty span would only add sequences around nothing.
8
+ const HEADING = /^( {0,3})(#{1,6})([ \t]+)(.*)$/;
9
+
10
+ // The `>` run is captured whole so a nested quote keeps every marker exactly where
11
+ // the renderer expects to find it before it prepends its own border.
12
+ const QUOTE = /^( {0,3})((?:>[ \t]?)+)(.*)$/;
13
+
14
+ // The pass writes its own escapes, and the mermaid transformer that runs before it
15
+ // may have written some too. A line that already carries one is copied verbatim:
16
+ // that single guard is what makes a second run over the same text a no-op, and
17
+ // what keeps a diagram from being restyled as a blockquote.
18
+ const ESCAPE = "\u001b";
19
+
20
+ // A backtick preceded by a backslash: the escape a code span needs, and also the
21
+ // escape the pass itself emits, so a line carrying one is never rewritten twice.
22
+ // Rewriting half of it would turn visible text into markup, and the same guard
23
+ // covers a span whose text ends in a backslash, because the tick after that
24
+ // backslash is escaped too.
25
+ const ESCAPED_BACKTICK = "\\`";
26
+
27
+ // The delimiters the renderer drops from a code span, re-emitted escaped so
28
+ // `marked` hands them back as text and they take the style of their context.
29
+ const RESTORED_BACKTICK = ESCAPED_BACKTICK;
30
+
31
+ // The host already paints every heading bold, so the level is told apart by one
32
+ // attribute that survives the host's own prefixes: h1 and h3 take italic, h2
33
+ // underline, and h4-h6 nothing, since the renderer prints their `#` prefix
34
+ // visibly and that is distinction enough.
35
+ const ITALIC = { on: ITALIC_ON, off: ITALIC_OFF };
36
+ const UNDERLINE = { on: UNDERLINE_ON, off: UNDERLINE_OFF };
37
+
38
+ // Styles the constructs the transformer alone can reach, leaving every visible
39
+ // character where it was: headings and blockquote lines get their sequences inside
40
+ // the line, and the delimiters of an inline code span come back as escaped text.
41
+ // Fences are the one place both stages agree not to touch (see `markdown-fence-lang`).
42
+ export function styleMarkdown(markdown: string, palette: MarkdownPalette): string {
43
+ const lines = markdown.split("\n");
44
+ const output: string[] = [];
45
+ let opening: OpeningFence | undefined;
46
+ for (const line of lines) {
47
+ if (opening !== undefined) {
48
+ // Inside a fence every line is literal body, closing line included.
49
+ output.push(line);
50
+ if (isClosingFence(line, opening)) opening = undefined;
51
+ continue;
52
+ }
53
+ const fence = parseOpeningFence(line);
54
+ if (fence !== undefined) {
55
+ output.push(line);
56
+ opening = fence;
57
+ continue;
58
+ }
59
+ if (line.includes(ESCAPE)) {
60
+ output.push(line);
61
+ continue;
62
+ }
63
+ output.push(styleLine(restoreInlineCode(line), palette));
64
+ }
65
+ return output.join("\n");
66
+ }
67
+
68
+ // Headings and quote markers are mutually exclusive (`#` and `>` cannot start the
69
+ // same line), so the order only documents which construct owns the line.
70
+ function styleLine(line: string, palette: MarkdownPalette): string {
71
+ const heading = HEADING.exec(line);
72
+ if (heading !== null) {
73
+ const text = heading[4] ?? "";
74
+ if (text !== "") {
75
+ const attribute = headingAttribute((heading[2] ?? "").length);
76
+ const open = palette.accent + (attribute?.on ?? "");
77
+ if (open === "") return line;
78
+ // Closed in reverse order: the attribute first, then the color it borrowed.
79
+ const close = (attribute?.off ?? "") + (palette.accent === "" ? "" : FG_DEFAULT);
80
+ return `${heading[1] ?? ""}${heading[2] ?? ""}${heading[3] ?? ""}${open}${text}${close}`;
81
+ }
82
+ }
83
+ if (palette.quoteOpen === "") return line;
84
+ const quote = QUOTE.exec(line);
85
+ if (quote === null) return line;
86
+ const text = quote[3] ?? "";
87
+ // A quote line with no text is the blank line between two quote paragraphs: the
88
+ // host prints it empty, so there is nothing to color and no pair to add.
89
+ if (text === "") return line;
90
+ return `${quote[1] ?? ""}${quote[2] ?? ""}${palette.quoteOpen}${text}${palette.quoteClose}`;
91
+ }
92
+
93
+ function headingAttribute(level: number): { on: string; off: string } | undefined {
94
+ if (level === 1 || level === 3) return ITALIC;
95
+ if (level === 2) return UNDERLINE;
96
+ return undefined;
97
+ }
98
+
99
+ // The renderer prints a code span without its backticks (`markdown.js` styles
100
+ // `token.text` only), so the delimiters come back as escaped text. Nothing is
101
+ // injected: the delimiters inherit the style of the context they sit in, which
102
+ // degrades nothing inside a link, a heading or a table cell.
103
+ function restoreInlineCode(line: string): string {
104
+ if (line.includes(ESCAPED_BACKTICK)) return line;
105
+ let output = "";
106
+ let index = 0;
107
+ while (index < line.length) {
108
+ const open = singleBacktickAt(line, index);
109
+ if (open === -1) return output + line.slice(index);
110
+ const close = singleBacktickAt(line, open + 1);
111
+ // Half a pair is a span still arriving: the line stays as it is until the
112
+ // closing tick shows up, which is the same moment the renderer turns it into a
113
+ // code span.
114
+ if (close === -1) return line;
115
+ const text = line.slice(open + 1, close);
116
+ // A span holding a double tick is a multi-backtick delimiter this pass does not
117
+ // model. An empty span cannot reach here (`singleBacktickAt` refuses a run of
118
+ // two), and the check stays as the invariant the pair is written under.
119
+ if (text === "" || text.includes("``")) return line;
120
+ output += line.slice(index, open) + RESTORED_BACKTICK + text + RESTORED_BACKTICK;
121
+ index = close + 1;
122
+ }
123
+ return output;
124
+ }
125
+
126
+ // Returns the index of the next backtick that stands alone, or -1. A run of two or
127
+ // more is a different delimiter, so it is skipped rather than taken as an edge.
128
+ function singleBacktickAt(line: string, from: number): number {
129
+ for (let index = line.indexOf("`", from); index !== -1; index = line.indexOf("`", index + 1)) {
130
+ if (line[index - 1] === "`" || line[index + 1] === "`") continue;
131
+ return index;
132
+ }
133
+ return -1;
134
+ }
@@ -0,0 +1,53 @@
1
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import { type AnsiTheme, DIM_OFF, DIM_ON, FG_DEFAULT, MD_TOKEN } from "./tokens.ts";
3
+
4
+ // The heading foreground. One token for all six levels on purpose: the level is
5
+ // told apart by an SGR attribute in `markdown-style.ts`, so retheming cannot make
6
+ // two levels of the same document drift into two unrelated colors.
7
+ const ACCENT_TOKEN: ThemeColor = "accent";
8
+
9
+ // The few sequences the markdown pass injects, derived from the theme once per
10
+ // render. The host's markdown theme is not extensible, so this is the palette the
11
+ // pass paints with instead of `fg()`, which wraps a whole string and therefore
12
+ // cannot recolor a span inside a line the host already painted.
13
+ export interface MarkdownPalette {
14
+ // What every heading opens with; "" when the theme gives the token no color of
15
+ // its own, which is the signal to inject nothing at all.
16
+ accent: string;
17
+ // The quote pair has to undo what the host paints itself: `mdQuote` may be
18
+ // faint, so opening the quote turns that off first and closing restores it.
19
+ quoteOpen: string;
20
+ quoteClose: string;
21
+ // Value key of the transformer memo, derived from the sequences above and
22
+ // nothing else: a theme switch that does not move them leaves the previous
23
+ // render valid, which is exactly right because the bytes would be identical.
24
+ signature: string;
25
+ }
26
+
27
+ export function markdownPalette(theme: AnsiTheme): MarkdownPalette {
28
+ const accent = ownFg(theme, ACCENT_TOKEN);
29
+ // The host paints blockquote text through `mdQuote`, and its faint flag is what
30
+ // `\x1b[22m` closes. That is also the one sequence of the pass that closes bold
31
+ // along with dim, which is safe only here: the host applies no bold to quote text.
32
+ const quoteIsDim = theme.getFgAnsi("mdQuote").includes(DIM_ON);
33
+ const quoteFg = ownFg(theme, MD_TOKEN.quote);
34
+ // Without a color of its own the construct has nothing to say, so the pair stays
35
+ // empty rather than cancelling and re-applying the host's own style.
36
+ const quoteOpen = quoteFg === "" ? "" : (quoteIsDim ? DIM_OFF : "") + quoteFg;
37
+ const quoteClose = quoteFg === "" ? "" : FG_DEFAULT + (quoteIsDim ? DIM_ON : "");
38
+ return {
39
+ accent,
40
+ quoteOpen,
41
+ quoteClose,
42
+ signature: [accent, quoteOpen, quoteClose].join("\u0000"),
43
+ };
44
+ }
45
+
46
+ // A token the theme maps to the terminal default ("" or `\x1b[39m` in the host's
47
+ // `Theme`) is not a color this pass can add: injecting it would wrap the text in
48
+ // sequences that only cancel each other, which is precisely what a monochrome
49
+ // terminal must not receive.
50
+ function ownFg(theme: AnsiTheme, token: ThemeColor): string {
51
+ const ansi = theme.getFgAnsi(token);
52
+ return ansi === "" || ansi === FG_DEFAULT ? "" : ansi;
53
+ }
@@ -0,0 +1,180 @@
1
+ import { truncateToVisualLines } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, type Component } from "@earendil-works/pi-tui";
3
+ import { parseGrepLine } from "./grep-parse.ts";
4
+ import { highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
5
+ import { DIFF_HEADER, colonPrefix, isJsonDocument, styleDiffLine, truncationWarnings } from "./render-utils.ts";
6
+ import { TOKEN, type StyleTheme } from "./tokens.ts";
7
+
8
+ // The built-in shell renderer keeps five visual lines when collapsed; any other
9
+ // number is a visible difference against stock pi.
10
+ const PREVIEW_LINES = 5;
11
+
12
+ // The built-in separates its "[Full output: ...]" block with a blank line, which
13
+ // is what keeps the strip from eating body text that merely ends in "]".
14
+ const FULL_OUTPUT_SEPARATOR = "\n\n[";
15
+
16
+ const DIFF_HUNK = /^@@ /;
17
+ const DIFF_CHANGE = /^[+-]/;
18
+ const ERROR_LINE = /^(error|fatal|panic|traceback|ERR!)/i;
19
+ const WARNING_LINE = /^(warning|warn)\b/i;
20
+
21
+ export interface BashInput {
22
+ output: string;
23
+ details:
24
+ | {
25
+ truncation?: {
26
+ truncated?: boolean;
27
+ truncatedBy?: "lines" | "bytes";
28
+ outputLines?: number;
29
+ totalLines?: number;
30
+ maxBytes?: number;
31
+ };
32
+ fullOutputPath?: string;
33
+ }
34
+ | undefined;
35
+ durationMs: number | undefined;
36
+ /**
37
+ * A streaming result: the host keeps the full-output block in the body and the
38
+ * builder prints no timer, so the elapsed line stays with the live renderer.
39
+ */
40
+ isPartial?: boolean;
41
+ theme: StyleTheme;
42
+ /** Injected in tests: `highlightCode` paints through the module-global theme. */
43
+ highlight?: HighlightFn;
44
+ }
45
+
46
+ export interface BashBody {
47
+ /** Styled body, without the leading newline the component wrapper adds. */
48
+ body: string;
49
+ /** Bracketed warning text, without the brackets. */
50
+ warnings?: string;
51
+ /** Duration text, without the "Took " prefix. */
52
+ timer?: string;
53
+ }
54
+
55
+ // Byte-identical to the built-in `formatToolDuration`: a diff here is a visible
56
+ // difference in the timer line, and `60.0s` at 59.999 ms is intended behavior.
57
+ export function formatDuration(ms: number): string {
58
+ const seconds = ms / 1000;
59
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
60
+ const totalSeconds = Math.floor(seconds);
61
+ const minutes = Math.floor(totalSeconds / 60);
62
+ const remainder = totalSeconds % 60;
63
+ return minutes < 60
64
+ ? `${minutes}m ${remainder}s`
65
+ : `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;
66
+ }
67
+
68
+ // A diff is recognized by its header plus a hunk marker or several changed
69
+ // lines: a log line that merely starts with "--- " must not paint red/green.
70
+ function isDiffOutput(lines: string[]): boolean {
71
+ const first = lines.find((line) => line.trim() !== "");
72
+ if (first === undefined || !DIFF_HEADER.test(first)) return false;
73
+ let hunks = 0;
74
+ let changes = 0;
75
+ for (const line of lines) {
76
+ if (DIFF_HUNK.test(line)) hunks += 1;
77
+ else if (DIFF_CHANGE.test(line)) changes += 1;
78
+ }
79
+ return hunks > 0 || changes > 1;
80
+ }
81
+
82
+ // Commands that print compiler or test output repeat grep's "path:line: text"
83
+ // shape, so it is parsed with the same function instead of a second regex.
84
+ function styleLine(line: string, theme: StyleTheme): string {
85
+ if (ERROR_LINE.test(line)) return theme.fg(TOKEN.broken, line);
86
+ if (WARNING_LINE.test(line)) return theme.fg(TOKEN.notice, line);
87
+ const entry = parseGrepLine(line);
88
+ if (entry.kind !== "match") return theme.fg(TOKEN.content, line);
89
+ const path = theme.fg(TOKEN.path, entry.path);
90
+ return `${colonPrefix(path, entry.line, theme)} ${theme.fg(TOKEN.content, entry.text)}`;
91
+ }
92
+
93
+ function styleOutput(output: string, theme: StyleTheme, highlight: HighlightFn): string {
94
+ const lines = output.split("\n");
95
+ if (isDiffOutput(lines)) return lines.map((line) => styleDiffLine(line, theme)).join("\n");
96
+ if (isJsonDocument(output)) {
97
+ // Whole-block highlighting keeps keys, strings and numbers distinct; the
98
+ // fallback protects readers when the tokenizer throws.
99
+ const fallback = (line: string): string => theme.fg(TOKEN.content, line);
100
+ return highlightLines(output, "json", fallback, highlight).join("\n");
101
+ }
102
+ return lines.map((line) => styleLine(line, theme)).join("\n");
103
+ }
104
+
105
+ type BashTruncation = NonNullable<NonNullable<BashInput["details"]>["truncation"]>;
106
+
107
+ // Same wording as the built-in renderer, including the byte limit it falls back
108
+ // to when the host did not record one. The built-in treats a missing
109
+ // `truncatedBy` as byte truncation, so the default is spelled out here.
110
+ function truncationText(truncation: BashTruncation): string {
111
+ return truncationWarnings({
112
+ truncatedBy: truncation.truncatedBy ?? "bytes",
113
+ outputLines: truncation.outputLines,
114
+ totalLines: truncation.totalLines,
115
+ maxBytes: truncation.maxBytes,
116
+ }).join(". ");
117
+ }
118
+
119
+ // The built-in moves the trailing "[Full output: ...]" block out of the body and
120
+ // rebuilds it as a warning, so the path is not shown twice. A partial result may
121
+ // still be rewritten by the tool, so the block stays in place exactly as the
122
+ // built-in does (`!options.isPartial`), and its own blank line is the only
123
+ // separator that can start the block.
124
+ function stripFullOutputBlock(output: string, details: BashInput["details"], isPartial: boolean): string {
125
+ const truncation = details?.truncation;
126
+ const fullOutputPath = details?.fullOutputPath;
127
+ if (isPartial || !truncation?.truncated || !fullOutputPath || !output.endsWith("]")) return output;
128
+ const blockStart = output.lastIndexOf(FULL_OUTPUT_SEPARATOR);
129
+ if (blockStart === -1 || !output.slice(blockStart).includes(fullOutputPath)) return output;
130
+ return output.slice(0, blockStart).trimEnd();
131
+ }
132
+
133
+ // A partial result prints no timer: the elapsed line belongs to the live
134
+ // renderer.
135
+ export function buildBashBody(input: BashInput): BashBody {
136
+ const truncation = input.details?.truncation;
137
+ const fullOutputPath = input.details?.fullOutputPath;
138
+ const output = stripFullOutputBlock(input.output.trim(), input.details, input.isPartial === true);
139
+
140
+ const body = output === "" ? "" : styleOutput(output, input.theme, input.highlight ?? builtInHighlight);
141
+
142
+ const warnings: string[] = [];
143
+ if (fullOutputPath) warnings.push(`Full output: ${fullOutputPath}`);
144
+ if (truncation?.truncated) warnings.push(`Truncated: ${truncationText(truncation)}`);
145
+
146
+ return {
147
+ body,
148
+ warnings: warnings.length === 0 ? undefined : warnings.join(". "),
149
+ timer: input.isPartial || input.durationMs === undefined ? undefined : formatDuration(input.durationMs),
150
+ };
151
+ }
152
+
153
+ // Collapsed shell output is cut by visual line, not by logical line: a single
154
+ // long line (minified JSON, a build log without newlines) would otherwise fill
155
+ // the screen. The lines are cached per width because a component re-renders on
156
+ // every frame of the transcript.
157
+ export function createBashPreview(body: string, expandHint: string, theme: StyleTheme): Component {
158
+ let cachedWidth: number | undefined;
159
+ let cachedLines: string[] | undefined;
160
+ return {
161
+ render(width: number): string[] {
162
+ if (cachedLines !== undefined && cachedWidth === width) return cachedLines;
163
+ const { visualLines, skippedCount } = truncateToVisualLines(body, PREVIEW_LINES, width, 0, "end");
164
+ const lines = visualLines.map((line) => truncateToWidth(line, width));
165
+ if (skippedCount > 0) {
166
+ // Same hint format as the built-in preview, above the kept tail.
167
+ const hint = `${theme.fg("muted", `... (${skippedCount} earlier lines,`)} ${expandHint}${theme.fg("muted", ")")}`;
168
+ cachedLines = [truncateToWidth(hint, width), ...lines];
169
+ } else {
170
+ cachedLines = lines;
171
+ }
172
+ cachedWidth = width;
173
+ return cachedLines;
174
+ },
175
+ invalidate(): void {
176
+ cachedWidth = undefined;
177
+ cachedLines = undefined;
178
+ },
179
+ };
180
+ }