@mandujs/core 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mandujs/core",
3
- "version": "0.49.0",
3
+ "version": "0.51.0",
4
4
  "description": "Mandu Framework Core - Spec, Generator, Guard, Runtime",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Issue #245 M3 — Tailwind v4 `@theme` compiler tests.
3
+ *
4
+ * Pin the contract every other tool (CLI sync, MCP discovery,
5
+ * dev-mode watcher) depends on:
6
+ *
7
+ * - DESIGN.md tokens → CSS variable naming (Tailwind v4 convention).
8
+ * - Slug normalisation handles the human-friendly names DESIGN.md
9
+ * authors actually write.
10
+ * - Markered region merge preserves user-edited regions.
11
+ * - Conflicts surface explicitly so the user can reconcile.
12
+ */
13
+
14
+ import { describe, it, expect } from "bun:test";
15
+ import { parseDesignMd } from "../parser";
16
+ import {
17
+ compileTailwindTheme,
18
+ mergeThemeIntoCss,
19
+ slugifyTokenName,
20
+ stripMarkeredBlock,
21
+ THEME_MARKER_END,
22
+ THEME_MARKER_START,
23
+ } from "../tailwind-theme";
24
+
25
+ describe("slugifyTokenName", () => {
26
+ it("kebab-cases multi-word names", () => {
27
+ expect(slugifyTokenName("Hot Peach")).toBe("hot-peach");
28
+ expect(slugifyTokenName("Body Small")).toBe("body-small");
29
+ expect(slugifyTokenName("h1 hero")).toBe("h1-hero");
30
+ });
31
+
32
+ it("collapses runs of whitespace and underscores", () => {
33
+ expect(slugifyTokenName("primary color")).toBe("primary-color");
34
+ expect(slugifyTokenName("warm_cream")).toBe("warm-cream");
35
+ });
36
+
37
+ it("strips characters that aren't word/space/dash", () => {
38
+ expect(slugifyTokenName("primary!")).toBe("primary");
39
+ expect(slugifyTokenName("orange (500)")).toBe("orange-500");
40
+ });
41
+
42
+ it("lowercases ASCII", () => {
43
+ expect(slugifyTokenName("Primary")).toBe("primary");
44
+ });
45
+ });
46
+
47
+ describe("compileTailwindTheme — color palette", () => {
48
+ it("emits --color-<slug> per token", () => {
49
+ const spec = parseDesignMd(`# Test
50
+ ## Color Palette
51
+ - Primary — #FF8C42 — brand accent
52
+ - Surface — #FFF8F0 — neutral background
53
+ `);
54
+ const compiled = compileTailwindTheme(spec);
55
+ const vars = compiled.entries.map((e) => [e.variable, e.value]);
56
+ expect(vars).toContainEqual(["--color-primary", "#FF8C42"]);
57
+ expect(vars).toContainEqual(["--color-surface", "#FFF8F0"]);
58
+ });
59
+
60
+ it("warns and skips tokens with no parseable value", () => {
61
+ const spec = parseDesignMd(`# Test
62
+ ## Color Palette
63
+ - Primary — see Stripe brand docs
64
+ - Surface — #FFF8F0
65
+ `);
66
+ const compiled = compileTailwindTheme(spec);
67
+ expect(compiled.entries.find((e) => e.variable === "--color-primary")).toBeUndefined();
68
+ expect(compiled.warnings.some((w) => w.kind === "missing-value" && w.tokenName === "Primary")).toBe(true);
69
+ });
70
+
71
+ it("flags slug collisions", () => {
72
+ const spec = parseDesignMd(`# Test
73
+ ## Color Palette
74
+ - Primary — #ff0000
75
+ - primary — #00ff00
76
+ `);
77
+ const compiled = compileTailwindTheme(spec);
78
+ expect(compiled.warnings.some((w) => w.kind === "slug-collision")).toBe(true);
79
+ // First wins.
80
+ expect(compiled.entries.find((e) => e.variable === "--color-primary")?.value).toBe("#ff0000");
81
+ });
82
+ });
83
+
84
+ describe("compileTailwindTheme — emit order + section comments", () => {
85
+ it("groups entries by section with comment dividers", () => {
86
+ const spec = parseDesignMd(`# Test
87
+ ## Color Palette
88
+ - Primary — #FF8C42
89
+
90
+ ## Layout
91
+ - sm: 0.5rem
92
+ - md: 1rem
93
+ `);
94
+ const compiled = compileTailwindTheme(spec);
95
+ expect(compiled.cssBody).toContain("/* Colors */");
96
+ expect(compiled.cssBody).toContain("--color-primary: #FF8C42;");
97
+ expect(compiled.cssBody).toContain("/* Spacing */");
98
+ expect(compiled.cssBody).toContain("--spacing-sm: 0.5rem;");
99
+ });
100
+ });
101
+
102
+ describe("mergeThemeIntoCss", () => {
103
+ it("inserts a fresh markered block when none exists", () => {
104
+ const spec = parseDesignMd(`# Test
105
+ ## Color Palette
106
+ - Primary — #FF8C42
107
+ `);
108
+ const compiled = compileTailwindTheme(spec);
109
+ const result = mergeThemeIntoCss("@import 'tailwindcss';\n", compiled);
110
+ expect(result.inserted).toBe(true);
111
+ expect(result.css).toContain(THEME_MARKER_START);
112
+ expect(result.css).toContain(THEME_MARKER_END);
113
+ expect(result.css).toContain("--color-primary: #FF8C42;");
114
+ expect(result.css).toContain("@import 'tailwindcss';");
115
+ });
116
+
117
+ it("replaces the markered region only — leaves surrounding content untouched", () => {
118
+ const initial = `@import 'tailwindcss';
119
+
120
+ /* user comment */
121
+ ${THEME_MARKER_START}
122
+ @theme {
123
+ --color-primary: oldvalue;
124
+ }
125
+ ${THEME_MARKER_END}
126
+
127
+ .user-class { color: red; }
128
+ `;
129
+ const spec = parseDesignMd(`# Test
130
+ ## Color Palette
131
+ - Primary — #FF8C42
132
+ `);
133
+ const compiled = compileTailwindTheme(spec);
134
+ const result = mergeThemeIntoCss(initial, compiled);
135
+ expect(result.inserted).toBe(false);
136
+ expect(result.css).toContain("/* user comment */");
137
+ expect(result.css).toContain(".user-class { color: red; }");
138
+ expect(result.css).toContain("--color-primary: #FF8C42;");
139
+ expect(result.css).not.toContain("oldvalue");
140
+ });
141
+
142
+ it("flags conflicts when a hand-written @theme variable contradicts DESIGN.md", () => {
143
+ const initial = `@import 'tailwindcss';
144
+ @theme {
145
+ --color-primary: #000000;
146
+ }
147
+ `;
148
+ const spec = parseDesignMd(`# Test
149
+ ## Color Palette
150
+ - Primary — #FF8C42
151
+ `);
152
+ const compiled = compileTailwindTheme(spec);
153
+ const result = mergeThemeIntoCss(initial, compiled);
154
+ expect(result.conflicts).toHaveLength(1);
155
+ expect(result.conflicts[0]!.variable).toBe("--color-primary");
156
+ expect(result.conflicts[0]!.fromDesign).toBe("#FF8C42");
157
+ expect(result.conflicts[0]!.fromCss).toBe("#000000");
158
+ });
159
+
160
+ it("emits an empty markered region (no orphans) when DESIGN.md has no tokens", () => {
161
+ const spec = parseDesignMd("# Empty\n");
162
+ const compiled = compileTailwindTheme(spec);
163
+ const result = mergeThemeIntoCss("body { margin: 0; }\n", compiled);
164
+ expect(result.css).toContain(THEME_MARKER_START);
165
+ expect(result.css).toContain(THEME_MARKER_END);
166
+ expect(result.css).toContain("body { margin: 0; }");
167
+ });
168
+ });
169
+
170
+ describe("stripMarkeredBlock", () => {
171
+ it("removes only the markered region", () => {
172
+ const css = `@import 'tailwindcss';
173
+ ${THEME_MARKER_START}
174
+ @theme {
175
+ --color-primary: #FF8C42;
176
+ }
177
+ ${THEME_MARKER_END}
178
+ .user { color: red; }
179
+ `;
180
+ const result = stripMarkeredBlock(css);
181
+ expect(result).not.toContain("--color-primary");
182
+ expect(result).toContain("@import 'tailwindcss';");
183
+ expect(result).toContain(".user { color: red; }");
184
+ });
185
+
186
+ it("is a no-op when no markers are present", () => {
187
+ const css = `@import 'tailwindcss';\n`;
188
+ expect(stripMarkeredBlock(css)).toBe(css);
189
+ });
190
+ });
191
+
192
+ describe("end-to-end — stripe-like DESIGN.md → Tailwind theme", () => {
193
+ it("compiles a full multi-section DESIGN.md into one cohesive @theme", () => {
194
+ const designMd = `# Stripe-like
195
+
196
+ ## Color Palette
197
+ - Primary — #635BFF — brand
198
+ - Surface — #FFFFFF — page background
199
+ - Text — #1A1F36 — body text
200
+
201
+ ## Typography
202
+ - body: font-family: "Inter", sans-serif; size: 16px; line-height: 1.5
203
+ - h1 hero: font-family: "Inter", sans-serif; size: 48px; line-height: 1.1
204
+
205
+ ## Layout
206
+ - xs: 0.25rem
207
+ - sm: 0.5rem
208
+ - md: 1rem
209
+
210
+ ## Depth & Elevation
211
+ - card — 0 1px 3px rgba(0,0,0,0.1)
212
+ - modal — 0 25px 50px rgba(0,0,0,0.25)
213
+ `;
214
+ const spec = parseDesignMd(designMd);
215
+ const compiled = compileTailwindTheme(spec);
216
+
217
+ // Colors
218
+ expect(compiled.cssBody).toContain("--color-primary: #635BFF;");
219
+ expect(compiled.cssBody).toContain("--color-surface: #FFFFFF;");
220
+ // Typography (font + text)
221
+ expect(compiled.cssBody).toContain("--font-body:");
222
+ expect(compiled.cssBody).toContain("--text-h1-hero: 48px / 1.1;");
223
+ // Spacing
224
+ expect(compiled.cssBody).toContain("--spacing-md: 1rem;");
225
+ // Shadows
226
+ expect(compiled.cssBody).toContain("--shadow-card:");
227
+ expect(compiled.cssBody).toContain("--shadow-modal:");
228
+ });
229
+ });
@@ -20,6 +20,20 @@ export {
20
20
  AWESOME_DESIGN_MD_RAW_BASE,
21
21
  } from "./scaffold";
