uilint-core 0.2.1 → 0.2.3

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.
@@ -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","../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\nexport interface BuildSourceScanPromptOptions {\n /**\n * Display filename/path for context in the prompt.\n */\n filePath?: string;\n /**\n * Optional focus target for manual scan UX.\n */\n componentName?: string;\n componentLine?: number;\n /**\n * If true, the scan is for the selected element + children (UI text only).\n */\n includeChildren?: boolean;\n /**\n * Optional list of data-loc values (format: \"path:line:column\") that the model MUST\n * restrict issues to (so UI can highlight exactly).\n */\n dataLocs?: string[];\n}\n\n/**\n * Builds a prompt for scanning a source file/snippet for issues that can be mapped\n * back to rendered DOM elements via `data-loc`.\n *\n * Response schema (JSON):\n * { \"issues\": [{ \"line\"?: number, \"message\": string, \"dataLoc\"?: string }] }\n */\nexport function buildSourceScanPrompt(\n sourceCode: string,\n styleGuide: string | null,\n options: BuildSourceScanPromptOptions = {}\n): string {\n const fileLabel = options.filePath || \"component.tsx\";\n const dataLocList = Array.isArray(options.dataLocs) ? options.dataLocs : [];\n\n const focusSection =\n options.componentName && options.componentName.trim()\n ? `## Focus\n\nFocus on the \"${options.componentName.trim()}\" component${\n typeof options.componentLine === \"number\"\n ? ` (near line ${options.componentLine})`\n : \"\"\n }.\n\n`\n : \"\";\n\n const scopeText =\n options.includeChildren === true\n ? \"Scope: selected element + children.\"\n : \"Scope: selected element only.\";\n\n const dataLocSection =\n dataLocList.length > 0\n ? `## Element Locations (data-loc values)\n\nThe following elements are rendered on the page from this file. Each data-loc has format \"path:line:column\".\nWhen reporting issues, include the matching dataLoc value so we can highlight the specific element.\n\n\\`\\`\\`\n${dataLocList.join(\"\\n\")}\n\\`\\`\\`\n\n`\n : \"\";\n\n const guideSection = styleGuide\n ? `## Style Guide\n\n${styleGuide}\n\n`\n : \"\";\n\n return `You are a UI code reviewer. Analyze the following React/TypeScript UI code for style consistency issues.\n\n${guideSection}${focusSection}${scopeText}\n\n${dataLocSection}## Source Code (${fileLabel})\n\n\\`\\`\\`tsx\n${sourceCode}\n\\`\\`\\`\n\n## Task\n\nIdentify any style inconsistencies, violations of best practices, or deviations from the style guide.\nFor each issue, provide:\n- line: the line number in the source file\n- message: a clear description of the issue\n- dataLoc: the matching data-loc value from the list above (if applicable, to identify the specific element)\n\n## Critical Requirements for dataLoc\n\n- If \"Element Locations (data-loc values)\" are provided, ONLY report issues that correspond to one of those elements.\n- When you include a dataLoc, it MUST be copied verbatim from the list (no shortening paths, no normalization).\n- If you cannot match an issue to a provided dataLoc, omit that issue from the response.\n\nRespond with JSON:\n\\`\\`\\`json\n{\n \"issues\": [\n { \"line\": 12, \"message\": \"Color #3575E2 should be #3B82F6 (primary blue from styleguide)\", \"dataLoc\": \"app/page.tsx:12:5\" }\n ]\n}\n\\`\\`\\`\n\nIf no issues are found, respond with:\n\\`\\`\\`json\n{ \"issues\": [] }\n\\`\\`\\``;\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 LLMInstrumentationCallbacks,\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 private instrumentation?: LLMInstrumentationCallbacks;\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 this.instrumentation = options.instrumentation;\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(\n prompt,\n true,\n onProgress,\n \"analyze-styles\"\n )\n : await this.generate(prompt, true, \"analyze-styles\");\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(\n prompt,\n true,\n onProgress,\n \"analyze-source\"\n )\n : await this.generate(prompt, true, \"analyze-source\");\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(\n prompt,\n false,\n \"generate-styleguide\"\n );\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 operationName: string = \"ollama-generate\"\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Start instrumentation span if available\n const span = this.instrumentation?.onGenerationStart?.({\n name: operationName,\n model: this.model,\n prompt,\n metadata: { jsonFormat, stream: false },\n });\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 const error = `Ollama API error: ${response.status}`;\n span?.end(\"\", { error });\n throw new Error(error);\n }\n\n const data = await response.json();\n const output = data.response || \"\";\n\n // End instrumentation span with output and usage\n span?.end(output, {\n promptTokens: data.prompt_eval_count,\n completionTokens: data.eval_count,\n totalTokens:\n (data.prompt_eval_count || 0) + (data.eval_count || 0) || undefined,\n });\n\n return output;\n } catch (error) {\n span?.end(\"\", { error: String(error) });\n throw error;\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 operationName: string = \"ollama-generate-stream\"\n ): Promise<string> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n // Start instrumentation span if available\n const span = this.instrumentation?.onGenerationStart?.({\n name: operationName,\n model: this.model,\n prompt,\n metadata: { jsonFormat, stream: true },\n });\n\n // Track token counts from streaming response\n let promptTokens: number | undefined;\n let completionTokens: number | undefined;\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 const error = `Ollama API error: ${response.status}`;\n span?.end(\"\", { error });\n throw new Error(error);\n }\n\n if (!response.body) {\n const error = \"No response body for streaming\";\n span?.end(\"\", { error });\n throw new Error(error);\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 // Capture token counts from final chunk\n if (chunk.done) {\n promptTokens = chunk.prompt_eval_count;\n completionTokens = chunk.eval_count;\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 if (chunk.done) {\n promptTokens = chunk.prompt_eval_count;\n completionTokens = chunk.eval_count;\n }\n } catch {\n // Skip malformed JSON\n }\n }\n\n // End instrumentation span with output and usage\n span?.end(fullResponse, {\n promptTokens,\n completionTokens,\n totalTokens: (promptTokens || 0) + (completionTokens || 0) || undefined,\n });\n\n return fullResponse;\n } catch (error) {\n span?.end(\"\", { error: String(error) });\n throw error;\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 * Sets instrumentation callbacks for observability.\n * This allows configuring instrumentation after construction.\n */\n setInstrumentation(\n instrumentation: LLMInstrumentationCallbacks | undefined\n ): void {\n this.instrumentation = instrumentation;\n }\n\n /**\n * Returns true if instrumentation is currently configured.\n */\n hasInstrumentation(): boolean {\n return !!this.instrumentation;\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 {\n buildConsistencyPrompt,\n countElements,\n hasAnalyzableGroups,\n} 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))\n return false;\n\n // Validate severity\n if (!VALID_SEVERITIES.includes(obj.severity as ViolationSeverity))\n 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[] = [\n `Found ${violations.length} consistency issue(s):\\n`,\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":";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