uilint-core 0.1.16 → 0.1.18
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/dist/{chunk-CV67FKA6.js → chunk-RTT2ZE6O.js} +243 -7
- package/dist/chunk-RTT2ZE6O.js.map +1 -0
- package/dist/index.d.ts +148 -1
- package/dist/index.js +19 -3
- package/dist/node.d.ts +1 -1
- package/dist/node.js +18 -2
- package/dist/node.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-CV67FKA6.js.map +0 -1
|
@@ -35,11 +35,7 @@ Example response:
|
|
|
35
35
|
{
|
|
36
36
|
"issues": [
|
|
37
37
|
{
|
|
38
|
-
|
|
39
|
-
"type": "color",
|
|
40
|
-
"message": "Found similar blue colors that should be consolidated",
|
|
41
|
-
"currentValue": "#3575E2",
|
|
42
|
-
"expectedValue": "#3B82F6"
|
|
38
|
+
...issue fields...
|
|
43
39
|
}
|
|
44
40
|
]
|
|
45
41
|
}`;
|
|
@@ -1004,6 +1000,238 @@ function styleGuideToMarkdown(guide) {
|
|
|
1004
1000
|
return lines.join("\n");
|
|
1005
1001
|
}
|
|
1006
1002
|
|
|
1003
|
+
// src/consistency/prompts.ts
|
|
1004
|
+
function formatElement(el) {
|
|
1005
|
+
const parts = [
|
|
1006
|
+
`id: ${el.id}`,
|
|
1007
|
+
`text: "${el.text}"`,
|
|
1008
|
+
el.component ? `component: ${el.component}` : null,
|
|
1009
|
+
`context: ${el.context || "root"}`
|
|
1010
|
+
].filter(Boolean);
|
|
1011
|
+
const styleEntries = Object.entries(el.styles).filter(
|
|
1012
|
+
([, v]) => v && v !== "0px" && v !== "none" && v !== "normal"
|
|
1013
|
+
);
|
|
1014
|
+
if (styleEntries.length > 0) {
|
|
1015
|
+
const styleStr = styleEntries.map(([k, v]) => `${k}: ${v}`).join(", ");
|
|
1016
|
+
parts.push(`styles: { ${styleStr} }`);
|
|
1017
|
+
}
|
|
1018
|
+
if (el.rect.width > 0 || el.rect.height > 0) {
|
|
1019
|
+
parts.push(`size: ${Math.round(el.rect.width)}x${Math.round(el.rect.height)}`);
|
|
1020
|
+
}
|
|
1021
|
+
return ` { ${parts.join(", ")} }`;
|
|
1022
|
+
}
|
|
1023
|
+
function formatGroup(groupName, elements) {
|
|
1024
|
+
if (elements.length < 2) return null;
|
|
1025
|
+
const lines = [`## ${groupName} (${elements.length} elements)`];
|
|
1026
|
+
elements.forEach((el) => {
|
|
1027
|
+
lines.push(formatElement(el));
|
|
1028
|
+
});
|
|
1029
|
+
return lines.join("\n");
|
|
1030
|
+
}
|
|
1031
|
+
function buildConsistencyPrompt(snapshot) {
|
|
1032
|
+
const groupSections = [];
|
|
1033
|
+
const groups = [
|
|
1034
|
+
{ name: "Buttons", key: "buttons" },
|
|
1035
|
+
{ name: "Headings", key: "headings" },
|
|
1036
|
+
{ name: "Cards", key: "cards" },
|
|
1037
|
+
{ name: "Links", key: "links" },
|
|
1038
|
+
{ name: "Inputs", key: "inputs" },
|
|
1039
|
+
{ name: "Containers", key: "containers" }
|
|
1040
|
+
];
|
|
1041
|
+
for (const { name, key } of groups) {
|
|
1042
|
+
const section = formatGroup(name, snapshot[key]);
|
|
1043
|
+
if (section) {
|
|
1044
|
+
groupSections.push(section);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
if (groupSections.length === 0) {
|
|
1048
|
+
return "No element groups with 2+ elements found for consistency analysis.";
|
|
1049
|
+
}
|
|
1050
|
+
return `You are a UI consistency analyzer. Your task is to find visual inconsistencies between similar UI elements that SHOULD match but DON'T.
|
|
1051
|
+
|
|
1052
|
+
# Instructions
|
|
1053
|
+
|
|
1054
|
+
Analyze the following groups of UI elements. Within each group, elements should generally have consistent styling unless they're intentionally different (e.g., primary vs secondary buttons).
|
|
1055
|
+
|
|
1056
|
+
## What to FLAG (violations):
|
|
1057
|
+
- Padding/spacing differences between similar elements (e.g., one button has 12px padding, another has 16px)
|
|
1058
|
+
- Font size or weight inconsistencies within same element types
|
|
1059
|
+
- Unintentional color variations (e.g., slightly different blues: #3B82F6 vs #3575E2)
|
|
1060
|
+
- Border radius mismatches (e.g., one card has 8px radius, another has 12px)
|
|
1061
|
+
- Shadow inconsistencies between similar components
|
|
1062
|
+
- Heading hierarchy issues (h1 should be larger than h2, h2 larger than h3)
|
|
1063
|
+
|
|
1064
|
+
## What to NOT FLAG:
|
|
1065
|
+
- Intentional variations (primary vs secondary buttons, different heading levels)
|
|
1066
|
+
- Elements in different contexts that reasonably differ (header vs footer)
|
|
1067
|
+
- Sub-2px differences (likely rounding or subpixel rendering)
|
|
1068
|
+
- Different element types that shouldn't match
|
|
1069
|
+
|
|
1070
|
+
# Element Groups
|
|
1071
|
+
|
|
1072
|
+
${groupSections.join("\n\n")}
|
|
1073
|
+
|
|
1074
|
+
# Response Format
|
|
1075
|
+
|
|
1076
|
+
Respond with JSON ONLY. Return a single JSON object with a "violations" array.
|
|
1077
|
+
|
|
1078
|
+
Each violation should have:
|
|
1079
|
+
- elementIds: array of element IDs involved, e.g. ["el-3", "el-7"]
|
|
1080
|
+
- category: one of "spacing", "color", "typography", "sizing", "borders", "shadows"
|
|
1081
|
+
- severity: one of "error" (major inconsistency), "warning" (minor but noticeable), "info" (subtle)
|
|
1082
|
+
- message: short human-readable description
|
|
1083
|
+
- details: { property: the CSS property, values: array of differing values found, suggestion?: optional fix }
|
|
1084
|
+
|
|
1085
|
+
Example response:
|
|
1086
|
+
{
|
|
1087
|
+
"violations": [
|
|
1088
|
+
{
|
|
1089
|
+
"elementIds": ["el-3", "el-7"],
|
|
1090
|
+
"category": "spacing",
|
|
1091
|
+
"severity": "warning",
|
|
1092
|
+
"message": "Inconsistent padding on buttons",
|
|
1093
|
+
"details": {
|
|
1094
|
+
"property": "padding",
|
|
1095
|
+
"values": ["12px 24px", "16px 32px"],
|
|
1096
|
+
"suggestion": "Use consistent padding of 12px 24px"
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
]
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
Be minimal. Only report significant inconsistencies. If no violations found, return {"violations": []}.`;
|
|
1103
|
+
}
|
|
1104
|
+
function countElements(snapshot) {
|
|
1105
|
+
return snapshot.buttons.length + snapshot.headings.length + snapshot.cards.length + snapshot.links.length + snapshot.inputs.length + snapshot.containers.length;
|
|
1106
|
+
}
|
|
1107
|
+
function hasAnalyzableGroups(snapshot) {
|
|
1108
|
+
return snapshot.buttons.length >= 2 || snapshot.headings.length >= 2 || snapshot.cards.length >= 2 || snapshot.links.length >= 2 || snapshot.inputs.length >= 2 || snapshot.containers.length >= 2;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// src/consistency/analyzer.ts
|
|
1112
|
+
var VALID_CATEGORIES = [
|
|
1113
|
+
"spacing",
|
|
1114
|
+
"color",
|
|
1115
|
+
"typography",
|
|
1116
|
+
"sizing",
|
|
1117
|
+
"borders",
|
|
1118
|
+
"shadows"
|
|
1119
|
+
];
|
|
1120
|
+
var VALID_SEVERITIES = ["error", "warning", "info"];
|
|
1121
|
+
function parseGroupedSnapshot(json) {
|
|
1122
|
+
try {
|
|
1123
|
+
const parsed = JSON.parse(json);
|
|
1124
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
1125
|
+
const result = {
|
|
1126
|
+
buttons: Array.isArray(parsed.buttons) ? parsed.buttons : [],
|
|
1127
|
+
headings: Array.isArray(parsed.headings) ? parsed.headings : [],
|
|
1128
|
+
cards: Array.isArray(parsed.cards) ? parsed.cards : [],
|
|
1129
|
+
links: Array.isArray(parsed.links) ? parsed.links : [],
|
|
1130
|
+
inputs: Array.isArray(parsed.inputs) ? parsed.inputs : [],
|
|
1131
|
+
containers: Array.isArray(parsed.containers) ? parsed.containers : []
|
|
1132
|
+
};
|
|
1133
|
+
return result;
|
|
1134
|
+
} catch {
|
|
1135
|
+
return null;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
function parseViolationsResponse(response) {
|
|
1139
|
+
try {
|
|
1140
|
+
const parsed = JSON.parse(response);
|
|
1141
|
+
if (Array.isArray(parsed.violations)) {
|
|
1142
|
+
return validateViolations(parsed.violations);
|
|
1143
|
+
}
|
|
1144
|
+
return [];
|
|
1145
|
+
} catch {
|
|
1146
|
+
const jsonMatch = response.match(/\{[\s\S]*"violations"[\s\S]*\}/);
|
|
1147
|
+
if (jsonMatch) {
|
|
1148
|
+
try {
|
|
1149
|
+
const parsed = JSON.parse(jsonMatch[0]);
|
|
1150
|
+
if (Array.isArray(parsed.violations)) {
|
|
1151
|
+
return validateViolations(parsed.violations);
|
|
1152
|
+
}
|
|
1153
|
+
} catch {
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
return [];
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
function validateViolations(violations) {
|
|
1160
|
+
return violations.filter((v) => {
|
|
1161
|
+
if (!v || typeof v !== "object") return false;
|
|
1162
|
+
const obj = v;
|
|
1163
|
+
if (!Array.isArray(obj.elementIds)) return false;
|
|
1164
|
+
if (typeof obj.category !== "string") return false;
|
|
1165
|
+
if (typeof obj.severity !== "string") return false;
|
|
1166
|
+
if (typeof obj.message !== "string") return false;
|
|
1167
|
+
if (!obj.details || typeof obj.details !== "object") return false;
|
|
1168
|
+
if (!VALID_CATEGORIES.includes(obj.category)) return false;
|
|
1169
|
+
if (!VALID_SEVERITIES.includes(obj.severity)) return false;
|
|
1170
|
+
return true;
|
|
1171
|
+
}).map((v) => ({
|
|
1172
|
+
elementIds: v.elementIds,
|
|
1173
|
+
category: v.category,
|
|
1174
|
+
severity: v.severity,
|
|
1175
|
+
message: v.message,
|
|
1176
|
+
details: {
|
|
1177
|
+
property: typeof v.details.property === "string" ? v.details.property : "",
|
|
1178
|
+
values: Array.isArray(v.details.values) ? v.details.values : [],
|
|
1179
|
+
suggestion: typeof v.details.suggestion === "string" ? v.details.suggestion : void 0
|
|
1180
|
+
}
|
|
1181
|
+
}));
|
|
1182
|
+
}
|
|
1183
|
+
async function analyzeConsistency(snapshot, options = {}) {
|
|
1184
|
+
const startTime = Date.now();
|
|
1185
|
+
const elementCount = countElements(snapshot);
|
|
1186
|
+
if (!hasAnalyzableGroups(snapshot)) {
|
|
1187
|
+
return {
|
|
1188
|
+
violations: [],
|
|
1189
|
+
elementCount,
|
|
1190
|
+
analysisTime: Date.now() - startTime
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
const prompt = buildConsistencyPrompt(snapshot);
|
|
1194
|
+
const client = new OllamaClient({
|
|
1195
|
+
model: options.model,
|
|
1196
|
+
baseUrl: options.baseUrl
|
|
1197
|
+
});
|
|
1198
|
+
const response = await client.complete(prompt, { json: true });
|
|
1199
|
+
const violations = parseViolationsResponse(response);
|
|
1200
|
+
return {
|
|
1201
|
+
violations,
|
|
1202
|
+
elementCount,
|
|
1203
|
+
analysisTime: Date.now() - startTime
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
function formatConsistencyViolations(violations) {
|
|
1207
|
+
if (violations.length === 0) {
|
|
1208
|
+
return "\u2713 No consistency issues found.";
|
|
1209
|
+
}
|
|
1210
|
+
const lines = [`Found ${violations.length} consistency issue(s):
|
|
1211
|
+
`];
|
|
1212
|
+
const severityIcons = {
|
|
1213
|
+
error: "\u2716",
|
|
1214
|
+
warning: "\u26A0",
|
|
1215
|
+
info: "\u2139"
|
|
1216
|
+
};
|
|
1217
|
+
violations.forEach((v, i) => {
|
|
1218
|
+
const icon = severityIcons[v.severity] || "\u2022";
|
|
1219
|
+
lines.push(`${i + 1}. ${icon} [${v.category}] ${v.message}`);
|
|
1220
|
+
lines.push(` Elements: ${v.elementIds.join(", ")}`);
|
|
1221
|
+
if (v.details.property) {
|
|
1222
|
+
lines.push(` Property: ${v.details.property}`);
|
|
1223
|
+
}
|
|
1224
|
+
if (v.details.values.length > 0) {
|
|
1225
|
+
lines.push(` Values: ${v.details.values.join(" vs ")}`);
|
|
1226
|
+
}
|
|
1227
|
+
if (v.details.suggestion) {
|
|
1228
|
+
lines.push(` Suggestion: ${v.details.suggestion}`);
|
|
1229
|
+
}
|
|
1230
|
+
lines.push("");
|
|
1231
|
+
});
|
|
1232
|
+
return lines.join("\n");
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1007
1235
|
export {
|
|
1008
1236
|
buildAnalysisPrompt,
|
|
1009
1237
|
buildSourceAnalysisPrompt,
|
|
@@ -1031,6 +1259,14 @@ export {
|
|
|
1031
1259
|
extractStyleValues,
|
|
1032
1260
|
extractTailwindAllowlist,
|
|
1033
1261
|
generateStyleGuideFromStyles,
|
|
1034
|
-
styleGuideToMarkdown
|
|
1262
|
+
styleGuideToMarkdown,
|
|
1263
|
+
buildConsistencyPrompt,
|
|
1264
|
+
countElements,
|
|
1265
|
+
hasAnalyzableGroups,
|
|
1266
|
+
parseGroupedSnapshot,
|
|
1267
|
+
parseViolationsResponse,
|
|
1268
|
+
validateViolations,
|
|
1269
|
+
analyzeConsistency,
|
|
1270
|
+
formatConsistencyViolations
|
|
1035
1271
|
};
|
|
1036
|
-
//# sourceMappingURL=chunk-
|
|
1272
|
+
//# sourceMappingURL=chunk-RTT2ZE6O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ollama/prompts.ts","../src/ollama/defaults.ts","../src/ollama/client.ts","../src/format/issues.ts","../src/tailwind/class-tokens.ts","../src/scanner/style-extractor.ts","../src/styleguide/schema.ts","../src/styleguide/parser.ts","../src/styleguide/generator.ts","../src/consistency/prompts.ts","../src/consistency/analyzer.ts"],"sourcesContent":["/**\n * LLM prompt builders for UILint analysis\n */\n\n/**\n * Builds a prompt for style analysis\n */\nexport function buildAnalysisPrompt(\n styleSummary: string,\n styleGuide: string | null\n): string {\n const guideSection = styleGuide\n ? `## Current Style Guide\\n${styleGuide}\\n\\n`\n : \"## No Style Guide Found\\nAnalyze the styles and identify inconsistencies.\\n\\n\";\n\n return `You are a UI consistency analyzer. Analyze the following extracted styles and identify UI consistency violations.\n\n${guideSection}\n\n${styleSummary}\n\nRespond with JSON ONLY. Return a single JSON object containing an \"issues\" array. Each issue should have:\n- id: unique string identifier\n- type: one of \"color\", \"typography\", \"spacing\", \"component\", \"responsive\", \"accessibility\"\n- message: human-readable description of the issue\n- currentValue: the problematic value found\n- expectedValue: what it should be (if known from style guide)\n\nIMPORTANT:\n- Output ONLY violations. Do NOT include fix instructions, remediation steps, or \"suggestions\".\n- Do NOT include extra top-level keys. Only return {\"issues\":[...]}.\n- Keep messages short and neutral.\n\nFocus on:\n1. Similar but not identical colors (e.g., #3B82F6 vs #3575E2)\n2. Inconsistent font sizes or weights\n3. Spacing values that don't follow a consistent scale (e.g., 4px base unit)\n4. Mixed border-radius values\n5. If utility/Tailwind classes are present in the summary, treat them as the styling surface area and flag inconsistent utility usage (e.g., mixing px-4 and px-5 for the same component type)\n\nBe minimal. Only report significant inconsistencies.\n\nExample response:\n{\n \"issues\": [\n {\n ...issue fields...\n }\n ]\n}`;\n}\n\nexport interface BuildSourceAnalysisPromptOptions {\n /**\n * Optional filename/path for extra context in the prompt.\n */\n filePath?: string;\n /**\n * Optional hint about language (e.g. tsx, jsx, html).\n */\n languageHint?: string;\n /**\n * Optional additional context (e.g., Tailwind tokens, extracted utilities).\n * Keep this concise; it's appended verbatim.\n */\n extraContext?: string;\n}\n\n/**\n * Builds a prompt for analyzing a raw source file/snippet (TSX/JSX/etc) directly,\n * without attempting to parse it as HTML/DOM.\n */\nexport function buildSourceAnalysisPrompt(\n source: string,\n styleGuide: string | null,\n options: BuildSourceAnalysisPromptOptions = {}\n): string {\n const guideSection = styleGuide\n ? `## Current Style Guide\\n${styleGuide}\\n\\n`\n : \"## No Style Guide Found\\nAnalyze the UI code and identify inconsistencies.\\n\\n\";\n\n const metaLines: string[] = [];\n if (options.filePath) metaLines.push(`- filePath: ${options.filePath}`);\n if (options.languageHint)\n metaLines.push(`- languageHint: ${options.languageHint}`);\n const metaSection =\n metaLines.length > 0\n ? `## Source Metadata\\n${metaLines.join(\"\\n\")}\\n\\n`\n : \"\";\n\n const extra =\n options.extraContext && options.extraContext.trim()\n ? `## Additional Context\\n${options.extraContext.trim()}\\n\\n`\n : \"\";\n\n return `You are a UI consistency analyzer. Analyze the following UI source code and identify UI consistency violations.\n\n${guideSection}${metaSection}${extra}## Source Code (raw)\n${source}\n\nRespond with JSON ONLY. Return a single JSON object containing an \"issues\" array. Each issue should have:\n- id: unique string identifier\n- type: one of \"color\", \"typography\", \"spacing\", \"component\", \"responsive\", \"accessibility\"\n- message: human-readable description of the issue\n- currentValue: the problematic value found\n- expectedValue: what it should be (if known from style guide)\n\nIMPORTANT:\n- Output ONLY violations. Do NOT include fix instructions, remediation steps, or \"suggestions\".\n- Do NOT include extra top-level keys. Only return {\"issues\":[...]}.\n- Keep messages short and neutral.\n\nFocus on:\n1. Inconsistent Tailwind/utility classes (e.g., mixing px-4 and px-5 for the same component type)\n2. Inconsistent component variants (e.g., button sizes/radii/typography drift)\n3. Hardcoded colors/spacing/typography that should use tokens/scale\n4. Accessibility issues visible from code (e.g., missing labels, low-contrast combos if obvious)\n\nBe minimal. Only report significant inconsistencies.`;\n}\n\n/**\n * Builds a prompt for style guide generation\n */\nexport function buildStyleGuidePrompt(styleSummary: string): string {\n return `You are a design system expert. Based on the following detected styles, generate a clean, organized style guide in Markdown format.\n\n${styleSummary}\n\nGenerate a style guide with these sections:\n1. Colors - List the main colors with semantic names (Primary, Secondary, etc.)\n2. Typography - Font families, sizes, and weights\n3. Spacing - Base unit and common spacing values\n4. Components - Common component patterns\n5. Tailwind (if utility classes are present) - list commonly used utilities and any relevant theme tokens\n\nUse this format:\n# UI Style Guide\n\n## Colors\n- **Primary**: #HEXCODE (usage description)\n- **Secondary**: #HEXCODE (usage description)\n...\n\n## Typography\n- **Font Family**: FontName\n- **Font Sizes**: list of sizes\n- **Font Weights**: list of weights\n\n## Spacing\n- **Base unit**: Xpx\n- **Common values**: list of values\n\n## Components\n- **Buttons**: styles\n- **Cards**: styles\n...\n\nBe concise and focus on the most used values.`;\n}\n","/**\n * Single source of truth for Ollama defaults used across the monorepo.\n */\n\n/**\n * Default Ollama model used when none is provided.\n *\n * Note: This should match the model we recommend users `ollama pull`.\n */\nexport const UILINT_DEFAULT_OLLAMA_MODEL = \"qwen3-coder:30b\";\n","/**\n * Ollama API client for LLM interactions\n */\n\nimport type {\n UILintIssue,\n AnalysisResult,\n OllamaClientOptions,\n StreamProgressCallback,\n} from \"../types.js\";\nimport {\n buildAnalysisPrompt,\n buildSourceAnalysisPrompt,\n buildStyleGuidePrompt,\n type BuildSourceAnalysisPromptOptions,\n} from \"./prompts.js\";\nimport { UILINT_DEFAULT_OLLAMA_MODEL } from \"./defaults.js\";\n\nconst DEFAULT_BASE_URL = \"http://localhost:11434\";\nconst DEFAULT_TIMEOUT = 60000;\n\nexport class OllamaClient {\n private baseUrl: string;\n private model: string;\n private timeout: number;\n\n constructor(options: OllamaClientOptions = {}) {\n this.baseUrl = options.baseUrl || DEFAULT_BASE_URL;\n this.model = options.model || UILINT_DEFAULT_OLLAMA_MODEL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Low-level completion API for custom prompts (used by installers/tools).\n *\n * When `json` is true, Ollama is requested to emit JSON (best-effort).\n */\n async complete(\n prompt: string,\n options: {\n json?: boolean;\n stream?: boolean;\n onProgress?: StreamProgressCallback;\n } = {}\n ): Promise<string> {\n const jsonFormat = options.json ?? false;\n if (options.stream && options.onProgress) {\n return await this.generateStreaming(\n prompt,\n jsonFormat,\n options.onProgress\n );\n }\n return await this.generate(prompt, jsonFormat);\n }\n\n /**\n * Analyzes styles and returns issues\n */\n async analyzeStyles(\n styleSummary: string,\n styleGuide: string | null,\n onProgress?: StreamProgressCallback\n ): Promise<AnalysisResult> {\n const startTime = Date.now();\n const prompt = buildAnalysisPrompt(styleSummary, styleGuide);\n\n try {\n const response = onProgress\n ? await this.generateStreaming(prompt, true, onProgress)\n : await this.generate(prompt);\n const issues = this.parseIssuesResponse(response);\n\n return {\n issues,\n analysisTime: Date.now() - startTime,\n };\n } catch (error) {\n console.error(\"[UILint] Analysis failed:\", error);\n return {\n issues: [],\n analysisTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Analyzes a raw source file/snippet (TSX/JSX/etc) directly and returns issues.\n * This bypasses HTML/DOM parsing entirely.\n */\n async analyzeSource(\n source: string,\n styleGuide: string | null,\n onProgress?: StreamProgressCallback,\n options: BuildSourceAnalysisPromptOptions = {}\n ): Promise<AnalysisResult> {\n const startTime = Date.now();\n const prompt = buildSourceAnalysisPrompt(source, styleGuide, options);\n\n try {\n const response = onProgress\n ? await this.generateStreaming(prompt, true, onProgress)\n : await this.generate(prompt);\n const issues = this.parseIssuesResponse(response);\n\n return {\n issues,\n analysisTime: Date.now() - startTime,\n };\n } catch (error) {\n console.error(\"[UILint] Analysis failed:\", error);\n return {\n issues: [],\n analysisTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Generates a style guide from detected styles\n */\n async generateStyleGuide(styleSummary: string): Promise<string | null> {\n const prompt = buildStyleGuidePrompt(styleSummary);\n\n try {\n const response = await this.generate(prompt, false);\n return response;\n } catch (error) {\n console.error(\"[UILint] Style guide generation failed:\", error);\n return null;\n }\n }\n\n /**\n * Core generate method that calls Ollama API\n */\n private async generate(\n prompt: string,\n jsonFormat: boolean = true\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: false,\n ...(jsonFormat && { format: \"json\" }),\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Ollama API error: ${response.status}`);\n }\n\n const data = await response.json();\n return data.response || \"\";\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Streaming generate method that calls Ollama API with streaming\n * and reports progress via callback\n */\n private async generateStreaming(\n prompt: string,\n jsonFormat: boolean = true,\n onProgress: StreamProgressCallback\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: true,\n ...(jsonFormat && { format: \"json\" }),\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Ollama API error: ${response.status}`);\n }\n\n if (!response.body) {\n throw new Error(\"No response body for streaming\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let fullResponse = \"\";\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete JSON lines from the buffer\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const chunk = JSON.parse(line);\n if (chunk.response) {\n fullResponse += chunk.response;\n // Get the latest line from the response for progress display\n const responseLines = fullResponse.split(\"\\n\");\n const latestLine =\n responseLines[responseLines.length - 1] ||\n responseLines[responseLines.length - 2] ||\n \"\";\n onProgress(latestLine.trim(), fullResponse);\n }\n } catch {\n // Skip malformed JSON chunks\n }\n }\n }\n\n // Process any remaining content in buffer\n if (buffer.trim()) {\n try {\n const chunk = JSON.parse(buffer);\n if (chunk.response) {\n fullResponse += chunk.response;\n }\n } catch {\n // Skip malformed JSON\n }\n }\n\n return fullResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Parses issues from LLM response\n */\n private parseIssuesResponse(response: string): UILintIssue[] {\n try {\n const parsed = JSON.parse(response);\n return parsed.issues || [];\n } catch {\n console.warn(\"[UILint] Failed to parse LLM response as JSON\");\n return [];\n }\n }\n\n /**\n * Checks if Ollama is available\n */\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/api/tags`, {\n method: \"GET\",\n signal: AbortSignal.timeout(5000),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the current model\n */\n getModel(): string {\n return this.model;\n }\n\n /**\n * Sets the model\n */\n setModel(model: string): void {\n this.model = model;\n }\n}\n\n// Default singleton instance\nlet defaultClient: OllamaClient | null = null;\n\nexport function getOllamaClient(options?: OllamaClientOptions): OllamaClient {\n if (!defaultClient || options) {\n defaultClient = new OllamaClient(options);\n }\n return defaultClient;\n}\n","import type { UILintIssue } from \"../types.js\";\n\nexport interface FormatViolationsOptions {\n /**\n * Optional context label (e.g., filename) to include as a single header line.\n * Keep this empty for the most minimal output.\n */\n context?: string;\n /**\n * Include the trailing \"consult the style guide\" message.\n * Defaults to true.\n */\n includeFooter?: boolean;\n /**\n * Override the footer message.\n */\n footerMessage?: string;\n}\n\nconst DEFAULT_FOOTER = \"Consult the style guide for guidance.\";\n\n/**\n * Ensures issues are safe/minimal to print or serialize:\n * - drops `suggestion` (we only want violations)\n * - trims string fields\n */\nexport function sanitizeIssues(issues: UILintIssue[]): UILintIssue[] {\n return issues.map((issue) => ({\n id: String(issue.id ?? \"\").trim(),\n type: issue.type,\n message: String(issue.message ?? \"\").trim(),\n element: issue.element ? String(issue.element).trim() : undefined,\n selector: issue.selector ? String(issue.selector).trim() : undefined,\n currentValue: issue.currentValue ? String(issue.currentValue).trim() : undefined,\n expectedValue: issue.expectedValue\n ? String(issue.expectedValue).trim()\n : undefined,\n // Intentionally omit `suggestion`\n }));\n}\n\n/**\n * Minimal human-readable rendering of violations.\n * Intended for CLI/MCP text output.\n */\nexport function formatViolationsText(\n issues: UILintIssue[],\n options: FormatViolationsOptions = {}\n): string {\n const { context, includeFooter = true, footerMessage = DEFAULT_FOOTER } =\n options;\n\n if (!issues || issues.length === 0) {\n return \"No violations found.\";\n }\n\n const lines: string[] = [];\n\n if (context && context.trim()) {\n lines.push(`Violations in ${context.trim()}:`);\n lines.push(\"\");\n }\n\n const sanitized = sanitizeIssues(issues);\n sanitized.forEach((issue, i) => {\n lines.push(`${i + 1}. [${issue.type}] ${issue.message}`);\n if (issue.currentValue && issue.expectedValue) {\n lines.push(` ${issue.currentValue} → ${issue.expectedValue}`);\n } else if (issue.currentValue) {\n lines.push(` ${issue.currentValue}`);\n }\n lines.push(\"\");\n });\n\n // remove trailing blank line\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n\n if (includeFooter) {\n lines.push(\"\");\n lines.push(footerMessage);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Tailwind / utility-class token extraction helpers.\n *\n * Notes:\n * - Works on HTML (class=\"...\") and TSX-ish input (className=\"...\") via regex.\n * - Variant parsing is bracket-aware so arbitrary values like bg-[color:var(--x)]\n * don't get split incorrectly on \":\".\n */\n\nexport interface ClassTokenCounts {\n /**\n * Base utilities with variants stripped.\n * Example: \"sm:hover:bg-gray-50\" => utility \"bg-gray-50\"\n */\n utilities: Map<string, number>;\n /**\n * Individual variant prefixes.\n * Example: \"sm:hover:bg-gray-50\" => variants \"sm\", \"hover\"\n */\n variants: Map<string, number>;\n}\n\nexport interface ExtractClassTokenOptions {\n /**\n * Maximum number of tokens to process (guardrail for very large inputs).\n */\n maxTokens?: number;\n}\n\nexport function extractClassTokensFromHtml(\n html: string,\n options: ExtractClassTokenOptions = {}\n): ClassTokenCounts {\n const { maxTokens = 20000 } = options;\n\n const utilities = new Map<string, number>();\n const variants = new Map<string, number>();\n\n if (!html) return { utilities, variants };\n\n // Match both HTML and JSX-ish attributes.\n // - class=\"...\"\n // - className=\"...\"\n const attrPattern = /\\b(?:class|className)\\s*=\\s*[\"']([^\"']+)[\"']/g;\n\n let tokenBudget = maxTokens;\n let match: RegExpExecArray | null;\n while ((match = attrPattern.exec(html)) && tokenBudget > 0) {\n const raw = match[1];\n if (!raw) continue;\n\n const tokens = raw.split(/\\s+/g).filter(Boolean);\n for (const token of tokens) {\n if (tokenBudget-- <= 0) break;\n\n const { base, variantList } = splitVariants(token);\n const normalizedBase = normalizeUtility(base);\n if (!normalizedBase) continue;\n\n increment(utilities, normalizedBase);\n for (const v of variantList) increment(variants, v);\n }\n }\n\n return { utilities, variants };\n}\n\nexport function topEntries(\n map: Map<string, number>,\n limit: number\n): Array<{ token: string; count: number }> {\n return [...map.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, limit)\n .map(([token, count]) => ({ token, count }));\n}\n\nfunction increment(map: Map<string, number>, key: string): void {\n map.set(key, (map.get(key) || 0) + 1);\n}\n\nfunction normalizeUtility(token: string): string | null {\n const t = token.trim();\n if (!t) return null;\n\n // Strip important modifier\n const noImportant = t.startsWith(\"!\") ? t.slice(1) : t;\n\n // Ignore obviously non-class tokens\n if (!noImportant || noImportant === \"{\" || noImportant === \"}\") return null;\n\n return noImportant;\n}\n\n/**\n * Splits a class token into variants and base utility.\n * Bracket-aware to avoid splitting arbitrary values on \":\".\n *\n * Examples:\n * - \"sm:hover:bg-gray-50\" => variants [\"sm\",\"hover\"], base \"bg-gray-50\"\n * - \"bg-[color:var(--x)]\" => variants [], base \"bg-[color:var(--x)]\"\n * - \"sm:bg-[color:var(--x)]\" => variants [\"sm\"], base \"bg-[color:var(--x)]\"\n */\nfunction splitVariants(token: string): { base: string; variantList: string[] } {\n const parts: string[] = [];\n let buf = \"\";\n let bracketDepth = 0;\n\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n if (ch === \"[\") bracketDepth++;\n if (ch === \"]\" && bracketDepth > 0) bracketDepth--;\n\n if (ch === \":\" && bracketDepth === 0) {\n parts.push(buf);\n buf = \"\";\n continue;\n }\n\n buf += ch;\n }\n parts.push(buf);\n\n if (parts.length <= 1) return { base: token, variantList: [] };\n\n const base = parts[parts.length - 1] || \"\";\n const variantList = parts\n .slice(0, -1)\n .map((v) => v.trim())\n .filter(Boolean);\n\n return { base, variantList };\n}\n","/**\n * Style extraction from DOM elements\n */\n\nimport type {\n ExtractedStyles,\n SerializedStyles,\n TailwindThemeTokens,\n} from \"../types.js\";\nimport {\n extractClassTokensFromHtml,\n topEntries,\n} from \"../tailwind/class-tokens.js\";\n\n/**\n * Extracts all computed styles from elements in the document\n * Works in both browser and JSDOM environments\n */\nexport function extractStyles(\n root: Element | Document,\n getComputedStyle: (el: Element) => CSSStyleDeclaration\n): ExtractedStyles {\n const styles: ExtractedStyles = {\n colors: new Map(),\n fontSizes: new Map(),\n fontFamilies: new Map(),\n fontWeights: new Map(),\n spacing: new Map(),\n borderRadius: new Map(),\n };\n\n const elements = root.querySelectorAll(\"*\");\n\n elements.forEach((element) => {\n // nodeType === 1 means Element node (works in both browser and JSDOM)\n if (element.nodeType !== 1) return;\n\n const computed = getComputedStyle(element);\n\n // Extract colors\n extractColor(computed.color, styles.colors);\n extractColor(computed.backgroundColor, styles.colors);\n extractColor(computed.borderColor, styles.colors);\n\n // Extract typography\n incrementMap(styles.fontSizes, computed.fontSize);\n incrementMap(styles.fontFamilies, normalizeFontFamily(computed.fontFamily));\n incrementMap(styles.fontWeights, computed.fontWeight);\n\n // Extract spacing\n extractSpacing(computed.margin, styles.spacing);\n extractSpacing(computed.padding, styles.spacing);\n incrementMap(styles.spacing, computed.gap);\n\n // Extract border radius\n incrementMap(styles.borderRadius, computed.borderRadius);\n });\n\n return styles;\n}\n\n/**\n * Extracts styles from browser DOM (uses window.getComputedStyle)\n */\nexport function extractStylesFromDOM(\n root?: Element | Document\n): ExtractedStyles {\n const targetRoot = root || document.body;\n return extractStyles(targetRoot, (el) => window.getComputedStyle(el));\n}\n\nfunction extractColor(color: string, map: Map<string, number>): void {\n if (!color || color === \"transparent\" || color === \"rgba(0, 0, 0, 0)\") return;\n\n // Normalize to hex\n const hex = rgbToHex(color);\n if (hex) {\n incrementMap(map, hex);\n }\n}\n\nfunction extractSpacing(value: string, map: Map<string, number>): void {\n if (!value || value === \"0px\") return;\n\n // Split compound values (e.g., \"10px 20px 10px 20px\")\n const values = value.split(\" \").filter((v) => v && v !== \"0px\");\n values.forEach((v) => incrementMap(map, v));\n}\n\nfunction incrementMap(map: Map<string, number>, value: string): void {\n if (!value || value === \"normal\" || value === \"auto\") return;\n map.set(value, (map.get(value) || 0) + 1);\n}\n\nfunction normalizeFontFamily(fontFamily: string): string {\n // Get the primary font (first in the stack)\n const primary = fontFamily.split(\",\")[0].trim();\n return primary.replace(/['\"]/g, \"\");\n}\n\nfunction rgbToHex(rgb: string): string | null {\n // Handle hex values\n if (rgb.startsWith(\"#\")) return rgb.toUpperCase();\n\n // Handle rgb/rgba values\n const match = rgb.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (!match) return null;\n\n const [, r, g, b] = match;\n const toHex = (n: string) => parseInt(n).toString(16).padStart(2, \"0\");\n\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();\n}\n\n/**\n * Converts ExtractedStyles maps to plain objects for serialization\n */\nexport function serializeStyles(styles: ExtractedStyles): SerializedStyles {\n return {\n colors: Object.fromEntries(styles.colors),\n fontSizes: Object.fromEntries(styles.fontSizes),\n fontFamilies: Object.fromEntries(styles.fontFamilies),\n fontWeights: Object.fromEntries(styles.fontWeights),\n spacing: Object.fromEntries(styles.spacing),\n borderRadius: Object.fromEntries(styles.borderRadius),\n };\n}\n\n/**\n * Converts SerializedStyles back to ExtractedStyles\n */\nexport function deserializeStyles(\n serialized: SerializedStyles\n): ExtractedStyles {\n return {\n colors: new Map(Object.entries(serialized.colors)),\n fontSizes: new Map(Object.entries(serialized.fontSizes)),\n fontFamilies: new Map(Object.entries(serialized.fontFamilies)),\n fontWeights: new Map(Object.entries(serialized.fontWeights)),\n spacing: new Map(Object.entries(serialized.spacing)),\n borderRadius: new Map(Object.entries(serialized.borderRadius)),\n };\n}\n\n/**\n * Creates a summary of extracted styles for LLM analysis\n */\nexport function createStyleSummary(\n styles: ExtractedStyles,\n options: CreateStyleSummaryOptions = {}\n): string {\n return createStyleSummaryWithOptions(styles, options);\n}\n\nexport interface CreateStyleSummaryOptions {\n /**\n * Optional HTML/TSX-ish string used to extract utility classes (Tailwind etc).\n */\n html?: string;\n /**\n * Optional Tailwind theme tokens (typically from tailwind.config.*).\n */\n tailwindTheme?: TailwindThemeTokens | null;\n}\n\n/**\n * Creates a summary of extracted styles for LLM analysis.\n * Accepts optional Tailwind context to make Tailwind-heavy projects analyzable\n * even when computed styles are sparse (e.g., JSDOM without loaded CSS).\n */\nexport function createStyleSummaryWithOptions(\n styles: ExtractedStyles,\n options: CreateStyleSummaryOptions = {}\n): string {\n const lines: string[] = [];\n\n lines.push(\"## Detected Styles Summary\\n\");\n\n // Colors\n lines.push(\"### Colors\");\n const sortedColors = [...styles.colors.entries()].sort((a, b) => b[1] - a[1]);\n sortedColors.slice(0, 20).forEach(([color, count]) => {\n lines.push(`- ${color}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font sizes\n lines.push(\"### Font Sizes\");\n const sortedFontSizes = [...styles.fontSizes.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontSizes.forEach(([size, count]) => {\n lines.push(`- ${size}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font families\n lines.push(\"### Font Families\");\n const sortedFontFamilies = [...styles.fontFamilies.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontFamilies.forEach(([family, count]) => {\n lines.push(`- ${family}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font weights\n lines.push(\"### Font Weights\");\n const sortedFontWeights = [...styles.fontWeights.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontWeights.forEach(([weight, count]) => {\n lines.push(`- ${weight}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Spacing\n lines.push(\"### Spacing Values\");\n const sortedSpacing = [...styles.spacing.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedSpacing.slice(0, 15).forEach(([value, count]) => {\n lines.push(`- ${value}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Border radius\n lines.push(\"### Border Radius\");\n const sortedBorderRadius = [...styles.borderRadius.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedBorderRadius.forEach(([value, count]) => {\n lines.push(`- ${value}: ${count} occurrences`);\n });\n\n // Tailwind / utility classes (optional)\n if (options.html) {\n const tokens = extractClassTokensFromHtml(options.html);\n const topUtilities = topEntries(tokens.utilities, 40);\n const topVariants = topEntries(tokens.variants, 15);\n\n lines.push(\"\");\n lines.push(\"### Utility Classes (from markup)\");\n if (topUtilities.length === 0) {\n lines.push(\"- (none detected)\");\n } else {\n topUtilities.forEach(({ token, count }) => {\n lines.push(`- ${token}: ${count} occurrences`);\n });\n }\n\n if (topVariants.length > 0) {\n lines.push(\"\");\n lines.push(\"### Common Variants\");\n topVariants.forEach(({ token, count }) => {\n lines.push(`- ${token}: ${count} occurrences`);\n });\n }\n }\n\n // Tailwind theme tokens (optional)\n if (options.tailwindTheme) {\n const tt = options.tailwindTheme;\n lines.push(\"\");\n lines.push(\"### Tailwind Theme Tokens (from config)\");\n lines.push(`- configPath: ${tt.configPath}`);\n lines.push(`- colors: ${tt.colors.length}`);\n lines.push(`- spacingKeys: ${tt.spacingKeys.length}`);\n lines.push(`- borderRadiusKeys: ${tt.borderRadiusKeys.length}`);\n lines.push(`- fontFamilyKeys: ${tt.fontFamilyKeys.length}`);\n lines.push(`- fontSizeKeys: ${tt.fontSizeKeys.length}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Truncates HTML to a maximum length\n */\nexport function truncateHTML(html: string, maxLength: number = 50000): string {\n if (html.length <= maxLength) return html;\n return html.slice(0, maxLength) + \"<!-- truncated -->\";\n}\n","/**\n * Style guide schema and utilities\n */\n\nimport type { StyleGuide, ColorRule, TypographyRule, SpacingRule, ComponentRule } from \"../types.js\";\n\n/**\n * Creates an empty style guide structure\n */\nexport function createEmptyStyleGuide(): StyleGuide {\n return {\n colors: [],\n typography: [],\n spacing: [],\n components: [],\n };\n}\n\n/**\n * Validates a style guide object\n */\nexport function validateStyleGuide(guide: unknown): guide is StyleGuide {\n if (!guide || typeof guide !== \"object\") return false;\n\n const g = guide as Record<string, unknown>;\n\n return (\n Array.isArray(g.colors) &&\n Array.isArray(g.typography) &&\n Array.isArray(g.spacing) &&\n Array.isArray(g.components)\n );\n}\n\n/**\n * Merges detected styles into an existing style guide\n */\nexport function mergeStyleGuides(\n existing: StyleGuide,\n detected: Partial<StyleGuide>\n): StyleGuide {\n return {\n colors: mergeColorRules(existing.colors, detected.colors || []),\n typography: mergeTypographyRules(existing.typography, detected.typography || []),\n spacing: mergeSpacingRules(existing.spacing, detected.spacing || []),\n components: mergeComponentRules(existing.components, detected.components || []),\n };\n}\n\nfunction mergeColorRules(existing: ColorRule[], detected: ColorRule[]): ColorRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex(\n (e) => e.name === rule.name || e.value === rule.value\n );\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeTypographyRules(existing: TypographyRule[], detected: TypographyRule[]): TypographyRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex((e) => e.element === rule.element);\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeSpacingRules(existing: SpacingRule[], detected: SpacingRule[]): SpacingRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex(\n (e) => e.name === rule.name || e.value === rule.value\n );\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeComponentRules(existing: ComponentRule[], detected: ComponentRule[]): ComponentRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex((e) => e.name === rule.name);\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\n/**\n * Creates a color rule\n */\nexport function createColorRule(\n name: string,\n value: string,\n usage: string = \"\"\n): ColorRule {\n return { name, value: value.toUpperCase(), usage };\n}\n\n/**\n * Creates a typography rule\n */\nexport function createTypographyRule(\n element: string,\n options: Partial<Omit<TypographyRule, \"element\">> = {}\n): TypographyRule {\n return { element, ...options };\n}\n\n/**\n * Creates a spacing rule\n */\nexport function createSpacingRule(name: string, value: string): SpacingRule {\n return { name, value };\n}\n\n/**\n * Creates a component rule\n */\nexport function createComponentRule(name: string, styles: string[]): ComponentRule {\n return { name, styles };\n}\n\n","/**\n * Parse Markdown style guides into structured data\n */\n\nimport type {\n StyleGuide,\n ColorRule,\n TypographyRule,\n SpacingRule,\n ComponentRule,\n ExtractedStyleValues,\n} from \"../types.js\";\nimport { createEmptyStyleGuide } from \"./schema.js\";\n\n/**\n * Parses a Markdown style guide into a structured object\n */\nexport function parseStyleGuide(markdown: string): StyleGuide {\n const guide = createEmptyStyleGuide();\n const sections = splitIntoSections(markdown);\n\n sections.forEach(({ title, content }) => {\n const lowerTitle = title.toLowerCase();\n\n if (lowerTitle.includes(\"color\")) {\n guide.colors = parseColorSection(content);\n } else if (\n lowerTitle.includes(\"typography\") ||\n lowerTitle.includes(\"font\")\n ) {\n guide.typography = parseTypographySection(content);\n } else if (lowerTitle.includes(\"spacing\")) {\n guide.spacing = parseSpacingSection(content);\n } else if (lowerTitle.includes(\"component\")) {\n guide.components = parseComponentSection(content);\n }\n });\n\n return guide;\n}\n\ninterface Section {\n title: string;\n content: string;\n}\n\nfunction splitIntoSections(markdown: string): Section[] {\n const sections: Section[] = [];\n const lines = markdown.split(\"\\n\");\n\n let currentTitle = \"\";\n let currentContent: string[] = [];\n\n lines.forEach((line) => {\n const headerMatch = line.match(/^##\\s+(.+)$/);\n\n if (headerMatch) {\n if (currentTitle) {\n sections.push({\n title: currentTitle,\n content: currentContent.join(\"\\n\"),\n });\n }\n currentTitle = headerMatch[1];\n currentContent = [];\n } else {\n currentContent.push(line);\n }\n });\n\n if (currentTitle) {\n sections.push({\n title: currentTitle,\n content: currentContent.join(\"\\n\"),\n });\n }\n\n return sections;\n}\n\nfunction parseColorSection(content: string): ColorRule[] {\n const colors: ColorRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Primary**: #3B82F6 (used in buttons)\n const match = line.match(\n /[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(#[A-Fa-f0-9]{6})\\s*(?:\\(([^)]+)\\))?/\n );\n\n if (match) {\n colors.push({\n name: match[1].trim(),\n value: match[2].toUpperCase(),\n usage: match[3] || \"\",\n });\n }\n });\n\n return colors;\n}\n\nfunction parseTypographySection(content: string): TypographyRule[] {\n const typography: TypographyRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Headings**: font-family: \"Inter\", font-size: 24px\n const elementMatch = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (elementMatch) {\n const rule: TypographyRule = {\n element: elementMatch[1].trim(),\n };\n\n const props = elementMatch[2];\n\n const fontFamilyMatch = props.match(/font-family:\\s*\"?([^\",]+)\"?/);\n if (fontFamilyMatch) rule.fontFamily = fontFamilyMatch[1].trim();\n\n const fontSizeMatch = props.match(/font-size:\\s*(\\d+px)/);\n if (fontSizeMatch) rule.fontSize = fontSizeMatch[1];\n\n const fontWeightMatch = props.match(/font-weight:\\s*(\\d+)/);\n if (fontWeightMatch) rule.fontWeight = fontWeightMatch[1];\n\n const lineHeightMatch = props.match(/line-height:\\s*([\\d.]+)/);\n if (lineHeightMatch) rule.lineHeight = lineHeightMatch[1];\n\n typography.push(rule);\n }\n });\n\n return typography;\n}\n\nfunction parseSpacingSection(content: string): SpacingRule[] {\n const spacing: SpacingRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Base unit**: 4px\n const match = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (match) {\n spacing.push({\n name: match[1].trim(),\n value: match[2].trim(),\n });\n }\n });\n\n return spacing;\n}\n\nfunction parseComponentSection(content: string): ComponentRule[] {\n const components: ComponentRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Buttons**: rounded-lg, px-4 py-2\n const match = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (match) {\n components.push({\n name: match[1].trim(),\n styles: match[2].split(\",\").map((s) => s.trim()),\n });\n }\n });\n\n return components;\n}\n\n/**\n * Parses sections from a Markdown style guide (simpler format)\n */\nexport function parseStyleGuideSections(\n content: string\n): Record<string, string> {\n const sections: Record<string, string> = {};\n const lines = content.split(\"\\n\");\n\n let currentSection = \"intro\";\n let currentContent: string[] = [];\n\n for (const line of lines) {\n const headerMatch = line.match(/^##\\s+(.+)$/);\n\n if (headerMatch) {\n if (currentContent.length > 0) {\n sections[currentSection.toLowerCase()] = currentContent\n .join(\"\\n\")\n .trim();\n }\n\n currentSection = headerMatch[1];\n currentContent = [];\n } else {\n currentContent.push(line);\n }\n }\n\n if (currentContent.length > 0) {\n sections[currentSection.toLowerCase()] = currentContent.join(\"\\n\").trim();\n }\n\n return sections;\n}\n\n/**\n * Extracts specific values from the style guide\n */\nexport function extractStyleValues(content: string): ExtractedStyleValues {\n const result: ExtractedStyleValues = {\n colors: [],\n fontSizes: [],\n fontFamilies: [],\n spacing: [],\n borderRadius: [],\n };\n\n // Extract hex colors\n const colorMatches = content.matchAll(/#[A-Fa-f0-9]{6}\\b/g);\n for (const match of colorMatches) {\n if (!result.colors.includes(match[0].toUpperCase())) {\n result.colors.push(match[0].toUpperCase());\n }\n }\n\n // Extract font sizes (e.g., 16px, 1.5rem)\n const fontSizeMatches = content.matchAll(/\\b(\\d+(?:\\.\\d+)?(?:px|rem|em))\\b/g);\n for (const match of fontSizeMatches) {\n if (!result.fontSizes.includes(match[1])) {\n result.fontSizes.push(match[1]);\n }\n }\n\n // Extract font families (quoted strings in font context)\n const fontFamilyMatches = content.matchAll(\n /font-family:\\s*[\"']?([^\"',\\n]+)/gi\n );\n for (const match of fontFamilyMatches) {\n const family = match[1].trim();\n if (!result.fontFamilies.includes(family)) {\n result.fontFamilies.push(family);\n }\n }\n\n return result;\n}\n\nexport interface TailwindAllowlist {\n allowAnyColor: boolean;\n allowStandardSpacing: boolean;\n allowedTailwindColors: Set<string>;\n allowedUtilities: Set<string>;\n allowedSpacingKeys: Set<string>;\n allowedBorderRadiusKeys: Set<string>;\n allowedFontSizeKeys: Set<string>;\n allowedFontFamilyKeys: Set<string>;\n}\n\n/**\n * Extract Tailwind / utility-class allowlist configuration from a style guide.\n *\n * Expected formats:\n * - A JSON code block inside a \"## Tailwind\" section (preferred; produced by UILint)\n * - Fallback: inline backticked utilities within the Tailwind section\n */\nexport function extractTailwindAllowlist(content: string): TailwindAllowlist {\n const empty: TailwindAllowlist = {\n allowAnyColor: false,\n allowStandardSpacing: false,\n allowedTailwindColors: new Set(),\n allowedUtilities: new Set(),\n allowedSpacingKeys: new Set(),\n allowedBorderRadiusKeys: new Set(),\n allowedFontSizeKeys: new Set(),\n allowedFontFamilyKeys: new Set(),\n };\n\n // Only look for allowlist details in the Tailwind section.\n const sections = parseStyleGuideSections(content);\n const tailwindSection =\n sections[\"tailwind\"] ??\n // defensive: some styleguides use different casing/spacing\n sections[\"tailwind utilities\"] ??\n \"\";\n\n if (!tailwindSection) return empty;\n\n const parsed = tryParseFirstJsonCodeBlock(tailwindSection);\n if (parsed && typeof parsed === \"object\") {\n const allowAnyColor = Boolean((parsed as any).allowAnyColor);\n const allowStandardSpacing = Boolean((parsed as any).allowStandardSpacing);\n\n const allowedUtilitiesArr = Array.isArray((parsed as any).allowedUtilities)\n ? ((parsed as any).allowedUtilities as unknown[]).filter(\n (u): u is string => typeof u === \"string\"\n )\n : [];\n\n const themeTokens = (parsed as any).themeTokens ?? {};\n const themeColors = Array.isArray(themeTokens.colors)\n ? (themeTokens.colors as unknown[]).filter(\n (c): c is string => typeof c === \"string\"\n )\n : [];\n const spacingKeys = Array.isArray(themeTokens.spacingKeys)\n ? (themeTokens.spacingKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const borderRadiusKeys = Array.isArray(themeTokens.borderRadiusKeys)\n ? (themeTokens.borderRadiusKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const fontFamilyKeys = Array.isArray(themeTokens.fontFamilyKeys)\n ? (themeTokens.fontFamilyKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const fontSizeKeys = Array.isArray(themeTokens.fontSizeKeys)\n ? (themeTokens.fontSizeKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n\n const allowedTailwindColors = new Set<string>();\n for (const c of themeColors) {\n const raw = c.trim();\n if (!raw) continue;\n if (raw.toLowerCase().startsWith(\"tailwind:\")) {\n allowedTailwindColors.add(raw.toLowerCase());\n continue;\n }\n const m = raw.match(/^([a-zA-Z]+)-(\\d{2,3})$/);\n if (m) {\n allowedTailwindColors.add(`tailwind:${m[1].toLowerCase()}-${m[2]}`);\n }\n }\n\n return {\n allowAnyColor,\n allowStandardSpacing,\n allowedTailwindColors,\n allowedUtilities: new Set(\n allowedUtilitiesArr.map((s) => s.trim()).filter(Boolean)\n ),\n allowedSpacingKeys: new Set(\n spacingKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedBorderRadiusKeys: new Set(\n borderRadiusKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedFontSizeKeys: new Set(\n fontSizeKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedFontFamilyKeys: new Set(\n fontFamilyKeys.map((s) => s.trim()).filter(Boolean)\n ),\n };\n }\n\n // Fallback: harvest backticked utilities from markdown.\n const backticked: string[] = [];\n for (const m of tailwindSection.matchAll(/`([^`]+)`/g)) {\n backticked.push(m[1]);\n }\n\n return {\n ...empty,\n allowedUtilities: new Set(\n backticked\n .flatMap((s) => s.split(/[,\\s]+/g))\n .map((s) => s.trim())\n .filter(Boolean)\n ),\n };\n}\n\nfunction tryParseFirstJsonCodeBlock(section: string): unknown | null {\n // Prefer ```json fenced blocks, but fall back to any fenced block.\n const jsonBlocks = [...section.matchAll(/```json\\s*([\\s\\S]*?)```/gi)];\n const anyBlocks = [...section.matchAll(/```\\s*([\\s\\S]*?)```/g)];\n\n const candidates = (jsonBlocks.length ? jsonBlocks : anyBlocks).map(\n (m) => m[1]\n );\n for (const raw of candidates) {\n const trimmed = raw.trim();\n if (!trimmed) continue;\n try {\n return JSON.parse(trimmed);\n } catch {\n continue;\n }\n }\n return null;\n}\n","/**\n * Generate Markdown style guides from extracted styles\n */\n\nimport type {\n ExtractedStyles,\n StyleGuide,\n TailwindThemeTokens,\n} from \"../types.js\";\nimport {\n extractClassTokensFromHtml,\n topEntries,\n} from \"../tailwind/class-tokens.js\";\n\n/**\n * Generates a Markdown style guide from extracted styles\n */\nexport interface GenerateStyleGuideOptions {\n /**\n * Optional HTML/TSX-ish string used to extract utility classes (Tailwind etc).\n */\n html?: string;\n /**\n * Optional Tailwind theme tokens (typically from tailwind.config.*).\n */\n tailwindTheme?: TailwindThemeTokens | null;\n}\n\nexport function generateStyleGuideFromStyles(\n styles: ExtractedStyles,\n options: GenerateStyleGuideOptions = {}\n): string {\n // NOTE: Style guide auto-generation has been removed.\n // UILint now requires an explicit, user-owned style guide file (typically\n // `.uilint/styleguide.md`) to avoid silently producing/overwriting rules.\n void styles;\n void options;\n throw new Error(\n 'Style guide auto-generation has been removed. Create \".uilint/styleguide.md\" at your workspace root (recommended: run \"/genstyleguide\" in Cursor).'\n );\n}\n\n/**\n * Finds the greatest common divisor of an array of numbers\n */\nfunction findGCD(numbers: number[]): number {\n if (numbers.length === 0) return 0;\n if (numbers.length === 1) return numbers[0];\n\n const gcd = (a: number, b: number): number => {\n a = Math.abs(Math.round(a));\n b = Math.abs(Math.round(b));\n while (b) {\n const t = b;\n b = a % b;\n a = t;\n }\n return a;\n };\n\n return numbers.reduce((acc, n) => gcd(acc, n));\n}\n\n/**\n * Converts a StyleGuide object back to Markdown\n */\nexport function styleGuideToMarkdown(guide: StyleGuide): string {\n const lines: string[] = [];\n\n lines.push(\"# UI Style Guide\");\n lines.push(\"\");\n\n // Colors\n lines.push(\"## Colors\");\n guide.colors.forEach((color) => {\n const usage = color.usage ? ` (${color.usage})` : \"\";\n lines.push(`- **${color.name}**: ${color.value}${usage}`);\n });\n lines.push(\"\");\n\n // Typography\n lines.push(\"## Typography\");\n guide.typography.forEach((typo) => {\n const props: string[] = [];\n if (typo.fontFamily) props.push(`font-family: \"${typo.fontFamily}\"`);\n if (typo.fontSize) props.push(`font-size: ${typo.fontSize}`);\n if (typo.fontWeight) props.push(`font-weight: ${typo.fontWeight}`);\n if (typo.lineHeight) props.push(`line-height: ${typo.lineHeight}`);\n lines.push(`- **${typo.element}**: ${props.join(\", \")}`);\n });\n lines.push(\"\");\n\n // Spacing\n lines.push(\"## Spacing\");\n guide.spacing.forEach((space) => {\n lines.push(`- **${space.name}**: ${space.value}`);\n });\n lines.push(\"\");\n\n // Components\n lines.push(\"## Components\");\n guide.components.forEach((comp) => {\n lines.push(`- **${comp.name}**: ${comp.styles.join(\", \")}`);\n });\n\n return lines.join(\"\\n\");\n}\n","/**\n * LLM prompt builders for UI consistency analysis\n */\n\nimport type {\n ElementSnapshot,\n GroupedSnapshot,\n ElementRole,\n} from \"./types.js\";\n\n/**\n * Formats an element for inclusion in the prompt (minimal data for LLM)\n */\nfunction formatElement(el: ElementSnapshot): string {\n const parts = [\n `id: ${el.id}`,\n `text: \"${el.text}\"`,\n el.component ? `component: ${el.component}` : null,\n `context: ${el.context || \"root\"}`,\n ].filter(Boolean);\n\n // Only include non-empty style values\n const styleEntries = Object.entries(el.styles).filter(\n ([, v]) => v && v !== \"0px\" && v !== \"none\" && v !== \"normal\"\n );\n if (styleEntries.length > 0) {\n const styleStr = styleEntries.map(([k, v]) => `${k}: ${v}`).join(\", \");\n parts.push(`styles: { ${styleStr} }`);\n }\n\n if (el.rect.width > 0 || el.rect.height > 0) {\n parts.push(`size: ${Math.round(el.rect.width)}x${Math.round(el.rect.height)}`);\n }\n\n return ` { ${parts.join(\", \")} }`;\n}\n\n/**\n * Formats a group of elements for the prompt\n */\nfunction formatGroup(\n groupName: string,\n elements: ElementSnapshot[]\n): string | null {\n if (elements.length < 2) return null;\n\n const lines = [`## ${groupName} (${elements.length} elements)`];\n elements.forEach((el) => {\n lines.push(formatElement(el));\n });\n return lines.join(\"\\n\");\n}\n\n/**\n * Builds a single prompt for analyzing ALL element groups\n * This reduces LLM calls to 1 for better performance\n */\nexport function buildConsistencyPrompt(snapshot: GroupedSnapshot): string {\n const groupSections: string[] = [];\n\n // Format each group that has 2+ elements\n const groups: Array<{ name: string; key: keyof GroupedSnapshot }> = [\n { name: \"Buttons\", key: \"buttons\" },\n { name: \"Headings\", key: \"headings\" },\n { name: \"Cards\", key: \"cards\" },\n { name: \"Links\", key: \"links\" },\n { name: \"Inputs\", key: \"inputs\" },\n { name: \"Containers\", key: \"containers\" },\n ];\n\n for (const { name, key } of groups) {\n const section = formatGroup(name, snapshot[key]);\n if (section) {\n groupSections.push(section);\n }\n }\n\n if (groupSections.length === 0) {\n return \"No element groups with 2+ elements found for consistency analysis.\";\n }\n\n return `You are a UI consistency analyzer. Your task is to find visual inconsistencies between similar UI elements that SHOULD match but DON'T.\n\n# Instructions\n\nAnalyze the following groups of UI elements. Within each group, elements should generally have consistent styling unless they're intentionally different (e.g., primary vs secondary buttons).\n\n## What to FLAG (violations):\n- Padding/spacing differences between similar elements (e.g., one button has 12px padding, another has 16px)\n- Font size or weight inconsistencies within same element types\n- Unintentional color variations (e.g., slightly different blues: #3B82F6 vs #3575E2)\n- Border radius mismatches (e.g., one card has 8px radius, another has 12px)\n- Shadow inconsistencies between similar components\n- Heading hierarchy issues (h1 should be larger than h2, h2 larger than h3)\n\n## What to NOT FLAG:\n- Intentional variations (primary vs secondary buttons, different heading levels)\n- Elements in different contexts that reasonably differ (header vs footer)\n- Sub-2px differences (likely rounding or subpixel rendering)\n- Different element types that shouldn't match\n\n# Element Groups\n\n${groupSections.join(\"\\n\\n\")}\n\n# Response Format\n\nRespond with JSON ONLY. Return a single JSON object with a \"violations\" array.\n\nEach violation should have:\n- elementIds: array of element IDs involved, e.g. [\"el-3\", \"el-7\"]\n- category: one of \"spacing\", \"color\", \"typography\", \"sizing\", \"borders\", \"shadows\"\n- severity: one of \"error\" (major inconsistency), \"warning\" (minor but noticeable), \"info\" (subtle)\n- message: short human-readable description\n- details: { property: the CSS property, values: array of differing values found, suggestion?: optional fix }\n\nExample response:\n{\n \"violations\": [\n {\n \"elementIds\": [\"el-3\", \"el-7\"],\n \"category\": \"spacing\",\n \"severity\": \"warning\",\n \"message\": \"Inconsistent padding on buttons\",\n \"details\": {\n \"property\": \"padding\",\n \"values\": [\"12px 24px\", \"16px 32px\"],\n \"suggestion\": \"Use consistent padding of 12px 24px\"\n }\n }\n ]\n}\n\nBe minimal. Only report significant inconsistencies. If no violations found, return {\"violations\": []}.`;\n}\n\n/**\n * Counts total elements across all groups\n */\nexport function countElements(snapshot: GroupedSnapshot): number {\n return (\n snapshot.buttons.length +\n snapshot.headings.length +\n snapshot.cards.length +\n snapshot.links.length +\n snapshot.inputs.length +\n snapshot.containers.length\n );\n}\n\n/**\n * Checks if a snapshot has any groups worth analyzing (2+ elements)\n */\nexport function hasAnalyzableGroups(snapshot: GroupedSnapshot): boolean {\n return (\n snapshot.buttons.length >= 2 ||\n snapshot.headings.length >= 2 ||\n snapshot.cards.length >= 2 ||\n snapshot.links.length >= 2 ||\n snapshot.inputs.length >= 2 ||\n snapshot.containers.length >= 2\n );\n}\n","/**\n * Consistency analysis logic - shared between CLI and API routes\n */\n\nimport type {\n GroupedSnapshot,\n Violation,\n ConsistencyResult,\n ViolationCategory,\n ViolationSeverity,\n} from \"./types.js\";\nimport { buildConsistencyPrompt, countElements, hasAnalyzableGroups } from \"./prompts.js\";\nimport { OllamaClient } from \"../ollama/client.js\";\n\nconst VALID_CATEGORIES: ViolationCategory[] = [\n \"spacing\",\n \"color\",\n \"typography\",\n \"sizing\",\n \"borders\",\n \"shadows\",\n];\n\nconst VALID_SEVERITIES: ViolationSeverity[] = [\"error\", \"warning\", \"info\"];\n\n/**\n * Parses and validates a GroupedSnapshot from JSON string\n */\nexport function parseGroupedSnapshot(json: string): GroupedSnapshot | null {\n try {\n const parsed = JSON.parse(json);\n\n // Validate structure\n if (!parsed || typeof parsed !== \"object\") return null;\n\n const result: GroupedSnapshot = {\n buttons: Array.isArray(parsed.buttons) ? parsed.buttons : [],\n headings: Array.isArray(parsed.headings) ? parsed.headings : [],\n cards: Array.isArray(parsed.cards) ? parsed.cards : [],\n links: Array.isArray(parsed.links) ? parsed.links : [],\n inputs: Array.isArray(parsed.inputs) ? parsed.inputs : [],\n containers: Array.isArray(parsed.containers) ? parsed.containers : [],\n };\n\n return result;\n } catch {\n return null;\n }\n}\n\n/**\n * Parses violations from LLM response with defensive handling\n */\nexport function parseViolationsResponse(response: string): Violation[] {\n try {\n // Try direct JSON parse first\n const parsed = JSON.parse(response);\n if (Array.isArray(parsed.violations)) {\n return validateViolations(parsed.violations);\n }\n return [];\n } catch {\n // Try to extract JSON from response using regex\n const jsonMatch = response.match(/\\{[\\s\\S]*\"violations\"[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n if (Array.isArray(parsed.violations)) {\n return validateViolations(parsed.violations);\n }\n } catch {\n // Fallback failed\n }\n }\n return [];\n }\n}\n\n/**\n * Validates and filters violations to ensure correct structure\n */\nexport function validateViolations(violations: unknown[]): Violation[] {\n return violations\n .filter((v): v is Violation => {\n if (!v || typeof v !== \"object\") return false;\n const obj = v as Record<string, unknown>;\n\n // Required fields\n if (!Array.isArray(obj.elementIds)) return false;\n if (typeof obj.category !== \"string\") return false;\n if (typeof obj.severity !== \"string\") return false;\n if (typeof obj.message !== \"string\") return false;\n if (!obj.details || typeof obj.details !== \"object\") return false;\n\n // Validate category\n if (!VALID_CATEGORIES.includes(obj.category as ViolationCategory)) return false;\n\n // Validate severity\n if (!VALID_SEVERITIES.includes(obj.severity as ViolationSeverity)) return false;\n\n return true;\n })\n .map((v) => ({\n elementIds: v.elementIds,\n category: v.category,\n severity: v.severity,\n message: v.message,\n details: {\n property:\n typeof v.details.property === \"string\" ? v.details.property : \"\",\n values: Array.isArray(v.details.values) ? v.details.values : [],\n suggestion:\n typeof v.details.suggestion === \"string\"\n ? v.details.suggestion\n : undefined,\n },\n }));\n}\n\nexport interface AnalyzeConsistencyOptions {\n /** Ollama model to use */\n model?: string;\n /** Ollama base URL */\n baseUrl?: string;\n}\n\n/**\n * Analyzes a grouped snapshot for UI consistency violations\n * This is the main entry point for consistency analysis\n */\nexport async function analyzeConsistency(\n snapshot: GroupedSnapshot,\n options: AnalyzeConsistencyOptions = {}\n): Promise<ConsistencyResult> {\n const startTime = Date.now();\n const elementCount = countElements(snapshot);\n\n // Check if there are analyzable groups\n if (!hasAnalyzableGroups(snapshot)) {\n return {\n violations: [],\n elementCount,\n analysisTime: Date.now() - startTime,\n };\n }\n\n // Build prompt and call LLM\n const prompt = buildConsistencyPrompt(snapshot);\n const client = new OllamaClient({\n model: options.model,\n baseUrl: options.baseUrl,\n });\n\n const response = await client.complete(prompt, { json: true });\n\n // Parse violations\n const violations = parseViolationsResponse(response);\n\n return {\n violations,\n elementCount,\n analysisTime: Date.now() - startTime,\n };\n}\n\n/**\n * Formats violations for plain text output\n */\nexport function formatConsistencyViolations(violations: Violation[]): string {\n if (violations.length === 0) {\n return \"✓ No consistency issues found.\";\n }\n\n const lines: string[] = [`Found ${violations.length} consistency issue(s):\\n`];\n\n const severityIcons: Record<ViolationSeverity, string> = {\n error: \"✖\",\n warning: \"⚠\",\n info: \"ℹ\",\n };\n\n violations.forEach((v, i) => {\n const icon = severityIcons[v.severity] || \"•\";\n\n lines.push(`${i + 1}. ${icon} [${v.category}] ${v.message}`);\n lines.push(` Elements: ${v.elementIds.join(\", \")}`);\n\n if (v.details.property) {\n lines.push(` Property: ${v.details.property}`);\n }\n if (v.details.values.length > 0) {\n lines.push(` Values: ${v.details.values.join(\" vs \")}`);\n }\n if (v.details.suggestion) {\n lines.push(` Suggestion: ${v.details.suggestion}`);\n }\n lines.push(\"\");\n });\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAOO,SAAS,oBACd,cACA,YACQ;AACR,QAAM,eAAe,aACjB;AAAA,EAA2B,UAAU;AAAA;AAAA,IACrC;AAEJ,SAAO;AAAA;AAAA,EAEP,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+Bd;AAsBO,SAAS,0BACd,QACA,YACA,UAA4C,CAAC,GACrC;AACR,QAAM,eAAe,aACjB;AAAA,EAA2B,UAAU;AAAA;AAAA,IACrC;AAEJ,QAAM,YAAsB,CAAC;AAC7B,MAAI,QAAQ,SAAU,WAAU,KAAK,eAAe,QAAQ,QAAQ,EAAE;AACtE,MAAI,QAAQ;AACV,cAAU,KAAK,mBAAmB,QAAQ,YAAY,EAAE;AAC1D,QAAM,cACJ,UAAU,SAAS,IACf;AAAA,EAAuB,UAAU,KAAK,IAAI,CAAC;AAAA;AAAA,IAC3C;AAEN,QAAM,QACJ,QAAQ,gBAAgB,QAAQ,aAAa,KAAK,IAC9C;AAAA,EAA0B,QAAQ,aAAa,KAAK,CAAC;AAAA;AAAA,IACrD;AAEN,SAAO;AAAA;AAAA,EAEP,YAAY,GAAG,WAAW,GAAG,KAAK;AAAA,EAClC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBR;AAKO,SAAS,sBAAsB,cAA8B;AAClE,SAAO;AAAA;AAAA,EAEP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AAM,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,EAAE;AAAA,IACjD;AACA,QAAI,EAAE,QAAQ,OAAO,SAAS,GAAG;AAC/B,YAAM,KAAK,cAAc,EAAE,QAAQ,OAAO,KAAK,MAAM,CAAC,EAAE;AAAA,IAC1D;AACA,QAAI,EAAE,QAAQ,YAAY;AACxB,YAAM,KAAK,kBAAkB,EAAE,QAAQ,UAAU,EAAE;AAAA,IACrD;AACA,UAAM,KAAK,EAAE;AAAA,EACf,CAAC;AAED,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -347,4 +347,151 @@ declare function createSpacingRule(name: string, value: string): SpacingRule;
|
|
|
347
347
|
*/
|
|
348
348
|
declare function createComponentRule(name: string, styles: string[]): ComponentRule;
|
|
349
349
|
|
|
350
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Types for UI consistency analysis
|
|
352
|
+
*/
|
|
353
|
+
/**
|
|
354
|
+
* Relevant computed styles for consistency checking
|
|
355
|
+
*/
|
|
356
|
+
interface StyleSnapshot {
|
|
357
|
+
fontSize?: string;
|
|
358
|
+
fontWeight?: string;
|
|
359
|
+
color?: string;
|
|
360
|
+
backgroundColor?: string;
|
|
361
|
+
padding?: string;
|
|
362
|
+
borderRadius?: string;
|
|
363
|
+
border?: string;
|
|
364
|
+
boxShadow?: string;
|
|
365
|
+
gap?: string;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Element roles for grouping and analysis
|
|
369
|
+
*/
|
|
370
|
+
type ElementRole = "button" | "link" | "heading" | "input" | "card" | "container" | "text" | "other";
|
|
371
|
+
/**
|
|
372
|
+
* Snapshot of a single DOM element with its styles and context
|
|
373
|
+
*/
|
|
374
|
+
interface ElementSnapshot {
|
|
375
|
+
/** Unique ID mapping to data-elements attribute, e.g. "el-47" */
|
|
376
|
+
id: string;
|
|
377
|
+
/** HTML tag name */
|
|
378
|
+
tag: string;
|
|
379
|
+
/** Inferred semantic role */
|
|
380
|
+
role: ElementRole;
|
|
381
|
+
/** Truncated innerText (max 50 chars) */
|
|
382
|
+
text: string;
|
|
383
|
+
/** From data-ui-component attribute if present */
|
|
384
|
+
component?: string;
|
|
385
|
+
/** Ancestor context like "header > nav" */
|
|
386
|
+
context: string;
|
|
387
|
+
/** Relevant computed styles */
|
|
388
|
+
styles: StyleSnapshot;
|
|
389
|
+
/** Element dimensions */
|
|
390
|
+
rect: {
|
|
391
|
+
width: number;
|
|
392
|
+
height: number;
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Elements grouped by role for batch analysis
|
|
397
|
+
*/
|
|
398
|
+
interface GroupedSnapshot {
|
|
399
|
+
buttons: ElementSnapshot[];
|
|
400
|
+
headings: ElementSnapshot[];
|
|
401
|
+
cards: ElementSnapshot[];
|
|
402
|
+
links: ElementSnapshot[];
|
|
403
|
+
inputs: ElementSnapshot[];
|
|
404
|
+
containers: ElementSnapshot[];
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Violation categories detected by consistency analysis
|
|
408
|
+
*/
|
|
409
|
+
type ViolationCategory = "spacing" | "color" | "typography" | "sizing" | "borders" | "shadows";
|
|
410
|
+
/**
|
|
411
|
+
* Severity levels for violations
|
|
412
|
+
*/
|
|
413
|
+
type ViolationSeverity = "error" | "warning" | "info";
|
|
414
|
+
/**
|
|
415
|
+
* A consistency violation detected between similar elements
|
|
416
|
+
*/
|
|
417
|
+
interface Violation {
|
|
418
|
+
/** Element IDs involved in the violation, e.g. ["el-3", "el-7"] */
|
|
419
|
+
elementIds: string[];
|
|
420
|
+
/** Category of the inconsistency */
|
|
421
|
+
category: ViolationCategory;
|
|
422
|
+
/** Severity level */
|
|
423
|
+
severity: ViolationSeverity;
|
|
424
|
+
/** Human-readable description */
|
|
425
|
+
message: string;
|
|
426
|
+
/** Detailed information about the violation */
|
|
427
|
+
details: {
|
|
428
|
+
/** The CSS property that differs */
|
|
429
|
+
property: string;
|
|
430
|
+
/** The differing values found */
|
|
431
|
+
values: string[];
|
|
432
|
+
/** Optional suggestion for fixing */
|
|
433
|
+
suggestion?: string;
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Result of consistency analysis
|
|
438
|
+
*/
|
|
439
|
+
interface ConsistencyResult {
|
|
440
|
+
violations: Violation[];
|
|
441
|
+
/** Number of elements analyzed */
|
|
442
|
+
elementCount: number;
|
|
443
|
+
/** Time taken in milliseconds */
|
|
444
|
+
analysisTime: number;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* LLM prompt builders for UI consistency analysis
|
|
449
|
+
*/
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Builds a single prompt for analyzing ALL element groups
|
|
453
|
+
* This reduces LLM calls to 1 for better performance
|
|
454
|
+
*/
|
|
455
|
+
declare function buildConsistencyPrompt(snapshot: GroupedSnapshot): string;
|
|
456
|
+
/**
|
|
457
|
+
* Counts total elements across all groups
|
|
458
|
+
*/
|
|
459
|
+
declare function countElements(snapshot: GroupedSnapshot): number;
|
|
460
|
+
/**
|
|
461
|
+
* Checks if a snapshot has any groups worth analyzing (2+ elements)
|
|
462
|
+
*/
|
|
463
|
+
declare function hasAnalyzableGroups(snapshot: GroupedSnapshot): boolean;
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Consistency analysis logic - shared between CLI and API routes
|
|
467
|
+
*/
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Parses and validates a GroupedSnapshot from JSON string
|
|
471
|
+
*/
|
|
472
|
+
declare function parseGroupedSnapshot(json: string): GroupedSnapshot | null;
|
|
473
|
+
/**
|
|
474
|
+
* Parses violations from LLM response with defensive handling
|
|
475
|
+
*/
|
|
476
|
+
declare function parseViolationsResponse(response: string): Violation[];
|
|
477
|
+
/**
|
|
478
|
+
* Validates and filters violations to ensure correct structure
|
|
479
|
+
*/
|
|
480
|
+
declare function validateViolations(violations: unknown[]): Violation[];
|
|
481
|
+
interface AnalyzeConsistencyOptions {
|
|
482
|
+
/** Ollama model to use */
|
|
483
|
+
model?: string;
|
|
484
|
+
/** Ollama base URL */
|
|
485
|
+
baseUrl?: string;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Analyzes a grouped snapshot for UI consistency violations
|
|
489
|
+
* This is the main entry point for consistency analysis
|
|
490
|
+
*/
|
|
491
|
+
declare function analyzeConsistency(snapshot: GroupedSnapshot, options?: AnalyzeConsistencyOptions): Promise<ConsistencyResult>;
|
|
492
|
+
/**
|
|
493
|
+
* Formats violations for plain text output
|
|
494
|
+
*/
|
|
495
|
+
declare function formatConsistencyViolations(violations: Violation[]): string;
|
|
496
|
+
|
|
497
|
+
export { type AnalysisResult, type AnalyzeConsistencyOptions, type ColorRule, type ComponentRule, type ConsistencyResult, type DOMSnapshot, type ElementRole, type ElementSnapshot, type ExtractedStyleValues, type ExtractedStyles, type GroupedSnapshot, OllamaClient, type OllamaClientOptions, type SerializedStyles, type SpacingRule, type StreamProgressCallback, type StyleGuide, type StyleSnapshot, type TailwindThemeTokens, type TypographyRule, UILINT_DEFAULT_OLLAMA_MODEL, type UILintIssue, type Violation, type ViolationCategory, type ViolationSeverity, analyzeConsistency, buildAnalysisPrompt, buildConsistencyPrompt, buildSourceAnalysisPrompt, buildStyleGuidePrompt, countElements, createColorRule, createComponentRule, createEmptyStyleGuide, createSpacingRule, createStyleSummary, createTypographyRule, deserializeStyles, extractStyleValues, extractStyles, extractStylesFromDOM, extractTailwindAllowlist, formatConsistencyViolations, formatViolationsText, generateStyleGuideFromStyles, getOllamaClient, hasAnalyzableGroups, mergeStyleGuides, parseGroupedSnapshot, parseStyleGuide, parseStyleGuideSections, parseViolationsResponse, sanitizeIssues, serializeStyles, styleGuideToMarkdown, truncateHTML, validateStyleGuide, validateViolations };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
OllamaClient,
|
|
3
3
|
UILINT_DEFAULT_OLLAMA_MODEL,
|
|
4
|
+
analyzeConsistency,
|
|
4
5
|
buildAnalysisPrompt,
|
|
6
|
+
buildConsistencyPrompt,
|
|
5
7
|
buildSourceAnalysisPrompt,
|
|
6
8
|
buildStyleGuidePrompt,
|
|
9
|
+
countElements,
|
|
7
10
|
createColorRule,
|
|
8
11
|
createComponentRule,
|
|
9
12
|
createEmptyStyleGuide,
|
|
@@ -15,24 +18,32 @@ import {
|
|
|
15
18
|
extractStyles,
|
|
16
19
|
extractStylesFromDOM,
|
|
17
20
|
extractTailwindAllowlist,
|
|
21
|
+
formatConsistencyViolations,
|
|
18
22
|
formatViolationsText,
|
|
19
23
|
generateStyleGuideFromStyles,
|
|
20
24
|
getOllamaClient,
|
|
25
|
+
hasAnalyzableGroups,
|
|
21
26
|
mergeStyleGuides,
|
|
27
|
+
parseGroupedSnapshot,
|
|
22
28
|
parseStyleGuide,
|
|
23
29
|
parseStyleGuideSections,
|
|
30
|
+
parseViolationsResponse,
|
|
24
31
|
sanitizeIssues,
|
|
25
32
|
serializeStyles,
|
|
26
33
|
styleGuideToMarkdown,
|
|
27
34
|
truncateHTML,
|
|
28
|
-
validateStyleGuide
|
|
29
|
-
|
|
35
|
+
validateStyleGuide,
|
|
36
|
+
validateViolations
|
|
37
|
+
} from "./chunk-RTT2ZE6O.js";
|
|
30
38
|
export {
|
|
31
39
|
OllamaClient,
|
|
32
40
|
UILINT_DEFAULT_OLLAMA_MODEL,
|
|
41
|
+
analyzeConsistency,
|
|
33
42
|
buildAnalysisPrompt,
|
|
43
|
+
buildConsistencyPrompt,
|
|
34
44
|
buildSourceAnalysisPrompt,
|
|
35
45
|
buildStyleGuidePrompt,
|
|
46
|
+
countElements,
|
|
36
47
|
createColorRule,
|
|
37
48
|
createComponentRule,
|
|
38
49
|
createEmptyStyleGuide,
|
|
@@ -44,16 +55,21 @@ export {
|
|
|
44
55
|
extractStyles,
|
|
45
56
|
extractStylesFromDOM,
|
|
46
57
|
extractTailwindAllowlist,
|
|
58
|
+
formatConsistencyViolations,
|
|
47
59
|
formatViolationsText,
|
|
48
60
|
generateStyleGuideFromStyles,
|
|
49
61
|
getOllamaClient,
|
|
62
|
+
hasAnalyzableGroups,
|
|
50
63
|
mergeStyleGuides,
|
|
64
|
+
parseGroupedSnapshot,
|
|
51
65
|
parseStyleGuide,
|
|
52
66
|
parseStyleGuideSections,
|
|
67
|
+
parseViolationsResponse,
|
|
53
68
|
sanitizeIssues,
|
|
54
69
|
serializeStyles,
|
|
55
70
|
styleGuideToMarkdown,
|
|
56
71
|
truncateHTML,
|
|
57
|
-
validateStyleGuide
|
|
72
|
+
validateStyleGuide,
|
|
73
|
+
validateViolations
|
|
58
74
|
};
|
|
59
75
|
//# sourceMappingURL=index.js.map
|
package/dist/node.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DOMSnapshot, TailwindThemeTokens } from './index.js';
|
|
2
|
-
export { AnalysisResult, ColorRule, ComponentRule, ExtractedStyleValues, ExtractedStyles, OllamaClient, OllamaClientOptions, SerializedStyles, SpacingRule, StreamProgressCallback, StyleGuide, TypographyRule, UILINT_DEFAULT_OLLAMA_MODEL, UILintIssue, buildAnalysisPrompt, buildSourceAnalysisPrompt, buildStyleGuidePrompt, createColorRule, createComponentRule, createEmptyStyleGuide, createSpacingRule, createStyleSummary, createTypographyRule, deserializeStyles, extractStyleValues, extractStyles, extractStylesFromDOM, extractTailwindAllowlist, formatViolationsText, generateStyleGuideFromStyles, getOllamaClient, mergeStyleGuides, parseStyleGuide, parseStyleGuideSections, sanitizeIssues, serializeStyles, styleGuideToMarkdown, truncateHTML, validateStyleGuide } from './index.js';
|
|
2
|
+
export { AnalysisResult, AnalyzeConsistencyOptions, ColorRule, ComponentRule, ConsistencyResult, ElementRole, ElementSnapshot, ExtractedStyleValues, ExtractedStyles, GroupedSnapshot, OllamaClient, OllamaClientOptions, SerializedStyles, SpacingRule, StreamProgressCallback, StyleGuide, StyleSnapshot, TypographyRule, UILINT_DEFAULT_OLLAMA_MODEL, UILintIssue, Violation, ViolationCategory, ViolationSeverity, analyzeConsistency, buildAnalysisPrompt, buildConsistencyPrompt, buildSourceAnalysisPrompt, buildStyleGuidePrompt, countElements, createColorRule, createComponentRule, createEmptyStyleGuide, createSpacingRule, createStyleSummary, createTypographyRule, deserializeStyles, extractStyleValues, extractStyles, extractStylesFromDOM, extractTailwindAllowlist, formatConsistencyViolations, formatViolationsText, generateStyleGuideFromStyles, getOllamaClient, hasAnalyzableGroups, mergeStyleGuides, parseGroupedSnapshot, parseStyleGuide, parseStyleGuideSections, parseViolationsResponse, sanitizeIssues, serializeStyles, styleGuideToMarkdown, truncateHTML, validateStyleGuide, validateViolations } from './index.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Ollama bootstrapping utilities (Node.js only).
|
package/dist/node.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
OllamaClient,
|
|
3
3
|
UILINT_DEFAULT_OLLAMA_MODEL,
|
|
4
|
+
analyzeConsistency,
|
|
4
5
|
buildAnalysisPrompt,
|
|
6
|
+
buildConsistencyPrompt,
|
|
5
7
|
buildSourceAnalysisPrompt,
|
|
6
8
|
buildStyleGuidePrompt,
|
|
9
|
+
countElements,
|
|
7
10
|
createColorRule,
|
|
8
11
|
createComponentRule,
|
|
9
12
|
createEmptyStyleGuide,
|
|
@@ -15,18 +18,23 @@ import {
|
|
|
15
18
|
extractStyles,
|
|
16
19
|
extractStylesFromDOM,
|
|
17
20
|
extractTailwindAllowlist,
|
|
21
|
+
formatConsistencyViolations,
|
|
18
22
|
formatViolationsText,
|
|
19
23
|
generateStyleGuideFromStyles,
|
|
20
24
|
getOllamaClient,
|
|
25
|
+
hasAnalyzableGroups,
|
|
21
26
|
mergeStyleGuides,
|
|
27
|
+
parseGroupedSnapshot,
|
|
22
28
|
parseStyleGuide,
|
|
23
29
|
parseStyleGuideSections,
|
|
30
|
+
parseViolationsResponse,
|
|
24
31
|
sanitizeIssues,
|
|
25
32
|
serializeStyles,
|
|
26
33
|
styleGuideToMarkdown,
|
|
27
34
|
truncateHTML,
|
|
28
|
-
validateStyleGuide
|
|
29
|
-
|
|
35
|
+
validateStyleGuide,
|
|
36
|
+
validateViolations
|
|
37
|
+
} from "./chunk-RTT2ZE6O.js";
|
|
30
38
|
|
|
31
39
|
// src/ollama/bootstrap.ts
|
|
32
40
|
import { spawn, spawnSync } from "child_process";
|
|
@@ -416,9 +424,12 @@ export {
|
|
|
416
424
|
OllamaClient,
|
|
417
425
|
STYLEGUIDE_PATHS,
|
|
418
426
|
UILINT_DEFAULT_OLLAMA_MODEL,
|
|
427
|
+
analyzeConsistency,
|
|
419
428
|
buildAnalysisPrompt,
|
|
429
|
+
buildConsistencyPrompt,
|
|
420
430
|
buildSourceAnalysisPrompt,
|
|
421
431
|
buildStyleGuidePrompt,
|
|
432
|
+
countElements,
|
|
422
433
|
createColorRule,
|
|
423
434
|
createComponentRule,
|
|
424
435
|
createEmptyStyleGuide,
|
|
@@ -437,18 +448,22 @@ export {
|
|
|
437
448
|
findStyleGuidePath,
|
|
438
449
|
findTailwindConfigPath,
|
|
439
450
|
findWorkspaceRoot,
|
|
451
|
+
formatConsistencyViolations,
|
|
440
452
|
formatViolationsText,
|
|
441
453
|
generateStyleGuideFromStyles,
|
|
442
454
|
getDefaultStyleGuidePath,
|
|
443
455
|
getOllamaClient,
|
|
456
|
+
hasAnalyzableGroups,
|
|
444
457
|
hasStdin,
|
|
445
458
|
isJSON,
|
|
446
459
|
isOllamaInstalled,
|
|
447
460
|
mergeStyleGuides,
|
|
448
461
|
parseCLIInput,
|
|
462
|
+
parseGroupedSnapshot,
|
|
449
463
|
parseHTML,
|
|
450
464
|
parseStyleGuide,
|
|
451
465
|
parseStyleGuideSections,
|
|
466
|
+
parseViolationsResponse,
|
|
452
467
|
readStdin,
|
|
453
468
|
readStyleGuide,
|
|
454
469
|
readStyleGuideFromProject,
|
|
@@ -459,6 +474,7 @@ export {
|
|
|
459
474
|
styleGuideToMarkdown,
|
|
460
475
|
truncateHTML,
|
|
461
476
|
validateStyleGuide,
|
|
477
|
+
validateViolations,
|
|
462
478
|
writeStyleGuide
|
|
463
479
|
};
|
|
464
480
|
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ollama/bootstrap.ts","../src/scanner/html-parser.ts","../src/styleguide/reader.ts","../src/utils/workspace-root.ts","../src/tailwind/config-reader.ts"],"sourcesContent":["/**\n * Ollama bootstrapping utilities (Node.js only).\n *\n * Goals:\n * - Detect whether Ollama is installed.\n * - Ensure the Ollama daemon is running (best effort: start `ollama serve` detached).\n * - Ensure a given model is pulled (best effort: run `ollama pull <model>`).\n */\n\nimport { spawn, spawnSync } from \"child_process\";\nimport readline from \"readline\";\nimport { OllamaClient } from \"./client.js\";\nimport { UILINT_DEFAULT_OLLAMA_MODEL } from \"./defaults.js\";\n\nconst DEFAULT_OLLAMA_BASE_URL = \"http://localhost:11434\";\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isInteractiveTTY(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nasync function promptYesNo(question: string): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return await new Promise<boolean>((resolve) => {\n rl.question(`${question} (y/N) `, (answer) => {\n rl.close();\n const normalized = (answer || \"\").trim().toLowerCase();\n resolve(normalized === \"y\" || normalized === \"yes\");\n });\n });\n}\n\nexport function isOllamaInstalled(): boolean {\n const result = spawnSync(\"ollama\", [\"--version\"], { stdio: \"ignore\" });\n if (\n result.error &&\n (result.error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n return result.status === 0;\n}\n\nfunction isBrewInstalled(): boolean {\n const result = spawnSync(\"brew\", [\"--version\"], { stdio: \"ignore\" });\n if (\n result.error &&\n (result.error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n return result.status === 0;\n}\n\nfunction getInstallInstructions(): string[] {\n const lines: string[] = [\n \"Ollama is required for LLM-backed analysis.\",\n \"\",\n \"Install Ollama:\",\n \" - Download: https://ollama.ai\",\n ];\n\n if (process.platform === \"darwin\") {\n lines.push(\" - Homebrew: brew install ollama\");\n }\n\n lines.push(\"\");\n lines.push(\"Then start it:\");\n lines.push(\" ollama serve\");\n return lines;\n}\n\nasync function maybeInstallOllamaWithBrew(): Promise<boolean> {\n if (process.platform !== \"darwin\") return false;\n if (!isInteractiveTTY()) return false;\n\n if (!isBrewInstalled()) {\n // We can't auto-install without brew; leave instructions to the caller.\n return false;\n }\n\n const ok = await promptYesNo(\n \"Ollama is not installed. Install with Homebrew now?\"\n );\n if (!ok) return false;\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"brew\", [\"install\", \"ollama\"], { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`brew install ollama failed (exit ${code})`));\n });\n });\n\n return isOllamaInstalled();\n}\n\nexport async function ensureOllamaInstalledOrExplain(): Promise<void> {\n if (isOllamaInstalled()) return;\n\n const installedViaBrew = await maybeInstallOllamaWithBrew();\n if (installedViaBrew) return;\n\n const extra: string[] = [];\n if (process.platform === \"darwin\" && !isBrewInstalled()) {\n extra.push(\"\");\n extra.push(\"Homebrew is not installed. Install it first, then run:\");\n extra.push(\" brew install ollama\");\n }\n\n throw new Error([...getInstallInstructions(), ...extra].join(\"\\n\"));\n}\n\nexport async function ensureOllamaRunning(options?: {\n timeoutMs?: number;\n baseUrl?: string;\n}): Promise<void> {\n await ensureOllamaInstalledOrExplain();\n\n const baseUrl = options?.baseUrl || DEFAULT_OLLAMA_BASE_URL;\n const client = new OllamaClient({ baseUrl });\n const timeoutMs = options?.timeoutMs ?? 10_000;\n\n if (await client.isAvailable()) return;\n\n // Best-effort background start. We do not stop it later.\n try {\n const child = spawn(\"ollama\", [\"serve\"], {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n } catch (err) {\n throw new Error(\n `Failed to start Ollama automatically.\\n\\n${getInstallInstructions().join(\n \"\\n\"\n )}\\n\\nDetails: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (await client.isAvailable()) return;\n await sleep(250);\n }\n\n throw new Error(\n [\n \"Ollama did not become ready in time.\",\n \"\",\n \"Try starting it manually:\",\n \" ollama serve\",\n ].join(\"\\n\")\n );\n}\n\nasync function fetchOllamaTags(baseUrl: string): Promise<string[]> {\n const res = await fetch(`${baseUrl}/api/tags`, {\n method: \"GET\",\n signal: AbortSignal.timeout(5000),\n });\n\n if (!res.ok) {\n throw new Error(`Ollama tags endpoint returned ${res.status}`);\n }\n\n const data = (await res.json()) as { models?: Array<{ name?: string }> };\n const names = (data.models ?? [])\n .map((m) => m.name)\n .filter((n): n is string => typeof n === \"string\");\n return names;\n}\n\nexport async function ensureOllamaModelPulled(options?: {\n model?: string;\n baseUrl?: string;\n}): Promise<void> {\n const desired = (options?.model || UILINT_DEFAULT_OLLAMA_MODEL).trim();\n if (!desired) return;\n\n const baseUrl = options?.baseUrl || DEFAULT_OLLAMA_BASE_URL;\n const tags = await fetchOllamaTags(baseUrl);\n if (tags.includes(desired)) return;\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"ollama\", [\"pull\", desired], { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`ollama pull ${desired} failed (exit ${code})`));\n });\n });\n\n const tagsAfter = await fetchOllamaTags(baseUrl);\n if (!tagsAfter.includes(desired)) {\n throw new Error(\n `Model ${desired} did not appear in Ollama tags after pulling.`\n );\n }\n}\n\nexport async function ensureOllamaReady(options?: {\n model?: string;\n timeoutMs?: number;\n baseUrl?: string;\n}): Promise<void> {\n await ensureOllamaRunning({\n timeoutMs: options?.timeoutMs,\n baseUrl: options?.baseUrl,\n });\n await ensureOllamaModelPulled({\n model: options?.model,\n baseUrl: options?.baseUrl,\n });\n}\n","/**\n * HTML parser for extracting styles using JSDOM\n * Used by CLI and Node.js environments\n */\n\nimport { JSDOM } from \"jsdom\";\nimport type { ExtractedStyles, DOMSnapshot, SerializedStyles } from \"../types.js\";\nimport { extractStyles, deserializeStyles, truncateHTML } from \"./style-extractor.js\";\n\nexport interface ParseOptions {\n /**\n * If true, tries to load and process linked stylesheets\n */\n loadStylesheets?: boolean;\n /**\n * Max length for HTML in snapshot\n */\n maxHtmlLength?: number;\n}\n\n/**\n * Parses raw HTML and extracts styles using JSDOM\n */\nexport function parseHTML(\n html: string,\n options: ParseOptions = {}\n): DOMSnapshot {\n const { maxHtmlLength = 50000 } = options;\n\n const dom = new JSDOM(html, {\n runScripts: \"outside-only\",\n pretendToBeVisual: true,\n });\n\n const { document, getComputedStyle } = dom.window;\n const root = document.body || document.documentElement;\n\n const styles = extractStyles(root, getComputedStyle);\n const elementCount = root.querySelectorAll(\"*\").length;\n\n return {\n html: truncateHTML(html, maxHtmlLength),\n styles,\n elementCount,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Input format for CLI - can be raw HTML or pre-extracted JSON\n */\nexport interface CLIInput {\n html: string;\n styles?: SerializedStyles;\n}\n\n/**\n * Parses CLI input which can be either raw HTML or JSON with pre-extracted styles\n */\nexport function parseCLIInput(input: string): DOMSnapshot {\n // Try to parse as JSON first\n try {\n const parsed = JSON.parse(input) as CLIInput;\n \n if (parsed.html && parsed.styles) {\n // Pre-extracted styles from browser/test environment\n return {\n html: truncateHTML(parsed.html),\n styles: deserializeStyles(parsed.styles),\n elementCount: 0, // Not available for pre-extracted\n timestamp: Date.now(),\n };\n } else if (parsed.html) {\n // Just HTML in JSON format\n return parseHTML(parsed.html);\n }\n } catch {\n // Not JSON, treat as raw HTML\n }\n\n // Parse as raw HTML\n return parseHTML(input);\n}\n\n/**\n * Checks if a string looks like JSON\n */\nexport function isJSON(str: string): boolean {\n const trimmed = str.trim();\n return trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\");\n}\n\n/**\n * Reads input from stdin\n */\nexport async function readStdin(): Promise<string> {\n const chunks: Uint8Array[] = [];\n \n return new Promise((resolve, reject) => {\n process.stdin.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n });\n process.stdin.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf-8\")));\n process.stdin.on(\"error\", reject);\n });\n}\n\n/**\n * Detects if stdin has data\n */\nexport function hasStdin(): boolean {\n return !process.stdin.isTTY;\n}\n\n","/**\n * Style guide file operations\n */\n\nimport { readFile, writeFile, mkdir } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { join, dirname } from \"path\";\n\nexport const STYLEGUIDE_PATHS = [\n \".uilint/styleguide.md\",\n \"styleguide.md\",\n \".uilint/style-guide.md\",\n];\n\n/**\n * Finds the style guide file in a project\n */\nexport function findStyleGuidePath(projectPath: string): string | null {\n for (const relativePath of STYLEGUIDE_PATHS) {\n const fullPath = join(projectPath, relativePath);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Reads the style guide content\n */\nexport async function readStyleGuide(path: string): Promise<string> {\n return readFile(path, \"utf-8\");\n}\n\n/**\n * Reads style guide from project path, finding it automatically\n */\nexport async function readStyleGuideFromProject(\n projectPath: string\n): Promise<string | null> {\n const path = findStyleGuidePath(projectPath);\n if (!path) return null;\n return readStyleGuide(path);\n}\n\n/**\n * Writes style guide content to file\n */\nexport async function writeStyleGuide(path: string, content: string): Promise<void> {\n const dir = dirname(path);\n await mkdir(dir, { recursive: true });\n await writeFile(path, content, \"utf-8\");\n}\n\n/**\n * Gets the default style guide path for a project\n */\nexport function getDefaultStyleGuidePath(projectPath: string): string {\n return join(projectPath, \".uilint\", \"styleguide.md\");\n}\n\n/**\n * Checks if a style guide exists\n */\nexport function styleGuideExists(projectPath: string): boolean {\n return findStyleGuidePath(projectPath) !== null;\n}\n\n","/**\n * Resolve the workspace/repo root from an arbitrary starting directory.\n *\n * This is primarily used in monorepos where runtime `process.cwd()` may point at\n * a sub-app (e.g. `apps/web`) but UI linting assets live at the workspace root.\n */\nimport { existsSync, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nfunction hasWorkspacesField(dir: string): boolean {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as { workspaces?: unknown };\n return !!pkg.workspaces;\n } catch {\n return false;\n }\n}\n\nfunction hasRootMarker(dir: string): boolean {\n // pnpm is the primary supported monorepo layout in this repo\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return true;\n // fallbacks for other setups\n if (existsSync(join(dir, \".git\"))) return true;\n if (hasWorkspacesField(dir)) return true;\n return false;\n}\n\n/**\n * Walks up from `startDir` to find a likely workspace root.\n *\n * If none is found, returns `startDir`.\n */\nexport function findWorkspaceRoot(startDir: string): string {\n let dir = startDir;\n let lastFallback: string | null = null;\n\n for (;;) {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return dir;\n\n if (hasRootMarker(dir)) {\n // keep walking to prefer the highest-level marker (esp. .git)\n lastFallback = dir;\n }\n\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n return lastFallback || startDir;\n}\n","/**\n * Tailwind config reader (Node-only).\n *\n * Goals:\n * - Locate a Tailwind config file near a project directory.\n * - Load it (supports .ts via jiti).\n * - Produce compact token sets for styleguide + validation.\n *\n * Note: We intentionally extract tokens primarily from user-defined theme / extend\n * to avoid dumping Tailwind's full default palette into the style guide.\n */\n\nimport { existsSync } from \"fs\";\nimport { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport jiti from \"jiti\";\nimport type { TailwindThemeTokens } from \"../types.js\";\n\nconst CONFIG_CANDIDATES = [\n \"tailwind.config.ts\",\n \"tailwind.config.mts\",\n \"tailwind.config.cts\",\n \"tailwind.config.js\",\n \"tailwind.config.mjs\",\n \"tailwind.config.cjs\",\n];\n\nexport function findTailwindConfigPath(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of CONFIG_CANDIDATES) {\n const full = join(dir, name);\n if (existsSync(full)) return full;\n }\n\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nexport function readTailwindThemeTokens(\n projectDir: string\n): TailwindThemeTokens | null {\n const configPath = findTailwindConfigPath(projectDir);\n if (!configPath) return null;\n\n const loader = jiti(import.meta.url, { interopDefault: true });\n const loaded = loader(configPath) as any;\n const config = (loaded?.default ?? loaded) as any;\n if (!config || typeof config !== \"object\") return null;\n\n // Best-effort: run resolveConfig to ensure config is valid/normalized.\n // We don’t use the resolved theme for token enumeration (to avoid defaults),\n // but we do want to surface loader/shape problems early for debugging.\n try {\n const require = createRequire(import.meta.url);\n const maybe = require(\"tailwindcss/resolveConfig\");\n const resolveConfig = (maybe?.default ?? maybe) as\n | ((cfg: any) => any)\n | undefined;\n if (typeof resolveConfig === \"function\") resolveConfig(config);\n } catch {\n // If resolve fails, still attempt to extract from raw object.\n }\n\n const theme =\n config.theme && typeof config.theme === \"object\" ? config.theme : {};\n const extend =\n theme.extend && typeof theme.extend === \"object\" ? theme.extend : {};\n\n const colors = new Set<string>();\n const spacingKeys = new Set<string>();\n const borderRadiusKeys = new Set<string>();\n const fontFamilyKeys = new Set<string>();\n const fontSizeKeys = new Set<string>();\n\n // Merge base + extend per category.\n addColorTokens(colors, theme.colors);\n addColorTokens(colors, extend.colors);\n\n addKeys(spacingKeys, theme.spacing);\n addKeys(spacingKeys, extend.spacing);\n\n addKeys(borderRadiusKeys, theme.borderRadius);\n addKeys(borderRadiusKeys, extend.borderRadius);\n\n addKeys(fontFamilyKeys, theme.fontFamily);\n addKeys(fontFamilyKeys, extend.fontFamily);\n\n addKeys(fontSizeKeys, theme.fontSize);\n addKeys(fontSizeKeys, extend.fontSize);\n\n // If user config didn’t specify tokens, we still return an object to signal\n // \"tailwind detected\", but with empty sets (downstream can choose defaults).\n return {\n configPath,\n colors: [...colors],\n spacingKeys: [...spacingKeys],\n borderRadiusKeys: [...borderRadiusKeys],\n fontFamilyKeys: [...fontFamilyKeys],\n fontSizeKeys: [...fontSizeKeys],\n };\n}\n\nfunction addKeys(out: Set<string>, obj: unknown): void {\n if (!obj || typeof obj !== \"object\") return;\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n if (!key) continue;\n out.add(key);\n }\n}\n\nfunction addColorTokens(out: Set<string>, colors: unknown): void {\n if (!colors || typeof colors !== \"object\") return;\n\n for (const [name, value] of Object.entries(\n colors as Record<string, unknown>\n )) {\n if (!name) continue;\n\n if (typeof value === \"string\") {\n out.add(`tailwind:${name}`);\n continue;\n }\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n for (const shade of Object.keys(value as Record<string, unknown>)) {\n if (!shade) continue;\n out.add(`tailwind:${name}-${shade}`);\n }\n continue;\n }\n\n // Arrays / functions etc are ignored for token enumeration.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,SAAS,OAAO,iBAAiB;AACjC,OAAO,cAAc;AAIrB,IAAM,0BAA0B;AAEhC,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,mBAA4B;AACnC,SAAO,QAAQ,QAAQ,MAAM,SAAS,QAAQ,OAAO,KAAK;AAC5D;AAEA,eAAe,YAAY,UAAoC;AAC7D,QAAM,KAAK,SAAS,gBAAgB;AAAA,IAClC,OAAO,QAAQ;AAAA,IACf,QAAQ,QAAQ;AAAA,EAClB,CAAC;AACD,SAAO,MAAM,IAAI,QAAiB,CAAC,YAAY;AAC7C,OAAG,SAAS,GAAG,QAAQ,WAAW,CAAC,WA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cAAc;AAAA,IAClC,cAAc,CAAC,GAAG,YAAY;AAAA,EAChC;AACF;AAEA,SAAS,QAAQ,KAAkB,KAAoB;AACrD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU;AACrC,aAAW,OAAO,OAAO,KAAK,GAA8B,GAAG;AAC7D,QAAI,CAAC,IAAK;AACV,QAAI,IAAI,GAAG;AAAA,EACb;AACF;AAEA,SAAS,eAAe,KAAkB,QAAuB;AAC/D,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAE3C,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO;AAAA,IACjC;AAAA,EACF,GAAG;AACD,QAAI,CAAC,KAAM;AAEX,QAAI,OAAO,UAAU,UAAU;AAC7B,UAAI,IAAI,YAAY,IAAI,EAAE;AAC1B;AAAA,IACF;AAEA,QAAI,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,GAAG;AAC/D,iBAAW,SAAS,OAAO,KAAK,KAAgC,GAAG;AACjE,YAAI,CAAC,MAAO;AACZ,YAAI,IAAI,YAAY,IAAI,IAAI,KAAK,EAAE;AAAA,MACrC;AACA;AAAA,IACF;AAAA,EAGF;AACF;","names":["existsSync","dirname","join","existsSync","dirname","join","require"]}
|
|
1
|
+
{"version":3,"sources":["../src/ollama/bootstrap.ts","../src/scanner/html-parser.ts","../src/styleguide/reader.ts","../src/utils/workspace-root.ts","../src/tailwind/config-reader.ts"],"sourcesContent":["/**\n * Ollama bootstrapping utilities (Node.js only).\n *\n * Goals:\n * - Detect whether Ollama is installed.\n * - Ensure the Ollama daemon is running (best effort: start `ollama serve` detached).\n * - Ensure a given model is pulled (best effort: run `ollama pull <model>`).\n */\n\nimport { spawn, spawnSync } from \"child_process\";\nimport readline from \"readline\";\nimport { OllamaClient } from \"./client.js\";\nimport { UILINT_DEFAULT_OLLAMA_MODEL } from \"./defaults.js\";\n\nconst DEFAULT_OLLAMA_BASE_URL = \"http://localhost:11434\";\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isInteractiveTTY(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nasync function promptYesNo(question: string): Promise<boolean> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return await new Promise<boolean>((resolve) => {\n rl.question(`${question} (y/N) `, (answer) => {\n rl.close();\n const normalized = (answer || \"\").trim().toLowerCase();\n resolve(normalized === \"y\" || normalized === \"yes\");\n });\n });\n}\n\nexport function isOllamaInstalled(): boolean {\n const result = spawnSync(\"ollama\", [\"--version\"], { stdio: \"ignore\" });\n if (\n result.error &&\n (result.error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n return result.status === 0;\n}\n\nfunction isBrewInstalled(): boolean {\n const result = spawnSync(\"brew\", [\"--version\"], { stdio: \"ignore\" });\n if (\n result.error &&\n (result.error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n return result.status === 0;\n}\n\nfunction getInstallInstructions(): string[] {\n const lines: string[] = [\n \"Ollama is required for LLM-backed analysis.\",\n \"\",\n \"Install Ollama:\",\n \" - Download: https://ollama.ai\",\n ];\n\n if (process.platform === \"darwin\") {\n lines.push(\" - Homebrew: brew install ollama\");\n }\n\n lines.push(\"\");\n lines.push(\"Then start it:\");\n lines.push(\" ollama serve\");\n return lines;\n}\n\nasync function maybeInstallOllamaWithBrew(): Promise<boolean> {\n if (process.platform !== \"darwin\") return false;\n if (!isInteractiveTTY()) return false;\n\n if (!isBrewInstalled()) {\n // We can't auto-install without brew; leave instructions to the caller.\n return false;\n }\n\n const ok = await promptYesNo(\n \"Ollama is not installed. Install with Homebrew now?\"\n );\n if (!ok) return false;\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"brew\", [\"install\", \"ollama\"], { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`brew install ollama failed (exit ${code})`));\n });\n });\n\n return isOllamaInstalled();\n}\n\nexport async function ensureOllamaInstalledOrExplain(): Promise<void> {\n if (isOllamaInstalled()) return;\n\n const installedViaBrew = await maybeInstallOllamaWithBrew();\n if (installedViaBrew) return;\n\n const extra: string[] = [];\n if (process.platform === \"darwin\" && !isBrewInstalled()) {\n extra.push(\"\");\n extra.push(\"Homebrew is not installed. Install it first, then run:\");\n extra.push(\" brew install ollama\");\n }\n\n throw new Error([...getInstallInstructions(), ...extra].join(\"\\n\"));\n}\n\nexport async function ensureOllamaRunning(options?: {\n timeoutMs?: number;\n baseUrl?: string;\n}): Promise<void> {\n await ensureOllamaInstalledOrExplain();\n\n const baseUrl = options?.baseUrl || DEFAULT_OLLAMA_BASE_URL;\n const client = new OllamaClient({ baseUrl });\n const timeoutMs = options?.timeoutMs ?? 10_000;\n\n if (await client.isAvailable()) return;\n\n // Best-effort background start. We do not stop it later.\n try {\n const child = spawn(\"ollama\", [\"serve\"], {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n } catch (err) {\n throw new Error(\n `Failed to start Ollama automatically.\\n\\n${getInstallInstructions().join(\n \"\\n\"\n )}\\n\\nDetails: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (await client.isAvailable()) return;\n await sleep(250);\n }\n\n throw new Error(\n [\n \"Ollama did not become ready in time.\",\n \"\",\n \"Try starting it manually:\",\n \" ollama serve\",\n ].join(\"\\n\")\n );\n}\n\nasync function fetchOllamaTags(baseUrl: string): Promise<string[]> {\n const res = await fetch(`${baseUrl}/api/tags`, {\n method: \"GET\",\n signal: AbortSignal.timeout(5000),\n });\n\n if (!res.ok) {\n throw new Error(`Ollama tags endpoint returned ${res.status}`);\n }\n\n const data = (await res.json()) as { models?: Array<{ name?: string }> };\n const names = (data.models ?? [])\n .map((m) => m.name)\n .filter((n): n is string => typeof n === \"string\");\n return names;\n}\n\nexport async function ensureOllamaModelPulled(options?: {\n model?: string;\n baseUrl?: string;\n}): Promise<void> {\n const desired = (options?.model || UILINT_DEFAULT_OLLAMA_MODEL).trim();\n if (!desired) return;\n\n const baseUrl = options?.baseUrl || DEFAULT_OLLAMA_BASE_URL;\n const tags = await fetchOllamaTags(baseUrl);\n if (tags.includes(desired)) return;\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(\"ollama\", [\"pull\", desired], { stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`ollama pull ${desired} failed (exit ${code})`));\n });\n });\n\n const tagsAfter = await fetchOllamaTags(baseUrl);\n if (!tagsAfter.includes(desired)) {\n throw new Error(\n `Model ${desired} did not appear in Ollama tags after pulling.`\n );\n }\n}\n\nexport async function ensureOllamaReady(options?: {\n model?: string;\n timeoutMs?: number;\n baseUrl?: string;\n}): Promise<void> {\n await ensureOllamaRunning({\n timeoutMs: options?.timeoutMs,\n baseUrl: options?.baseUrl,\n });\n await ensureOllamaModelPulled({\n model: options?.model,\n baseUrl: options?.baseUrl,\n });\n}\n","/**\n * HTML parser for extracting styles using JSDOM\n * Used by CLI and Node.js environments\n */\n\nimport { JSDOM } from \"jsdom\";\nimport type { ExtractedStyles, DOMSnapshot, SerializedStyles } from \"../types.js\";\nimport { extractStyles, deserializeStyles, truncateHTML } from \"./style-extractor.js\";\n\nexport interface ParseOptions {\n /**\n * If true, tries to load and process linked stylesheets\n */\n loadStylesheets?: boolean;\n /**\n * Max length for HTML in snapshot\n */\n maxHtmlLength?: number;\n}\n\n/**\n * Parses raw HTML and extracts styles using JSDOM\n */\nexport function parseHTML(\n html: string,\n options: ParseOptions = {}\n): DOMSnapshot {\n const { maxHtmlLength = 50000 } = options;\n\n const dom = new JSDOM(html, {\n runScripts: \"outside-only\",\n pretendToBeVisual: true,\n });\n\n const { document, getComputedStyle } = dom.window;\n const root = document.body || document.documentElement;\n\n const styles = extractStyles(root, getComputedStyle);\n const elementCount = root.querySelectorAll(\"*\").length;\n\n return {\n html: truncateHTML(html, maxHtmlLength),\n styles,\n elementCount,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Input format for CLI - can be raw HTML or pre-extracted JSON\n */\nexport interface CLIInput {\n html: string;\n styles?: SerializedStyles;\n}\n\n/**\n * Parses CLI input which can be either raw HTML or JSON with pre-extracted styles\n */\nexport function parseCLIInput(input: string): DOMSnapshot {\n // Try to parse as JSON first\n try {\n const parsed = JSON.parse(input) as CLIInput;\n \n if (parsed.html && parsed.styles) {\n // Pre-extracted styles from browser/test environment\n return {\n html: truncateHTML(parsed.html),\n styles: deserializeStyles(parsed.styles),\n elementCount: 0, // Not available for pre-extracted\n timestamp: Date.now(),\n };\n } else if (parsed.html) {\n // Just HTML in JSON format\n return parseHTML(parsed.html);\n }\n } catch {\n // Not JSON, treat as raw HTML\n }\n\n // Parse as raw HTML\n return parseHTML(input);\n}\n\n/**\n * Checks if a string looks like JSON\n */\nexport function isJSON(str: string): boolean {\n const trimmed = str.trim();\n return trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\");\n}\n\n/**\n * Reads input from stdin\n */\nexport async function readStdin(): Promise<string> {\n const chunks: Uint8Array[] = [];\n \n return new Promise((resolve, reject) => {\n process.stdin.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n });\n process.stdin.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf-8\")));\n process.stdin.on(\"error\", reject);\n });\n}\n\n/**\n * Detects if stdin has data\n */\nexport function hasStdin(): boolean {\n return !process.stdin.isTTY;\n}\n\n","/**\n * Style guide file operations\n */\n\nimport { readFile, writeFile, mkdir } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { join, dirname } from \"path\";\n\nexport const STYLEGUIDE_PATHS = [\n \".uilint/styleguide.md\",\n \"styleguide.md\",\n \".uilint/style-guide.md\",\n];\n\n/**\n * Finds the style guide file in a project\n */\nexport function findStyleGuidePath(projectPath: string): string | null {\n for (const relativePath of STYLEGUIDE_PATHS) {\n const fullPath = join(projectPath, relativePath);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Reads the style guide content\n */\nexport async function readStyleGuide(path: string): Promise<string> {\n return readFile(path, \"utf-8\");\n}\n\n/**\n * Reads style guide from project path, finding it automatically\n */\nexport async function readStyleGuideFromProject(\n projectPath: string\n): Promise<string | null> {\n const path = findStyleGuidePath(projectPath);\n if (!path) return null;\n return readStyleGuide(path);\n}\n\n/**\n * Writes style guide content to file\n */\nexport async function writeStyleGuide(path: string, content: string): Promise<void> {\n const dir = dirname(path);\n await mkdir(dir, { recursive: true });\n await writeFile(path, content, \"utf-8\");\n}\n\n/**\n * Gets the default style guide path for a project\n */\nexport function getDefaultStyleGuidePath(projectPath: string): string {\n return join(projectPath, \".uilint\", \"styleguide.md\");\n}\n\n/**\n * Checks if a style guide exists\n */\nexport function styleGuideExists(projectPath: string): boolean {\n return findStyleGuidePath(projectPath) !== null;\n}\n\n","/**\n * Resolve the workspace/repo root from an arbitrary starting directory.\n *\n * This is primarily used in monorepos where runtime `process.cwd()` may point at\n * a sub-app (e.g. `apps/web`) but UI linting assets live at the workspace root.\n */\nimport { existsSync, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nfunction hasWorkspacesField(dir: string): boolean {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n try {\n const raw = readFileSync(pkgPath, \"utf-8\");\n const pkg = JSON.parse(raw) as { workspaces?: unknown };\n return !!pkg.workspaces;\n } catch {\n return false;\n }\n}\n\nfunction hasRootMarker(dir: string): boolean {\n // pnpm is the primary supported monorepo layout in this repo\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return true;\n // fallbacks for other setups\n if (existsSync(join(dir, \".git\"))) return true;\n if (hasWorkspacesField(dir)) return true;\n return false;\n}\n\n/**\n * Walks up from `startDir` to find a likely workspace root.\n *\n * If none is found, returns `startDir`.\n */\nexport function findWorkspaceRoot(startDir: string): string {\n let dir = startDir;\n let lastFallback: string | null = null;\n\n for (;;) {\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return dir;\n\n if (hasRootMarker(dir)) {\n // keep walking to prefer the highest-level marker (esp. .git)\n lastFallback = dir;\n }\n\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n return lastFallback || startDir;\n}\n","/**\n * Tailwind config reader (Node-only).\n *\n * Goals:\n * - Locate a Tailwind config file near a project directory.\n * - Load it (supports .ts via jiti).\n * - Produce compact token sets for styleguide + validation.\n *\n * Note: We intentionally extract tokens primarily from user-defined theme / extend\n * to avoid dumping Tailwind's full default palette into the style guide.\n */\n\nimport { existsSync } from \"fs\";\nimport { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport jiti from \"jiti\";\nimport type { TailwindThemeTokens } from \"../types.js\";\n\nconst CONFIG_CANDIDATES = [\n \"tailwind.config.ts\",\n \"tailwind.config.mts\",\n \"tailwind.config.cts\",\n \"tailwind.config.js\",\n \"tailwind.config.mjs\",\n \"tailwind.config.cjs\",\n];\n\nexport function findTailwindConfigPath(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of CONFIG_CANDIDATES) {\n const full = join(dir, name);\n if (existsSync(full)) return full;\n }\n\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nexport function readTailwindThemeTokens(\n projectDir: string\n): TailwindThemeTokens | null {\n const configPath = findTailwindConfigPath(projectDir);\n if (!configPath) return null;\n\n const loader = jiti(import.meta.url, { interopDefault: true });\n const loaded = loader(configPath) as any;\n const config = (loaded?.default ?? loaded) as any;\n if (!config || typeof config !== \"object\") return null;\n\n // Best-effort: run resolveConfig to ensure config is valid/normalized.\n // We don’t use the resolved theme for token enumeration (to avoid defaults),\n // but we do want to surface loader/shape problems early for debugging.\n try {\n const require = createRequire(import.meta.url);\n const maybe = require(\"tailwindcss/resolveConfig\");\n const resolveConfig = (maybe?.default ?? maybe) as\n | ((cfg: any) => any)\n | undefined;\n if (typeof resolveConfig === \"function\") resolveConfig(config);\n } catch {\n // If resolve fails, still attempt to extract from raw object.\n }\n\n const theme =\n config.theme && typeof config.theme === \"object\" ? config.theme : {};\n const extend =\n theme.extend && typeof theme.extend === \"object\" ? theme.extend : {};\n\n const colors = new Set<string>();\n const spacingKeys = new Set<string>();\n const borderRadiusKeys = new Set<string>();\n const fontFamilyKeys = new Set<string>();\n const fontSizeKeys = new Set<string>();\n\n // Merge base + extend per category.\n addColorTokens(colors, theme.colors);\n addColorTokens(colors, extend.colors);\n\n addKeys(spacingKeys, theme.spacing);\n addKeys(spacingKeys, extend.spacing);\n\n addKeys(borderRadiusKeys, theme.borderRadius);\n addKeys(borderRadiusKeys, extend.borderRadius);\n\n addKeys(fontFamilyKeys, theme.fontFamily);\n addKeys(fontFamilyKeys, extend.fontFamily);\n\n addKeys(fontSizeKeys, theme.fontSize);\n addKeys(fontSizeKeys, extend.fontSize);\n\n // If user config didn’t specify tokens, we still return an object to signal\n // \"tailwind detected\", but with empty sets (downstream can choose defaults).\n return {\n configPath,\n colors: [...colors],\n spacingKeys: [...spacingKeys],\n borderRadiusKeys: [...borderRadiusKeys],\n fontFamilyKeys: [...fontFamilyKeys],\n fontSizeKeys: [...fontSizeKeys],\n };\n}\n\nfunction addKeys(out: Set<string>, obj: unknown): void {\n if (!obj || typeof obj !== \"object\") return;\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n if (!key) continue;\n out.add(key);\n }\n}\n\nfunction addColorTokens(out: Set<string>, colors: unknown): void {\n if (!colors || typeof colors !== \"object\") return;\n\n for (const [name, value] of Object.entries(\n colors as Record<string, unknown>\n )) {\n if (!name) continue;\n\n if (typeof value === \"string\") {\n out.add(`tailwind:${name}`);\n continue;\n }\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n for (const shade of Object.keys(value as Record<string, unknown>)) {\n if (!shade) continue;\n out.add(`tailwind:${name}-${shade}`);\n }\n continue;\n }\n\n // Arrays / functions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MACrC;AACA;AAAA,IACF;AAAA,EAGF;AACF;","names":["existsSync","dirname","join","existsSync","dirname","join","require"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ollama/prompts.ts","../src/ollama/defaults.ts","../src/ollama/client.ts","../src/format/issues.ts","../src/tailwind/class-tokens.ts","../src/scanner/style-extractor.ts","../src/styleguide/schema.ts","../src/styleguide/parser.ts","../src/styleguide/generator.ts"],"sourcesContent":["/**\n * LLM prompt builders for UILint analysis\n */\n\n/**\n * Builds a prompt for style analysis\n */\nexport function buildAnalysisPrompt(\n styleSummary: string,\n styleGuide: string | null\n): string {\n const guideSection = styleGuide\n ? `## Current Style Guide\\n${styleGuide}\\n\\n`\n : \"## No Style Guide Found\\nAnalyze the styles and identify inconsistencies.\\n\\n\";\n\n return `You are a UI consistency analyzer. Analyze the following extracted styles and identify UI consistency violations.\n\n${guideSection}\n\n${styleSummary}\n\nRespond with JSON ONLY. Return a single JSON object containing an \"issues\" array. Each issue should have:\n- id: unique string identifier\n- type: one of \"color\", \"typography\", \"spacing\", \"component\", \"responsive\", \"accessibility\"\n- message: human-readable description of the issue\n- currentValue: the problematic value found\n- expectedValue: what it should be (if known from style guide)\n\nIMPORTANT:\n- Output ONLY violations. Do NOT include fix instructions, remediation steps, or \"suggestions\".\n- Do NOT include extra top-level keys. Only return {\"issues\":[...]}.\n- Keep messages short and neutral.\n\nFocus on:\n1. Similar but not identical colors (e.g., #3B82F6 vs #3575E2)\n2. Inconsistent font sizes or weights\n3. Spacing values that don't follow a consistent scale (e.g., 4px base unit)\n4. Mixed border-radius values\n5. If utility/Tailwind classes are present in the summary, treat them as the styling surface area and flag inconsistent utility usage (e.g., mixing px-4 and px-5 for the same component type)\n\nBe minimal. Only report significant inconsistencies.\n\nExample response:\n{\n \"issues\": [\n {\n \"id\": \"color-1\",\n \"type\": \"color\",\n \"message\": \"Found similar blue colors that should be consolidated\",\n \"currentValue\": \"#3575E2\",\n \"expectedValue\": \"#3B82F6\"\n }\n ]\n}`;\n}\n\nexport interface BuildSourceAnalysisPromptOptions {\n /**\n * Optional filename/path for extra context in the prompt.\n */\n filePath?: string;\n /**\n * Optional hint about language (e.g. tsx, jsx, html).\n */\n languageHint?: string;\n /**\n * Optional additional context (e.g., Tailwind tokens, extracted utilities).\n * Keep this concise; it's appended verbatim.\n */\n extraContext?: string;\n}\n\n/**\n * Builds a prompt for analyzing a raw source file/snippet (TSX/JSX/etc) directly,\n * without attempting to parse it as HTML/DOM.\n */\nexport function buildSourceAnalysisPrompt(\n source: string,\n styleGuide: string | null,\n options: BuildSourceAnalysisPromptOptions = {}\n): string {\n const guideSection = styleGuide\n ? `## Current Style Guide\\n${styleGuide}\\n\\n`\n : \"## No Style Guide Found\\nAnalyze the UI code and identify inconsistencies.\\n\\n\";\n\n const metaLines: string[] = [];\n if (options.filePath) metaLines.push(`- filePath: ${options.filePath}`);\n if (options.languageHint)\n metaLines.push(`- languageHint: ${options.languageHint}`);\n const metaSection =\n metaLines.length > 0\n ? `## Source Metadata\\n${metaLines.join(\"\\n\")}\\n\\n`\n : \"\";\n\n const extra =\n options.extraContext && options.extraContext.trim()\n ? `## Additional Context\\n${options.extraContext.trim()}\\n\\n`\n : \"\";\n\n return `You are a UI consistency analyzer. Analyze the following UI source code and identify UI consistency violations.\n\n${guideSection}${metaSection}${extra}## Source Code (raw)\n${source}\n\nRespond with JSON ONLY. Return a single JSON object containing an \"issues\" array. Each issue should have:\n- id: unique string identifier\n- type: one of \"color\", \"typography\", \"spacing\", \"component\", \"responsive\", \"accessibility\"\n- message: human-readable description of the issue\n- currentValue: the problematic value found\n- expectedValue: what it should be (if known from style guide)\n\nIMPORTANT:\n- Output ONLY violations. Do NOT include fix instructions, remediation steps, or \"suggestions\".\n- Do NOT include extra top-level keys. Only return {\"issues\":[...]}.\n- Keep messages short and neutral.\n\nFocus on:\n1. Inconsistent Tailwind/utility classes (e.g., mixing px-4 and px-5 for the same component type)\n2. Inconsistent component variants (e.g., button sizes/radii/typography drift)\n3. Hardcoded colors/spacing/typography that should use tokens/scale\n4. Accessibility issues visible from code (e.g., missing labels, low-contrast combos if obvious)\n\nBe minimal. Only report significant inconsistencies.`;\n}\n\n/**\n * Builds a prompt for style guide generation\n */\nexport function buildStyleGuidePrompt(styleSummary: string): string {\n return `You are a design system expert. Based on the following detected styles, generate a clean, organized style guide in Markdown format.\n\n${styleSummary}\n\nGenerate a style guide with these sections:\n1. Colors - List the main colors with semantic names (Primary, Secondary, etc.)\n2. Typography - Font families, sizes, and weights\n3. Spacing - Base unit and common spacing values\n4. Components - Common component patterns\n5. Tailwind (if utility classes are present) - list commonly used utilities and any relevant theme tokens\n\nUse this format:\n# UI Style Guide\n\n## Colors\n- **Primary**: #HEXCODE (usage description)\n- **Secondary**: #HEXCODE (usage description)\n...\n\n## Typography\n- **Font Family**: FontName\n- **Font Sizes**: list of sizes\n- **Font Weights**: list of weights\n\n## Spacing\n- **Base unit**: Xpx\n- **Common values**: list of values\n\n## Components\n- **Buttons**: styles\n- **Cards**: styles\n...\n\nBe concise and focus on the most used values.`;\n}\n","/**\n * Single source of truth for Ollama defaults used across the monorepo.\n */\n\n/**\n * Default Ollama model used when none is provided.\n *\n * Note: This should match the model we recommend users `ollama pull`.\n */\nexport const UILINT_DEFAULT_OLLAMA_MODEL = \"qwen3-coder:30b\";\n","/**\n * Ollama API client for LLM interactions\n */\n\nimport type {\n UILintIssue,\n AnalysisResult,\n OllamaClientOptions,\n StreamProgressCallback,\n} from \"../types.js\";\nimport {\n buildAnalysisPrompt,\n buildSourceAnalysisPrompt,\n buildStyleGuidePrompt,\n type BuildSourceAnalysisPromptOptions,\n} from \"./prompts.js\";\nimport { UILINT_DEFAULT_OLLAMA_MODEL } from \"./defaults.js\";\n\nconst DEFAULT_BASE_URL = \"http://localhost:11434\";\nconst DEFAULT_TIMEOUT = 60000;\n\nexport class OllamaClient {\n private baseUrl: string;\n private model: string;\n private timeout: number;\n\n constructor(options: OllamaClientOptions = {}) {\n this.baseUrl = options.baseUrl || DEFAULT_BASE_URL;\n this.model = options.model || UILINT_DEFAULT_OLLAMA_MODEL;\n this.timeout = options.timeout || DEFAULT_TIMEOUT;\n }\n\n /**\n * Low-level completion API for custom prompts (used by installers/tools).\n *\n * When `json` is true, Ollama is requested to emit JSON (best-effort).\n */\n async complete(\n prompt: string,\n options: {\n json?: boolean;\n stream?: boolean;\n onProgress?: StreamProgressCallback;\n } = {}\n ): Promise<string> {\n const jsonFormat = options.json ?? false;\n if (options.stream && options.onProgress) {\n return await this.generateStreaming(\n prompt,\n jsonFormat,\n options.onProgress\n );\n }\n return await this.generate(prompt, jsonFormat);\n }\n\n /**\n * Analyzes styles and returns issues\n */\n async analyzeStyles(\n styleSummary: string,\n styleGuide: string | null,\n onProgress?: StreamProgressCallback\n ): Promise<AnalysisResult> {\n const startTime = Date.now();\n const prompt = buildAnalysisPrompt(styleSummary, styleGuide);\n\n try {\n const response = onProgress\n ? await this.generateStreaming(prompt, true, onProgress)\n : await this.generate(prompt);\n const issues = this.parseIssuesResponse(response);\n\n return {\n issues,\n analysisTime: Date.now() - startTime,\n };\n } catch (error) {\n console.error(\"[UILint] Analysis failed:\", error);\n return {\n issues: [],\n analysisTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Analyzes a raw source file/snippet (TSX/JSX/etc) directly and returns issues.\n * This bypasses HTML/DOM parsing entirely.\n */\n async analyzeSource(\n source: string,\n styleGuide: string | null,\n onProgress?: StreamProgressCallback,\n options: BuildSourceAnalysisPromptOptions = {}\n ): Promise<AnalysisResult> {\n const startTime = Date.now();\n const prompt = buildSourceAnalysisPrompt(source, styleGuide, options);\n\n try {\n const response = onProgress\n ? await this.generateStreaming(prompt, true, onProgress)\n : await this.generate(prompt);\n const issues = this.parseIssuesResponse(response);\n\n return {\n issues,\n analysisTime: Date.now() - startTime,\n };\n } catch (error) {\n console.error(\"[UILint] Analysis failed:\", error);\n return {\n issues: [],\n analysisTime: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Generates a style guide from detected styles\n */\n async generateStyleGuide(styleSummary: string): Promise<string | null> {\n const prompt = buildStyleGuidePrompt(styleSummary);\n\n try {\n const response = await this.generate(prompt, false);\n return response;\n } catch (error) {\n console.error(\"[UILint] Style guide generation failed:\", error);\n return null;\n }\n }\n\n /**\n * Core generate method that calls Ollama API\n */\n private async generate(\n prompt: string,\n jsonFormat: boolean = true\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: false,\n ...(jsonFormat && { format: \"json\" }),\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Ollama API error: ${response.status}`);\n }\n\n const data = await response.json();\n return data.response || \"\";\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Streaming generate method that calls Ollama API with streaming\n * and reports progress via callback\n */\n private async generateStreaming(\n prompt: string,\n jsonFormat: boolean = true,\n onProgress: StreamProgressCallback\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: true,\n ...(jsonFormat && { format: \"json\" }),\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Ollama API error: ${response.status}`);\n }\n\n if (!response.body) {\n throw new Error(\"No response body for streaming\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let fullResponse = \"\";\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete JSON lines from the buffer\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const chunk = JSON.parse(line);\n if (chunk.response) {\n fullResponse += chunk.response;\n // Get the latest line from the response for progress display\n const responseLines = fullResponse.split(\"\\n\");\n const latestLine =\n responseLines[responseLines.length - 1] ||\n responseLines[responseLines.length - 2] ||\n \"\";\n onProgress(latestLine.trim(), fullResponse);\n }\n } catch {\n // Skip malformed JSON chunks\n }\n }\n }\n\n // Process any remaining content in buffer\n if (buffer.trim()) {\n try {\n const chunk = JSON.parse(buffer);\n if (chunk.response) {\n fullResponse += chunk.response;\n }\n } catch {\n // Skip malformed JSON\n }\n }\n\n return fullResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Parses issues from LLM response\n */\n private parseIssuesResponse(response: string): UILintIssue[] {\n try {\n const parsed = JSON.parse(response);\n return parsed.issues || [];\n } catch {\n console.warn(\"[UILint] Failed to parse LLM response as JSON\");\n return [];\n }\n }\n\n /**\n * Checks if Ollama is available\n */\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/api/tags`, {\n method: \"GET\",\n signal: AbortSignal.timeout(5000),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the current model\n */\n getModel(): string {\n return this.model;\n }\n\n /**\n * Sets the model\n */\n setModel(model: string): void {\n this.model = model;\n }\n}\n\n// Default singleton instance\nlet defaultClient: OllamaClient | null = null;\n\nexport function getOllamaClient(options?: OllamaClientOptions): OllamaClient {\n if (!defaultClient || options) {\n defaultClient = new OllamaClient(options);\n }\n return defaultClient;\n}\n","import type { UILintIssue } from \"../types.js\";\n\nexport interface FormatViolationsOptions {\n /**\n * Optional context label (e.g., filename) to include as a single header line.\n * Keep this empty for the most minimal output.\n */\n context?: string;\n /**\n * Include the trailing \"consult the style guide\" message.\n * Defaults to true.\n */\n includeFooter?: boolean;\n /**\n * Override the footer message.\n */\n footerMessage?: string;\n}\n\nconst DEFAULT_FOOTER = \"Consult the style guide for guidance.\";\n\n/**\n * Ensures issues are safe/minimal to print or serialize:\n * - drops `suggestion` (we only want violations)\n * - trims string fields\n */\nexport function sanitizeIssues(issues: UILintIssue[]): UILintIssue[] {\n return issues.map((issue) => ({\n id: String(issue.id ?? \"\").trim(),\n type: issue.type,\n message: String(issue.message ?? \"\").trim(),\n element: issue.element ? String(issue.element).trim() : undefined,\n selector: issue.selector ? String(issue.selector).trim() : undefined,\n currentValue: issue.currentValue ? String(issue.currentValue).trim() : undefined,\n expectedValue: issue.expectedValue\n ? String(issue.expectedValue).trim()\n : undefined,\n // Intentionally omit `suggestion`\n }));\n}\n\n/**\n * Minimal human-readable rendering of violations.\n * Intended for CLI/MCP text output.\n */\nexport function formatViolationsText(\n issues: UILintIssue[],\n options: FormatViolationsOptions = {}\n): string {\n const { context, includeFooter = true, footerMessage = DEFAULT_FOOTER } =\n options;\n\n if (!issues || issues.length === 0) {\n return \"No violations found.\";\n }\n\n const lines: string[] = [];\n\n if (context && context.trim()) {\n lines.push(`Violations in ${context.trim()}:`);\n lines.push(\"\");\n }\n\n const sanitized = sanitizeIssues(issues);\n sanitized.forEach((issue, i) => {\n lines.push(`${i + 1}. [${issue.type}] ${issue.message}`);\n if (issue.currentValue && issue.expectedValue) {\n lines.push(` ${issue.currentValue} → ${issue.expectedValue}`);\n } else if (issue.currentValue) {\n lines.push(` ${issue.currentValue}`);\n }\n lines.push(\"\");\n });\n\n // remove trailing blank line\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n\n if (includeFooter) {\n lines.push(\"\");\n lines.push(footerMessage);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Tailwind / utility-class token extraction helpers.\n *\n * Notes:\n * - Works on HTML (class=\"...\") and TSX-ish input (className=\"...\") via regex.\n * - Variant parsing is bracket-aware so arbitrary values like bg-[color:var(--x)]\n * don't get split incorrectly on \":\".\n */\n\nexport interface ClassTokenCounts {\n /**\n * Base utilities with variants stripped.\n * Example: \"sm:hover:bg-gray-50\" => utility \"bg-gray-50\"\n */\n utilities: Map<string, number>;\n /**\n * Individual variant prefixes.\n * Example: \"sm:hover:bg-gray-50\" => variants \"sm\", \"hover\"\n */\n variants: Map<string, number>;\n}\n\nexport interface ExtractClassTokenOptions {\n /**\n * Maximum number of tokens to process (guardrail for very large inputs).\n */\n maxTokens?: number;\n}\n\nexport function extractClassTokensFromHtml(\n html: string,\n options: ExtractClassTokenOptions = {}\n): ClassTokenCounts {\n const { maxTokens = 20000 } = options;\n\n const utilities = new Map<string, number>();\n const variants = new Map<string, number>();\n\n if (!html) return { utilities, variants };\n\n // Match both HTML and JSX-ish attributes.\n // - class=\"...\"\n // - className=\"...\"\n const attrPattern = /\\b(?:class|className)\\s*=\\s*[\"']([^\"']+)[\"']/g;\n\n let tokenBudget = maxTokens;\n let match: RegExpExecArray | null;\n while ((match = attrPattern.exec(html)) && tokenBudget > 0) {\n const raw = match[1];\n if (!raw) continue;\n\n const tokens = raw.split(/\\s+/g).filter(Boolean);\n for (const token of tokens) {\n if (tokenBudget-- <= 0) break;\n\n const { base, variantList } = splitVariants(token);\n const normalizedBase = normalizeUtility(base);\n if (!normalizedBase) continue;\n\n increment(utilities, normalizedBase);\n for (const v of variantList) increment(variants, v);\n }\n }\n\n return { utilities, variants };\n}\n\nexport function topEntries(\n map: Map<string, number>,\n limit: number\n): Array<{ token: string; count: number }> {\n return [...map.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, limit)\n .map(([token, count]) => ({ token, count }));\n}\n\nfunction increment(map: Map<string, number>, key: string): void {\n map.set(key, (map.get(key) || 0) + 1);\n}\n\nfunction normalizeUtility(token: string): string | null {\n const t = token.trim();\n if (!t) return null;\n\n // Strip important modifier\n const noImportant = t.startsWith(\"!\") ? t.slice(1) : t;\n\n // Ignore obviously non-class tokens\n if (!noImportant || noImportant === \"{\" || noImportant === \"}\") return null;\n\n return noImportant;\n}\n\n/**\n * Splits a class token into variants and base utility.\n * Bracket-aware to avoid splitting arbitrary values on \":\".\n *\n * Examples:\n * - \"sm:hover:bg-gray-50\" => variants [\"sm\",\"hover\"], base \"bg-gray-50\"\n * - \"bg-[color:var(--x)]\" => variants [], base \"bg-[color:var(--x)]\"\n * - \"sm:bg-[color:var(--x)]\" => variants [\"sm\"], base \"bg-[color:var(--x)]\"\n */\nfunction splitVariants(token: string): { base: string; variantList: string[] } {\n const parts: string[] = [];\n let buf = \"\";\n let bracketDepth = 0;\n\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n if (ch === \"[\") bracketDepth++;\n if (ch === \"]\" && bracketDepth > 0) bracketDepth--;\n\n if (ch === \":\" && bracketDepth === 0) {\n parts.push(buf);\n buf = \"\";\n continue;\n }\n\n buf += ch;\n }\n parts.push(buf);\n\n if (parts.length <= 1) return { base: token, variantList: [] };\n\n const base = parts[parts.length - 1] || \"\";\n const variantList = parts\n .slice(0, -1)\n .map((v) => v.trim())\n .filter(Boolean);\n\n return { base, variantList };\n}\n","/**\n * Style extraction from DOM elements\n */\n\nimport type {\n ExtractedStyles,\n SerializedStyles,\n TailwindThemeTokens,\n} from \"../types.js\";\nimport {\n extractClassTokensFromHtml,\n topEntries,\n} from \"../tailwind/class-tokens.js\";\n\n/**\n * Extracts all computed styles from elements in the document\n * Works in both browser and JSDOM environments\n */\nexport function extractStyles(\n root: Element | Document,\n getComputedStyle: (el: Element) => CSSStyleDeclaration\n): ExtractedStyles {\n const styles: ExtractedStyles = {\n colors: new Map(),\n fontSizes: new Map(),\n fontFamilies: new Map(),\n fontWeights: new Map(),\n spacing: new Map(),\n borderRadius: new Map(),\n };\n\n const elements = root.querySelectorAll(\"*\");\n\n elements.forEach((element) => {\n // nodeType === 1 means Element node (works in both browser and JSDOM)\n if (element.nodeType !== 1) return;\n\n const computed = getComputedStyle(element);\n\n // Extract colors\n extractColor(computed.color, styles.colors);\n extractColor(computed.backgroundColor, styles.colors);\n extractColor(computed.borderColor, styles.colors);\n\n // Extract typography\n incrementMap(styles.fontSizes, computed.fontSize);\n incrementMap(styles.fontFamilies, normalizeFontFamily(computed.fontFamily));\n incrementMap(styles.fontWeights, computed.fontWeight);\n\n // Extract spacing\n extractSpacing(computed.margin, styles.spacing);\n extractSpacing(computed.padding, styles.spacing);\n incrementMap(styles.spacing, computed.gap);\n\n // Extract border radius\n incrementMap(styles.borderRadius, computed.borderRadius);\n });\n\n return styles;\n}\n\n/**\n * Extracts styles from browser DOM (uses window.getComputedStyle)\n */\nexport function extractStylesFromDOM(\n root?: Element | Document\n): ExtractedStyles {\n const targetRoot = root || document.body;\n return extractStyles(targetRoot, (el) => window.getComputedStyle(el));\n}\n\nfunction extractColor(color: string, map: Map<string, number>): void {\n if (!color || color === \"transparent\" || color === \"rgba(0, 0, 0, 0)\") return;\n\n // Normalize to hex\n const hex = rgbToHex(color);\n if (hex) {\n incrementMap(map, hex);\n }\n}\n\nfunction extractSpacing(value: string, map: Map<string, number>): void {\n if (!value || value === \"0px\") return;\n\n // Split compound values (e.g., \"10px 20px 10px 20px\")\n const values = value.split(\" \").filter((v) => v && v !== \"0px\");\n values.forEach((v) => incrementMap(map, v));\n}\n\nfunction incrementMap(map: Map<string, number>, value: string): void {\n if (!value || value === \"normal\" || value === \"auto\") return;\n map.set(value, (map.get(value) || 0) + 1);\n}\n\nfunction normalizeFontFamily(fontFamily: string): string {\n // Get the primary font (first in the stack)\n const primary = fontFamily.split(\",\")[0].trim();\n return primary.replace(/['\"]/g, \"\");\n}\n\nfunction rgbToHex(rgb: string): string | null {\n // Handle hex values\n if (rgb.startsWith(\"#\")) return rgb.toUpperCase();\n\n // Handle rgb/rgba values\n const match = rgb.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (!match) return null;\n\n const [, r, g, b] = match;\n const toHex = (n: string) => parseInt(n).toString(16).padStart(2, \"0\");\n\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();\n}\n\n/**\n * Converts ExtractedStyles maps to plain objects for serialization\n */\nexport function serializeStyles(styles: ExtractedStyles): SerializedStyles {\n return {\n colors: Object.fromEntries(styles.colors),\n fontSizes: Object.fromEntries(styles.fontSizes),\n fontFamilies: Object.fromEntries(styles.fontFamilies),\n fontWeights: Object.fromEntries(styles.fontWeights),\n spacing: Object.fromEntries(styles.spacing),\n borderRadius: Object.fromEntries(styles.borderRadius),\n };\n}\n\n/**\n * Converts SerializedStyles back to ExtractedStyles\n */\nexport function deserializeStyles(\n serialized: SerializedStyles\n): ExtractedStyles {\n return {\n colors: new Map(Object.entries(serialized.colors)),\n fontSizes: new Map(Object.entries(serialized.fontSizes)),\n fontFamilies: new Map(Object.entries(serialized.fontFamilies)),\n fontWeights: new Map(Object.entries(serialized.fontWeights)),\n spacing: new Map(Object.entries(serialized.spacing)),\n borderRadius: new Map(Object.entries(serialized.borderRadius)),\n };\n}\n\n/**\n * Creates a summary of extracted styles for LLM analysis\n */\nexport function createStyleSummary(\n styles: ExtractedStyles,\n options: CreateStyleSummaryOptions = {}\n): string {\n return createStyleSummaryWithOptions(styles, options);\n}\n\nexport interface CreateStyleSummaryOptions {\n /**\n * Optional HTML/TSX-ish string used to extract utility classes (Tailwind etc).\n */\n html?: string;\n /**\n * Optional Tailwind theme tokens (typically from tailwind.config.*).\n */\n tailwindTheme?: TailwindThemeTokens | null;\n}\n\n/**\n * Creates a summary of extracted styles for LLM analysis.\n * Accepts optional Tailwind context to make Tailwind-heavy projects analyzable\n * even when computed styles are sparse (e.g., JSDOM without loaded CSS).\n */\nexport function createStyleSummaryWithOptions(\n styles: ExtractedStyles,\n options: CreateStyleSummaryOptions = {}\n): string {\n const lines: string[] = [];\n\n lines.push(\"## Detected Styles Summary\\n\");\n\n // Colors\n lines.push(\"### Colors\");\n const sortedColors = [...styles.colors.entries()].sort((a, b) => b[1] - a[1]);\n sortedColors.slice(0, 20).forEach(([color, count]) => {\n lines.push(`- ${color}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font sizes\n lines.push(\"### Font Sizes\");\n const sortedFontSizes = [...styles.fontSizes.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontSizes.forEach(([size, count]) => {\n lines.push(`- ${size}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font families\n lines.push(\"### Font Families\");\n const sortedFontFamilies = [...styles.fontFamilies.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontFamilies.forEach(([family, count]) => {\n lines.push(`- ${family}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Font weights\n lines.push(\"### Font Weights\");\n const sortedFontWeights = [...styles.fontWeights.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedFontWeights.forEach(([weight, count]) => {\n lines.push(`- ${weight}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Spacing\n lines.push(\"### Spacing Values\");\n const sortedSpacing = [...styles.spacing.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedSpacing.slice(0, 15).forEach(([value, count]) => {\n lines.push(`- ${value}: ${count} occurrences`);\n });\n lines.push(\"\");\n\n // Border radius\n lines.push(\"### Border Radius\");\n const sortedBorderRadius = [...styles.borderRadius.entries()].sort(\n (a, b) => b[1] - a[1]\n );\n sortedBorderRadius.forEach(([value, count]) => {\n lines.push(`- ${value}: ${count} occurrences`);\n });\n\n // Tailwind / utility classes (optional)\n if (options.html) {\n const tokens = extractClassTokensFromHtml(options.html);\n const topUtilities = topEntries(tokens.utilities, 40);\n const topVariants = topEntries(tokens.variants, 15);\n\n lines.push(\"\");\n lines.push(\"### Utility Classes (from markup)\");\n if (topUtilities.length === 0) {\n lines.push(\"- (none detected)\");\n } else {\n topUtilities.forEach(({ token, count }) => {\n lines.push(`- ${token}: ${count} occurrences`);\n });\n }\n\n if (topVariants.length > 0) {\n lines.push(\"\");\n lines.push(\"### Common Variants\");\n topVariants.forEach(({ token, count }) => {\n lines.push(`- ${token}: ${count} occurrences`);\n });\n }\n }\n\n // Tailwind theme tokens (optional)\n if (options.tailwindTheme) {\n const tt = options.tailwindTheme;\n lines.push(\"\");\n lines.push(\"### Tailwind Theme Tokens (from config)\");\n lines.push(`- configPath: ${tt.configPath}`);\n lines.push(`- colors: ${tt.colors.length}`);\n lines.push(`- spacingKeys: ${tt.spacingKeys.length}`);\n lines.push(`- borderRadiusKeys: ${tt.borderRadiusKeys.length}`);\n lines.push(`- fontFamilyKeys: ${tt.fontFamilyKeys.length}`);\n lines.push(`- fontSizeKeys: ${tt.fontSizeKeys.length}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Truncates HTML to a maximum length\n */\nexport function truncateHTML(html: string, maxLength: number = 50000): string {\n if (html.length <= maxLength) return html;\n return html.slice(0, maxLength) + \"<!-- truncated -->\";\n}\n","/**\n * Style guide schema and utilities\n */\n\nimport type { StyleGuide, ColorRule, TypographyRule, SpacingRule, ComponentRule } from \"../types.js\";\n\n/**\n * Creates an empty style guide structure\n */\nexport function createEmptyStyleGuide(): StyleGuide {\n return {\n colors: [],\n typography: [],\n spacing: [],\n components: [],\n };\n}\n\n/**\n * Validates a style guide object\n */\nexport function validateStyleGuide(guide: unknown): guide is StyleGuide {\n if (!guide || typeof guide !== \"object\") return false;\n\n const g = guide as Record<string, unknown>;\n\n return (\n Array.isArray(g.colors) &&\n Array.isArray(g.typography) &&\n Array.isArray(g.spacing) &&\n Array.isArray(g.components)\n );\n}\n\n/**\n * Merges detected styles into an existing style guide\n */\nexport function mergeStyleGuides(\n existing: StyleGuide,\n detected: Partial<StyleGuide>\n): StyleGuide {\n return {\n colors: mergeColorRules(existing.colors, detected.colors || []),\n typography: mergeTypographyRules(existing.typography, detected.typography || []),\n spacing: mergeSpacingRules(existing.spacing, detected.spacing || []),\n components: mergeComponentRules(existing.components, detected.components || []),\n };\n}\n\nfunction mergeColorRules(existing: ColorRule[], detected: ColorRule[]): ColorRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex(\n (e) => e.name === rule.name || e.value === rule.value\n );\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeTypographyRules(existing: TypographyRule[], detected: TypographyRule[]): TypographyRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex((e) => e.element === rule.element);\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeSpacingRules(existing: SpacingRule[], detected: SpacingRule[]): SpacingRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex(\n (e) => e.name === rule.name || e.value === rule.value\n );\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\nfunction mergeComponentRules(existing: ComponentRule[], detected: ComponentRule[]): ComponentRule[] {\n const merged = [...existing];\n detected.forEach((rule) => {\n const existingIndex = merged.findIndex((e) => e.name === rule.name);\n if (existingIndex === -1) {\n merged.push(rule);\n }\n });\n return merged;\n}\n\n/**\n * Creates a color rule\n */\nexport function createColorRule(\n name: string,\n value: string,\n usage: string = \"\"\n): ColorRule {\n return { name, value: value.toUpperCase(), usage };\n}\n\n/**\n * Creates a typography rule\n */\nexport function createTypographyRule(\n element: string,\n options: Partial<Omit<TypographyRule, \"element\">> = {}\n): TypographyRule {\n return { element, ...options };\n}\n\n/**\n * Creates a spacing rule\n */\nexport function createSpacingRule(name: string, value: string): SpacingRule {\n return { name, value };\n}\n\n/**\n * Creates a component rule\n */\nexport function createComponentRule(name: string, styles: string[]): ComponentRule {\n return { name, styles };\n}\n\n","/**\n * Parse Markdown style guides into structured data\n */\n\nimport type {\n StyleGuide,\n ColorRule,\n TypographyRule,\n SpacingRule,\n ComponentRule,\n ExtractedStyleValues,\n} from \"../types.js\";\nimport { createEmptyStyleGuide } from \"./schema.js\";\n\n/**\n * Parses a Markdown style guide into a structured object\n */\nexport function parseStyleGuide(markdown: string): StyleGuide {\n const guide = createEmptyStyleGuide();\n const sections = splitIntoSections(markdown);\n\n sections.forEach(({ title, content }) => {\n const lowerTitle = title.toLowerCase();\n\n if (lowerTitle.includes(\"color\")) {\n guide.colors = parseColorSection(content);\n } else if (\n lowerTitle.includes(\"typography\") ||\n lowerTitle.includes(\"font\")\n ) {\n guide.typography = parseTypographySection(content);\n } else if (lowerTitle.includes(\"spacing\")) {\n guide.spacing = parseSpacingSection(content);\n } else if (lowerTitle.includes(\"component\")) {\n guide.components = parseComponentSection(content);\n }\n });\n\n return guide;\n}\n\ninterface Section {\n title: string;\n content: string;\n}\n\nfunction splitIntoSections(markdown: string): Section[] {\n const sections: Section[] = [];\n const lines = markdown.split(\"\\n\");\n\n let currentTitle = \"\";\n let currentContent: string[] = [];\n\n lines.forEach((line) => {\n const headerMatch = line.match(/^##\\s+(.+)$/);\n\n if (headerMatch) {\n if (currentTitle) {\n sections.push({\n title: currentTitle,\n content: currentContent.join(\"\\n\"),\n });\n }\n currentTitle = headerMatch[1];\n currentContent = [];\n } else {\n currentContent.push(line);\n }\n });\n\n if (currentTitle) {\n sections.push({\n title: currentTitle,\n content: currentContent.join(\"\\n\"),\n });\n }\n\n return sections;\n}\n\nfunction parseColorSection(content: string): ColorRule[] {\n const colors: ColorRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Primary**: #3B82F6 (used in buttons)\n const match = line.match(\n /[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(#[A-Fa-f0-9]{6})\\s*(?:\\(([^)]+)\\))?/\n );\n\n if (match) {\n colors.push({\n name: match[1].trim(),\n value: match[2].toUpperCase(),\n usage: match[3] || \"\",\n });\n }\n });\n\n return colors;\n}\n\nfunction parseTypographySection(content: string): TypographyRule[] {\n const typography: TypographyRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Headings**: font-family: \"Inter\", font-size: 24px\n const elementMatch = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (elementMatch) {\n const rule: TypographyRule = {\n element: elementMatch[1].trim(),\n };\n\n const props = elementMatch[2];\n\n const fontFamilyMatch = props.match(/font-family:\\s*\"?([^\",]+)\"?/);\n if (fontFamilyMatch) rule.fontFamily = fontFamilyMatch[1].trim();\n\n const fontSizeMatch = props.match(/font-size:\\s*(\\d+px)/);\n if (fontSizeMatch) rule.fontSize = fontSizeMatch[1];\n\n const fontWeightMatch = props.match(/font-weight:\\s*(\\d+)/);\n if (fontWeightMatch) rule.fontWeight = fontWeightMatch[1];\n\n const lineHeightMatch = props.match(/line-height:\\s*([\\d.]+)/);\n if (lineHeightMatch) rule.lineHeight = lineHeightMatch[1];\n\n typography.push(rule);\n }\n });\n\n return typography;\n}\n\nfunction parseSpacingSection(content: string): SpacingRule[] {\n const spacing: SpacingRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Base unit**: 4px\n const match = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (match) {\n spacing.push({\n name: match[1].trim(),\n value: match[2].trim(),\n });\n }\n });\n\n return spacing;\n}\n\nfunction parseComponentSection(content: string): ComponentRule[] {\n const components: ComponentRule[] = [];\n const lines = content.split(\"\\n\");\n\n lines.forEach((line) => {\n // Match patterns like: - **Buttons**: rounded-lg, px-4 py-2\n const match = line.match(/[-*]\\s*\\*?\\*?([^*:]+)\\*?\\*?:\\s*(.+)/);\n\n if (match) {\n components.push({\n name: match[1].trim(),\n styles: match[2].split(\",\").map((s) => s.trim()),\n });\n }\n });\n\n return components;\n}\n\n/**\n * Parses sections from a Markdown style guide (simpler format)\n */\nexport function parseStyleGuideSections(\n content: string\n): Record<string, string> {\n const sections: Record<string, string> = {};\n const lines = content.split(\"\\n\");\n\n let currentSection = \"intro\";\n let currentContent: string[] = [];\n\n for (const line of lines) {\n const headerMatch = line.match(/^##\\s+(.+)$/);\n\n if (headerMatch) {\n if (currentContent.length > 0) {\n sections[currentSection.toLowerCase()] = currentContent\n .join(\"\\n\")\n .trim();\n }\n\n currentSection = headerMatch[1];\n currentContent = [];\n } else {\n currentContent.push(line);\n }\n }\n\n if (currentContent.length > 0) {\n sections[currentSection.toLowerCase()] = currentContent.join(\"\\n\").trim();\n }\n\n return sections;\n}\n\n/**\n * Extracts specific values from the style guide\n */\nexport function extractStyleValues(content: string): ExtractedStyleValues {\n const result: ExtractedStyleValues = {\n colors: [],\n fontSizes: [],\n fontFamilies: [],\n spacing: [],\n borderRadius: [],\n };\n\n // Extract hex colors\n const colorMatches = content.matchAll(/#[A-Fa-f0-9]{6}\\b/g);\n for (const match of colorMatches) {\n if (!result.colors.includes(match[0].toUpperCase())) {\n result.colors.push(match[0].toUpperCase());\n }\n }\n\n // Extract font sizes (e.g., 16px, 1.5rem)\n const fontSizeMatches = content.matchAll(/\\b(\\d+(?:\\.\\d+)?(?:px|rem|em))\\b/g);\n for (const match of fontSizeMatches) {\n if (!result.fontSizes.includes(match[1])) {\n result.fontSizes.push(match[1]);\n }\n }\n\n // Extract font families (quoted strings in font context)\n const fontFamilyMatches = content.matchAll(\n /font-family:\\s*[\"']?([^\"',\\n]+)/gi\n );\n for (const match of fontFamilyMatches) {\n const family = match[1].trim();\n if (!result.fontFamilies.includes(family)) {\n result.fontFamilies.push(family);\n }\n }\n\n return result;\n}\n\nexport interface TailwindAllowlist {\n allowAnyColor: boolean;\n allowStandardSpacing: boolean;\n allowedTailwindColors: Set<string>;\n allowedUtilities: Set<string>;\n allowedSpacingKeys: Set<string>;\n allowedBorderRadiusKeys: Set<string>;\n allowedFontSizeKeys: Set<string>;\n allowedFontFamilyKeys: Set<string>;\n}\n\n/**\n * Extract Tailwind / utility-class allowlist configuration from a style guide.\n *\n * Expected formats:\n * - A JSON code block inside a \"## Tailwind\" section (preferred; produced by UILint)\n * - Fallback: inline backticked utilities within the Tailwind section\n */\nexport function extractTailwindAllowlist(content: string): TailwindAllowlist {\n const empty: TailwindAllowlist = {\n allowAnyColor: false,\n allowStandardSpacing: false,\n allowedTailwindColors: new Set(),\n allowedUtilities: new Set(),\n allowedSpacingKeys: new Set(),\n allowedBorderRadiusKeys: new Set(),\n allowedFontSizeKeys: new Set(),\n allowedFontFamilyKeys: new Set(),\n };\n\n // Only look for allowlist details in the Tailwind section.\n const sections = parseStyleGuideSections(content);\n const tailwindSection =\n sections[\"tailwind\"] ??\n // defensive: some styleguides use different casing/spacing\n sections[\"tailwind utilities\"] ??\n \"\";\n\n if (!tailwindSection) return empty;\n\n const parsed = tryParseFirstJsonCodeBlock(tailwindSection);\n if (parsed && typeof parsed === \"object\") {\n const allowAnyColor = Boolean((parsed as any).allowAnyColor);\n const allowStandardSpacing = Boolean((parsed as any).allowStandardSpacing);\n\n const allowedUtilitiesArr = Array.isArray((parsed as any).allowedUtilities)\n ? ((parsed as any).allowedUtilities as unknown[]).filter(\n (u): u is string => typeof u === \"string\"\n )\n : [];\n\n const themeTokens = (parsed as any).themeTokens ?? {};\n const themeColors = Array.isArray(themeTokens.colors)\n ? (themeTokens.colors as unknown[]).filter(\n (c): c is string => typeof c === \"string\"\n )\n : [];\n const spacingKeys = Array.isArray(themeTokens.spacingKeys)\n ? (themeTokens.spacingKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const borderRadiusKeys = Array.isArray(themeTokens.borderRadiusKeys)\n ? (themeTokens.borderRadiusKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const fontFamilyKeys = Array.isArray(themeTokens.fontFamilyKeys)\n ? (themeTokens.fontFamilyKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n const fontSizeKeys = Array.isArray(themeTokens.fontSizeKeys)\n ? (themeTokens.fontSizeKeys as unknown[]).filter(\n (k): k is string => typeof k === \"string\"\n )\n : [];\n\n const allowedTailwindColors = new Set<string>();\n for (const c of themeColors) {\n const raw = c.trim();\n if (!raw) continue;\n if (raw.toLowerCase().startsWith(\"tailwind:\")) {\n allowedTailwindColors.add(raw.toLowerCase());\n continue;\n }\n const m = raw.match(/^([a-zA-Z]+)-(\\d{2,3})$/);\n if (m) {\n allowedTailwindColors.add(`tailwind:${m[1].toLowerCase()}-${m[2]}`);\n }\n }\n\n return {\n allowAnyColor,\n allowStandardSpacing,\n allowedTailwindColors,\n allowedUtilities: new Set(\n allowedUtilitiesArr.map((s) => s.trim()).filter(Boolean)\n ),\n allowedSpacingKeys: new Set(\n spacingKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedBorderRadiusKeys: new Set(\n borderRadiusKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedFontSizeKeys: new Set(\n fontSizeKeys.map((s) => s.trim()).filter(Boolean)\n ),\n allowedFontFamilyKeys: new Set(\n fontFamilyKeys.map((s) => s.trim()).filter(Boolean)\n ),\n };\n }\n\n // Fallback: harvest backticked utilities from markdown.\n const backticked: string[] = [];\n for (const m of tailwindSection.matchAll(/`([^`]+)`/g)) {\n backticked.push(m[1]);\n }\n\n return {\n ...empty,\n allowedUtilities: new Set(\n backticked\n .flatMap((s) => s.split(/[,\\s]+/g))\n .map((s) => s.trim())\n .filter(Boolean)\n ),\n };\n}\n\nfunction tryParseFirstJsonCodeBlock(section: string): unknown | null {\n // Prefer ```json fenced blocks, but fall back to any fenced block.\n const jsonBlocks = [...section.matchAll(/```json\\s*([\\s\\S]*?)```/gi)];\n const anyBlocks = [...section.matchAll(/```\\s*([\\s\\S]*?)```/g)];\n\n const candidates = (jsonBlocks.length ? jsonBlocks : anyBlocks).map(\n (m) => m[1]\n );\n for (const raw of candidates) {\n const trimmed = raw.trim();\n if (!trimmed) continue;\n try {\n return JSON.parse(trimmed);\n } catch {\n continue;\n }\n }\n return null;\n}\n","/**\n * Generate Markdown style guides from extracted styles\n */\n\nimport type {\n ExtractedStyles,\n StyleGuide,\n TailwindThemeTokens,\n} from \"../types.js\";\nimport {\n extractClassTokensFromHtml,\n topEntries,\n} from \"../tailwind/class-tokens.js\";\n\n/**\n * Generates a Markdown style guide from extracted styles\n */\nexport interface GenerateStyleGuideOptions {\n /**\n * Optional HTML/TSX-ish string used to extract utility classes (Tailwind etc).\n */\n html?: string;\n /**\n * Optional Tailwind theme tokens (typically from tailwind.config.*).\n */\n tailwindTheme?: TailwindThemeTokens | null;\n}\n\nexport function generateStyleGuideFromStyles(\n styles: ExtractedStyles,\n options: GenerateStyleGuideOptions = {}\n): string {\n // NOTE: Style guide auto-generation has been removed.\n // UILint now requires an explicit, user-owned style guide file (typically\n // `.uilint/styleguide.md`) to avoid silently producing/overwriting rules.\n void styles;\n void options;\n throw new Error(\n 'Style guide auto-generation has been removed. Create \".uilint/styleguide.md\" at your workspace root (recommended: run \"/genstyleguide\" in Cursor).'\n );\n}\n\n/**\n * Finds the greatest common divisor of an array of numbers\n */\nfunction findGCD(numbers: number[]): number {\n if (numbers.length === 0) return 0;\n if (numbers.length === 1) return numbers[0];\n\n const gcd = (a: number, b: number): number => {\n a = Math.abs(Math.round(a));\n b = Math.abs(Math.round(b));\n while (b) {\n const t = b;\n b = a % b;\n a = t;\n }\n return a;\n };\n\n return numbers.reduce((acc, n) => gcd(acc, n));\n}\n\n/**\n * Converts a StyleGuide object back to Markdown\n */\nexport function styleGuideToMarkdown(guide: StyleGuide): string {\n const lines: string[] = [];\n\n lines.push(\"# UI Style Guide\");\n lines.push(\"\");\n\n // Colors\n lines.push(\"## Colors\");\n guide.colors.forEach((color) => {\n const usage = color.usage ? ` (${color.usage})` : \"\";\n lines.push(`- **${color.name}**: ${color.value}${usage}`);\n });\n lines.push(\"\");\n\n // Typography\n lines.push(\"## Typography\");\n guide.typography.forEach((typo) => {\n const props: string[] = [];\n if (typo.fontFamily) props.push(`font-family: \"${typo.fontFamily}\"`);\n if (typo.fontSize) props.push(`font-size: ${typo.fontSize}`);\n if (typo.fontWeight) props.push(`font-weight: ${typo.fontWeight}`);\n if (typo.lineHeight) props.push(`line-height: ${typo.lineHeight}`);\n lines.push(`- **${typo.element}**: ${props.join(\", \")}`);\n });\n lines.push(\"\");\n\n // Spacing\n lines.push(\"## Spacing\");\n guide.spacing.forEach((space) => {\n lines.push(`- **${space.name}**: ${space.value}`);\n });\n lines.push(\"\");\n\n // Components\n lines.push(\"## Components\");\n guide.components.forEach((comp) => {\n lines.push(`- **${comp.name}**: ${comp.styles.join(\", \")}`);\n });\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAOO,SAAS,oBACd,cACA,YACQ;AACR,QAAM,eAAe,aACjB;AAAA,EAA2B,UAAU;AAAA;AAAA,IACrC;AAEJ,SAAO;AAAA;AAAA,EAEP,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmCd;AAsBO,SAAS,0BACd,QACA,YACA,UAA4C,CAAC,GACrC;AACR,QAAM,eAAe,aACjB;AAAA,EAA2B,UAAU;AAAA;AAAA,IACrC;AAEJ,QAAM,YAAsB,CAAC;AAC7B,MAAI,QAAQ,SAAU,WAAU,KAAK,eAAe,QAAQ,QAAQ,EAAE;AACtE,MAAI,QAAQ;AACV,cAAU,KAAK,mBAAmB,QAAQ,YAAY,EAAE;AAC1D,QAAM,cACJ,UAAU,SAAS,IACf;AAAA,EAAuB,UAAU,KAAK,IAAI,CAAC;AAAA;AAAA,IAC3C;AAEN,QAAM,QACJ,QAAQ,gBAAgB,QAAQ,aAAa,KAAK,IAC9C;AAAA,EAA0B,QAAQ,aAAa,KAAK,CAAC;AAAA;AAAA,IACrD;AAEN,SAAO;AAAA;AAAA,EAEP,YAAY,GAAG,WAAW,GAAG,KAAK;AAAA,EAClC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBR;AAKO,SAAS,sBAAsB,cAA8B;AAClE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