22
22
 
23
+ export {
24
+ compileTailwindTheme,
25
+ mergeThemeIntoCss,
26
+ stripMarkeredBlock,
27
+ slugifyTokenName,
28
+ THEME_MARKER_START,
29
+ THEME_MARKER_END,
30
+ type CompiledTheme,
31
+ type CompiledThemeEntry,
32
+ type CompiledThemeWarning,
33
+ type ThemeMergeConflict,
34
+ type ThemeMergeResult,
35
+ } from "./tailwind-theme";
36
+
23
37
  export type {
24
38
  AgentPrompt,
25
39
  AgentPromptsSection,
@@ -0,0 +1,441 @@
1
+ /**
2
+ * DESIGN.md → Tailwind v4 `@theme` compiler (Token Bridge).
3
+ *
4
+ * Issue #245 M3 — Team E. Reads structured tokens from a parsed
5
+ * `DesignSpec` and emits the CSS `@theme` block Tailwind v4 inlines
6
+ * to generate utility classes. The compiler is the **only** authoritative
7
+ * source for the CSS variable names — Tailwind's naming convention is
8
+ * baked in here so other tools (Guard, MCP) consult one place when
9
+ * they need to map a token name to its `--var`.
10
+ *
11
+ * # Variable naming (Tailwind v4 convention)
12
+ *
13
+ * - `--color-<name>` — color palette
14
+ * - `--font-<name>` — typography (font family)
15
+ * - `--text-<name>` — typography (font size + line-height)
16
+ * - `--spacing-<scale>` — layout / spacing
17
+ * - `--shadow-<name>` — depth / elevation
18
+ *
19
+ * # Token name normalisation
20
+ *
21
+ * DESIGN.md author writes tokens in human form ("Hot Peach", "Body
22
+ * Small"). Tailwind variables need kebab-case ASCII-safe identifiers.
23
+ * `slugifyTokenName()` is the canonical normaliser:
24
+ *
25
+ * "Hot Peach" → "hot-peach"
26
+ * "Body Small" → "body-small"
27
+ * "h1 hero" → "h1-hero"
28
+ *
29
+ * Collisions (two tokens that slugify the same) are flagged as
30
+ * `conflicts[]` so the caller can surface them — the compiler keeps
31
+ * the first occurrence and skips duplicates.
32
+ *
33
+ * # Conflict detection
34
+ *
35
+ * `compileTailwindTheme` also emits warnings when a DESIGN.md token
36
+ * contradicts an existing `@theme` block: same variable name, different
37
+ * value. The merge step (`mergeThemeIntoCss`) preserves user-edited
38
+ * regions outside the markers, so this is the only place the conflict
39
+ * can be detected.
40
+ */
41
+
42
+ import type { DesignSpec } from "./types";
43
+
44
+ // ─── Marker constants ────────────────────────────────────────────────
45
+
46
+ /**
47
+ * Marker comments wrapping the auto-generated `@theme` body.
48
+ *
49
+ * Mandu only ever rewrites the region between these markers. Anything
50
+ * outside is treated as user-owned and preserved verbatim. The marker
51
+ * format is intentionally noisy so a casual reader can tell at a
52
+ * glance "this is generated, don't hand-edit".
53
+ */
54
+ export const THEME_MARKER_START = "/* @mandu-design-sync:start — generated from DESIGN.md, do not edit */";
55
+ export const THEME_MARKER_END = "/* @mandu-design-sync:end */";
56
+
57
+ // ─── Public surface ───────────────────────────────────────────────────
58
+
59
+ export interface CompiledThemeEntry {
60
+ /** Tailwind v4 CSS variable name (`--color-primary`). */
61
+ variable: string;
62
+ value: string;
63
+ /** Origin token from the DesignSpec (e.g. "Hot Peach"). */
64
+ sourceTokenName: string;
65
+ /** Section the token came from. */
66
+ section: "color-palette" | "typography" | "layout" | "shadows";
67
+ }
68
+
69
+ export interface CompiledThemeWarning {
70
+ kind: "missing-value" | "slug-collision";
71
+ message: string;
72
+ /** Token name as it appears in DESIGN.md. */
73
+ tokenName: string;
74
+ section: CompiledThemeEntry["section"];
75
+ }
76
+
77
+ export interface CompiledTheme {
78
+ /** Flat list of variables in emit order. */
79
+ entries: CompiledThemeEntry[];
80
+ /** Non-fatal issues — missing values, slug collisions. */
81
+ warnings: CompiledThemeWarning[];
82
+ /** The `@theme { ... }` body as it would be written to disk. */
83
+ cssBody: string;
84
+ }
85
+
86
+ export interface ThemeMergeConflict {
87
+ variable: string;
88
+ fromDesign: string;
89
+ fromCss: string;
90
+ }
91
+
92
+ export interface ThemeMergeResult {
93
+ /** Updated CSS — markered region replaced, rest preserved. */
94
+ css: string;
95
+ /**
96
+ * Variables that collide with manual `@theme` declarations OUTSIDE
97
+ * the marker region. The caller surfaces these in CLI output so the
98
+ * user knows to reconcile.
99
+ */
100
+ conflicts: ThemeMergeConflict[];
101
+ /** Whether the markered region already existed (vs. was inserted). */
102
+ inserted: boolean;
103
+ }
104
+
105
+ /**
106
+ * Compile a `DesignSpec` into a Tailwind v4 `@theme` block.
107
+ *
108
+ * Tokens with no parseable value are skipped with a `missing-value`
109
+ * warning — they're declarative-only entries (e.g. "primary — see
110
+ * docs"). Slug collisions also warn but never throw.
111
+ */
112
+ export function compileTailwindTheme(spec: DesignSpec): CompiledTheme {
113
+ const entries: CompiledThemeEntry[] = [];
114
+ const warnings: CompiledThemeWarning[] = [];
115
+ const seen = new Set<string>();
116
+
117
+ // Color palette → --color-<slug>
118
+ for (const token of spec.sections["color-palette"].tokens) {
119
+ const variable = `--color-${slugifyTokenName(token.name)}`;
120
+ if (!token.value) {
121
+ warnings.push({
122
+ kind: "missing-value",
123
+ message: `color "${token.name}" has no parseable value — skipped`,
124
+ tokenName: token.name,
125
+ section: "color-palette",
126
+ });
127
+ continue;
128
+ }
129
+ if (seen.has(variable)) {
130
+ warnings.push({
131
+ kind: "slug-collision",
132
+ message: `color "${token.name}" collides with an earlier token on ${variable} — skipped`,
133
+ tokenName: token.name,
134
+ section: "color-palette",
135
+ });
136
+ continue;
137
+ }
138
+ seen.add(variable);
139
+ entries.push({
140
+ variable,
141
+ value: token.value,
142
+ sourceTokenName: token.name,
143
+ section: "color-palette",
144
+ });
145
+ }
146
+
147
+ // Typography → --font-<slug> + --text-<slug>
148
+ for (const token of spec.sections.typography.tokens) {
149
+ const slug = slugifyTokenName(token.name);
150
+ if (token.fontFamily) {
151
+ const variable = `--font-${slug}`;
152
+ if (!seen.has(variable)) {
153
+ seen.add(variable);
154
+ entries.push({
155
+ variable,
156
+ value: token.fontFamily,
157
+ sourceTokenName: token.name,
158
+ section: "typography",
159
+ });
160
+ } else {
161
+ warnings.push({
162
+ kind: "slug-collision",
163
+ message: `typography "${token.name}" collides on ${variable}`,
164
+ tokenName: token.name,
165
+ section: "typography",
166
+ });
167
+ }
168
+ }
169
+ if (token.size) {
170
+ const variable = `--text-${slug}`;
171
+ const value = token.lineHeight ? `${token.size} / ${token.lineHeight}` : token.size;
172
+ if (!seen.has(variable)) {
173
+ seen.add(variable);
174
+ entries.push({
175
+ variable,
176
+ value,
177
+ sourceTokenName: token.name,
178
+ section: "typography",
179
+ });
180
+ } else {
181
+ warnings.push({
182
+ kind: "slug-collision",
183
+ message: `typography "${token.name}" collides on ${variable}`,
184
+ tokenName: token.name,
185
+ section: "typography",
186
+ });
187
+ }
188
+ }
189
+ if (!token.fontFamily && !token.size) {
190
+ warnings.push({
191
+ kind: "missing-value",
192
+ message: `typography "${token.name}" has neither fontFamily nor size — skipped`,
193
+ tokenName: token.name,
194
+ section: "typography",
195
+ });
196
+ }
197
+ }
198
+
199
+ // Layout / spacing → --spacing-<slug>
200
+ for (const token of spec.sections.layout.tokens) {
201
+ if (!token.value) {
202
+ warnings.push({
203
+ kind: "missing-value",
204
+ message: `spacing "${token.name}" has no value — skipped`,
205
+ tokenName: token.name,
206
+ section: "layout",
207
+ });
208
+ continue;
209
+ }
210
+ const variable = `--spacing-${slugifyTokenName(token.name)}`;
211
+ if (seen.has(variable)) {
212
+ warnings.push({
213
+ kind: "slug-collision",
214
+ message: `spacing "${token.name}" collides on ${variable}`,
215
+ tokenName: token.name,
216
+ section: "layout",
217
+ });
218
+ continue;
219
+ }
220
+ seen.add(variable);
221
+ entries.push({
222
+ variable,
223
+ value: token.value,
224
+ sourceTokenName: token.name,
225
+ section: "layout",
226
+ });
227
+ }
228
+
229
+ // Shadows → --shadow-<slug>
230
+ for (const token of spec.sections.shadows.tokens) {
231
+ if (!token.value) {
232
+ warnings.push({
233
+ kind: "missing-value",
234
+ message: `shadow "${token.name}" has no value — skipped`,
235
+ tokenName: token.name,
236
+ section: "shadows",
237
+ });
238
+ continue;
239
+ }
240
+ const variable = `--shadow-${slugifyTokenName(token.name)}`;
241
+ if (seen.has(variable)) {
242
+ warnings.push({
243
+ kind: "slug-collision",
244
+ message: `shadow "${token.name}" collides on ${variable}`,
245
+ tokenName: token.name,
246
+ section: "shadows",
247
+ });
248
+ continue;
249
+ }
250
+ seen.add(variable);
251
+ entries.push({
252
+ variable,
253
+ value: token.value,
254
+ sourceTokenName: token.name,
255
+ section: "shadows",
256
+ });
257
+ }
258
+
259
+ return {
260
+ entries,
261
+ warnings,
262
+ cssBody: formatThemeBody(entries),
263
+ };
264
+ }
265
+
266
+ /**
267
+ * Merge a compiled `@theme` body into an existing CSS file. The
268
+ * markered region (between `THEME_MARKER_START` and `_END`) is
269
+ * **replaced**; everything outside is preserved verbatim.
270
+ *
271
+ * If the markers are absent, the merger inserts a fresh markered block:
272
+ * - Inside the first existing `@theme { ... }` block when one exists
273
+ * (so users get to keep their hand-written palette and the
274
+ * generated block sits alongside it).
275
+ * - Otherwise as a top-level `@theme { ... }` block prepended to the
276
+ * file. The user can move it later — we err on the side of
277
+ * "visible at the top" rather than "buried somewhere".
278
+ *
279
+ * Conflicts: variables declared both inside the generated region AND
280
+ * inside a hand-written `@theme` block elsewhere in the file are
281
+ * surfaced in `conflicts[]`. The auto-generated value wins inside the
282
+ * markered region; the user's value stays in their own block. The
283
+ * caller decides what to do with the warning.
284
+ */
285
+ export function mergeThemeIntoCss(
286
+ existingCss: string,
287
+ compiled: CompiledTheme,
288
+ ): ThemeMergeResult {
289
+ const generatedBlock = renderMarkeredBlock(compiled.cssBody);
290
+
291
+ const startIdx = existingCss.indexOf(THEME_MARKER_START);
292
+ const endIdx = existingCss.indexOf(THEME_MARKER_END);
293
+
294
+ let merged: string;
295
+ let inserted: boolean;
296
+ if (startIdx >= 0 && endIdx > startIdx) {
297
+ const before = existingCss.slice(0, startIdx);
298
+ const after = existingCss.slice(endIdx + THEME_MARKER_END.length);
299
+ merged = `${before}${generatedBlock}${after}`;
300
+ inserted = false;
301
+ } else {
302
+ merged = insertMarkeredBlock(existingCss, generatedBlock);
303
+ inserted = true;
304
+ }
305
+
306
+ const conflicts = detectMergeConflicts(existingCss, compiled);
307
+ return { css: merged, conflicts, inserted };
308
+ }
309
+
310
+ /**
311
+ * Strip the markered block from a CSS file — used by `mandu design
312
+ * sync --remove` and tests.
313
+ */
314
+ export function stripMarkeredBlock(css: string): string {
315
+ const startIdx = css.indexOf(THEME_MARKER_START);
316
+ const endIdx = css.indexOf(THEME_MARKER_END);
317
+ if (startIdx < 0 || endIdx < startIdx) return css;
318
+ const before = css.slice(0, startIdx).replace(/\n*$/, "\n");
319
+ const after = css.slice(endIdx + THEME_MARKER_END.length).replace(/^\n+/, "");
320
+ return `${before}${after}`;
321
+ }
322
+
323
+ /**
324
+ * Slugify a human-friendly token name into a kebab-case ASCII slug
325
+ * Tailwind v4 accepts as a CSS variable suffix.
326
+ */
327
+ export function slugifyTokenName(name: string): string {
328
+ return name
329
+ .normalize("NFKD")
330
+ .replace(/[^\w\s-]/g, "")
331
+ .trim()
332
+ .replace(/\s+/g, "-")
333
+ .replace(/_/g, "-")
334
+ .replace(/-+/g, "-")
335
+ .toLowerCase();
336
+ }
337
+
338
+ // ─── Internals ────────────────────────────────────────────────────────
339
+
340
+ function formatThemeBody(entries: CompiledThemeEntry[]): string {
341
+ if (entries.length === 0) return "";
342
+ const lines: string[] = [];
343
+ let lastSection: CompiledThemeEntry["section"] | null = null;
344
+ for (const entry of entries) {
345
+ if (entry.section !== lastSection) {
346
+ if (lastSection !== null) lines.push("");
347
+ lines.push(` /* ${humanizeSection(entry.section)} */`);
348
+ lastSection = entry.section;
349
+ }
350
+ lines.push(` ${entry.variable}: ${entry.value};`);
351
+ }
352
+ return lines.join("\n");
353
+ }
354
+
355
+ function humanizeSection(section: CompiledThemeEntry["section"]): string {
356
+ switch (section) {
357
+ case "color-palette":
358
+ return "Colors";
359
+ case "typography":
360
+ return "Typography";
361
+ case "layout":
362
+ return "Spacing";
363
+ case "shadows":
364
+ return "Shadows";
365
+ }
366
+ }
367
+
368
+ function renderMarkeredBlock(themeBody: string): string {
369
+ if (themeBody.trim().length === 0) {
370
+ // Even an empty body keeps the markers — re-running sync after
371
+ // emptying DESIGN.md should remove old vars, not orphan them.
372
+ return `${THEME_MARKER_START}\n@theme {\n}\n${THEME_MARKER_END}`;
373
+ }
374
+ return `${THEME_MARKER_START}\n@theme {\n${themeBody}\n}\n${THEME_MARKER_END}`;
375
+ }
376
+
377
+ /**
378
+ * Insert a fresh markered block. Prefer to nest it inside an existing
379
+ * `@theme` block when one exists; otherwise prepend.
380
+ */
381
+ function insertMarkeredBlock(css: string, block: string): string {
382
+ // Try to find the END of the first `@theme { ... }` block.
383
+ const themeStart = /@theme\s*\{/.exec(css);
384
+ if (themeStart) {
385
+ let depth = 0;
386
+ let i = themeStart.index;
387
+ for (; i < css.length; i++) {
388
+ const ch = css[i];
389
+ if (ch === "{") depth++;
390
+ else if (ch === "}") {
391
+ depth--;
392
+ if (depth === 0) break;
393
+ }
394
+ }
395
+ if (i < css.length) {
396
+ // Insert just before the closing `}` of the existing @theme block,
397
+ // unwrapping our generated block (which contains its own @theme).
398
+ // The cleanest move: replace the whole existing @theme block with
399
+ // a concatenation of "user's content" + generated body. But that
400
+ // risks re-ordering. So instead, append the generated block AFTER
401
+ // the existing one — Tailwind merges multiple @theme blocks at
402
+ // build time.
403
+ const before = css.slice(0, i + 1);
404
+ const after = css.slice(i + 1);
405
+ return `${before}\n\n${block}\n${after}`;
406
+ }
407
+ }
408
+ // No existing @theme → prepend.
409
+ return `${block}\n\n${css}`.replace(/\n{3,}/g, "\n\n");
410
+ }
411
+
412
+ function detectMergeConflicts(
413
+ existingCss: string,
414
+ compiled: CompiledTheme,
415
+ ): ThemeMergeConflict[] {
416
+ // Strip the markered region — anything inside is owned by Mandu and
417
+ // can't conflict with itself.
418
+ const outside = stripMarkeredBlock(existingCss);
419
+ const conflicts: ThemeMergeConflict[] = [];
420
+ for (const entry of compiled.entries) {
421
+ const re = new RegExp(
422
+ `${escapeRegex(entry.variable)}\\s*:\\s*([^;\\n]+);`,
423
+ "m",
424
+ );
425
+ const m = re.exec(outside);
426
+ if (!m) continue;
427
+ const fromCss = m[1]!.trim();
428
+ if (fromCss !== entry.value.trim()) {
429
+ conflicts.push({
430
+ variable: entry.variable,
431
+ fromDesign: entry.value,
432
+ fromCss,
433
+ });
434
+ }
435
+ }
436
+ return conflicts;
437
+ }
438
+
439
+ function escapeRegex(s: string): string {
440
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
441
+ }
@@ -304,6 +304,45 @@ function truncate(s: string, max: number): string {
304
304
  return JSON.stringify(s.slice(0, max - 1) + "…");
305
305
  }
306
306
 
307
+ /**
308
+ * Run the same DESIGN_INLINE_CLASS scan against a single file —
309
+ * surface used by the MCP `mandu_design_check` wrapper so an agent
310
+ * can preview violations on a file it's about to edit, without
311
+ * walking the whole project tree. Returns the same `GuardViolation`
312
+ * shape as the project-wide checker.
313
+ */
314
+ export async function checkFileForDesignInlineClasses(
315
+ rootDir: string,
316
+ filePath: string,
317
+ config: DesignGuardConfig | undefined,
318
+ ): Promise<GuardViolation[]> {
319
+ if (!config) return [];
320
+ const resolved = await resolveConfig(rootDir, config);
321
+ if (resolved.forbid.size === 0) return [];
322
+
323
+ const absolute = path.isAbsolute(filePath) ? filePath : path.join(rootDir, filePath);
324
+ const rel = path.relative(rootDir, absolute).replace(/\\/g, "/");
325
+ if (isExcluded(rel, resolved.exclude)) return [];
326
+
327
+ let content: string;
328
+ try {
329
+ content = await fs.readFile(absolute, "utf-8");
330
+ } catch {
331
+ return [];
332
+ }
333
+ const hits = scanContent(content, resolved.forbid);
334
+ return hits.map((hit) => ({
335
+ ruleId: "DESIGN_INLINE_CLASS",
336
+ file: rel,
337
+ line: hit.line,
338
+ message: buildMessage(hit, resolved.requireComponent),
339
+ suggestion: resolved.requireComponent[hit.token]
340
+ ? `Replace with ${resolved.requireComponent[hit.token]}.`
341
+ : "Extract this class into a component under src/client/shared/ui/ or src/client/widgets/, or remove the inline usage.",
342
+ severity: resolved.severity,
343
+ }));
344
+ }
345
+
307
346
  /**
308
347
  * Run the design-inline-class checker against the project source.
309
348
  * Returns Guard violations using the standard `GuardViolation` shape