Open History to see the last commit
1/**
2 * Compiler-free type-error annotations for code blocks.
3 *
4 * Replaces expressive-code-twoslash's error rendering (the part of twoslash
5 * we actually rely on) without spinning up a TypeScript program per block.
6 * Docs author errors as plain comments inside any fenced code block, so the
7 * MDX source stays readable as code — agents ingesting the raw markdown see
8 * a normal comment stating that (and why) the code fails to compile:
9 *
10 * ```typescript
11 * const providers: Layer<Providers> = Layer.empty;
12 * // @error: ts(2322) Type 'Layer<never, never, never>' is not assignable
13 * // @error: to type 'Layer<NoInfer<Providers>, never, StackServices>'.
14 * ```
15 *
16 * Rules:
17 * - A `// @error:` comment group annotates the nearest preceding code line:
18 * that line gets a red squiggle and the error box renders directly below
19 * it (exactly where the comment sits in the source).
20 * - Consecutive `// @error:` lines merge into one message. Line breaks
21 * collapse when the box renders (white-space: normal), so wrapping long
22 * messages across several comment lines is purely cosmetic in the source.
23 * - A leading `ts(NNNN)` on the first line becomes the box title
24 * ("Error ts(NNNN) ― "), matching the twoslash UI.
25 * - Works inside ```diff lang="typescript" blocks: a leading `+`/`-`/space
26 * diff marker before the comment is tolerated (the comment itself should
27 * be an unchanged/context line).
28 *
29 * The rendered markup and CSS replicate expressive-code-twoslash's error UI
30 * (`.twoslash-error-underline` squiggle + `.twoslash-error-box`), so the
31 * visual output is identical to what the compiler-backed plugin produced.
32 */
33import { ExpressiveCodeAnnotation } from "@astrojs/starlight/expressive-code";
34import { getClassNames, h } from "@astrojs/starlight/expressive-code/hast";
35
36/** Matches `// @error: <text>`, tolerating a leading diff marker. */
37const ERROR_COMMENT = /^(?:[+-](?=[\s/]))?\s*\/\/ @error: ?(.*)$/;
38
39/** Extracts an optional `ts(NNNN)` code from the start of the message. */
40const TS_CODE = /^ts\((\d+)\):?\s*/;
41
42/** The line's token container (`.code` child), or the node itself. */
43function codeContainer(node) {
44 return (
45 node.children?.find(
46 (c) => c.type === "element" && getClassNames(c).includes("code"),
47 ) ?? node
48 );
49}
50
51class ErrorUnderlineAnnotation extends ExpressiveCodeAnnotation {
52 render({ nodesToTransform }) {
53 return nodesToTransform.map((node) => {
54 if (node.type !== "element") return node;
55 // Wrap the line's tokens in a squiggle span rather than classing the
56 // container: the error box is appended to the same container below,
57 // and `text-decoration` propagates to descendants (it can't be
58 // cancelled from inside), so the box must be a sibling of the
59 // underlined span, not its child.
60 const code = codeContainer(node);
61 code.children = [
62 h("span.twoslash.twoslash-error-underline", code.children ?? []),
63 ];
64 return node;
65 });
66 }
67}
68
69class ErrorBoxAnnotation extends ExpressiveCodeAnnotation {
70 constructor(title, message) {
71 super({ renderPhase: "latest" });
72 this.title = title;
73 this.message = message;
74 }
75 render({ nodesToTransform }) {
76 return nodesToTransform.map((node) => {
77 if (node.type !== "element") return node;
78 // Append inside `.code` (a block container): a block-level flex box
79 // after inline token content renders on its own line below the code,
80 // exactly like twoslash's markup did. Appending to the `.ec-line`
81 // instead puts the box on the same flex row as the code.
82 codeContainer(node).children.push(
83 h("div.twoslash-error-box.twoslash-error-level-error", [
84 h("span.twoslash-error-box-icon"),
85 h("span.twoslash-error-box-content", [
86 ...(this.title
87 ? [h("span.twoslash-error-box-content-title", this.title)]
88 : []),
89 h("span.twoslash-error-box-content-message", this.message),
90 ]),
91 ]),
92 );
93 return node;
94 });
95 }
96}
97
98export function errorAnnotations() {
99 return {
100 name: "error-annotations",
101 baseStyles: `
102 .twoslash-error-underline {
103 text-decoration-line: spelling-error;
104 position: relative;
105 }
106 .twoslash-error-box {
107 display: flex;
108 z-index: 10;
109 padding: 0.1rem 0.3rem;
110 font-style: italic;
111 border: 1px solid rgba(from var(--al-error-col, #cd3131) r g b / 0.25);
112 border-radius: 4px;
113 font-size: 90%;
114 white-space: normal;
115 word-break: normal;
116 overflow-wrap: normal;
117 flex: 0 1 100%;
118 color: var(--al-error-col, #cd3131);
119 background: rgba(from var(--al-error-col, #cd3131) r g b / 0.1);
120 }
121 .twoslash-error-box .twoslash-error-box-icon {
122 display: inline-block;
123 vertical-align: middle;
124 }
125 .twoslash-error-box .twoslash-error-box-content {
126 display: inline-block;
127 vertical-align: middle;
128 flex: 0 1 100%;
129 }
130 .twoslash-error-box-content-message {
131 white-space: normal;
132 }
133 `,
134 hooks: {
135 preprocessCode({ codeBlock }) {
136 const lines = codeBlock.getLines();
137 /** @type {{ target: number, deletions: number[], parts: string[] }[]} */
138 const groups = [];
139 let current;
140 for (let i = 0; i < lines.length; i++) {
141 const match = lines[i].text.match(ERROR_COMMENT);
142 if (!match) {
143 current = undefined;
144 continue;
145 }
146 if (current) {
147 current.deletions.push(i);
148 current.parts.push(match[1]);
149 } else if (i > 0) {
150 current = { target: i - 1, deletions: [i], parts: [match[1]] };
151 groups.push(current);
152 }
153 }
154 if (groups.length === 0) return;
155
156 // Delete the comment lines (bottom-up so indices stay valid), then
157 // annotate each group's target line. Targets never move: a group's
158 // target always precedes its own deletions, and later groups'
159 // deletions never precede an earlier group's target.
160 const deleted = groups.flatMap((g) => g.deletions);
161 codeBlock.deleteLines(deleted);
162 for (const group of groups) {
163 const shift = deleted.filter((d) => d < group.target).length;
164 const line = codeBlock.getLine(group.target - shift);
165 if (!line) continue;
166 let message = group.parts.join("\n");
167 let title;
168 const code = message.match(TS_CODE);
169 if (code) {
170 title = `Error ts(${code[1]}) ― `;
171 message = message.slice(code[0].length);
172 }
173 line.addAnnotation(new ErrorUnderlineAnnotation({}));
174 line.addAnnotation(new ErrorBoxAnnotation(title, message));
175 }
176 },
177 },
178 };
179}