canicode 0.8.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/engine/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../src/core/adapters/tailwind-parser.ts","../../src/core/adapters/figma-mcp-adapter.ts","../../src/core/engine/design-data-parser.ts","../../package.json","../../src/core/contracts/figma-node.ts","../../src/core/contracts/issue.ts","../../src/core/contracts/score.ts","../../src/core/contracts/report.ts","../../src/core/rules/excluded-names.ts","../../src/core/rules/layout/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/ai-readability/index.ts","../../src/core/rules/handoff-risk/index.ts","../../src/agents/contracts/calibration.ts","../../src/agents/contracts/analysis-agent.ts","../../src/agents/contracts/conversion-agent.ts","../../src/agents/contracts/evaluation-agent.ts","../../src/agents/contracts/tuning-agent.ts","../../src/core/engine/scoring.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/index.ts","../../src/core/rules/custom/config-loader.ts","../../src/core/rules/custom/custom-rule-schema.ts","../../src/core/rules/custom/custom-rule-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/mcp/server.ts"],"names":["mkdirSync","dirname","writeFileSync","resolve","readFileSync","width","height","diff","z","config","existsSync","response","findNodeById","hasAutoLayout","isContainerNode","readFile","version","require","writeFile","visualCompare"],"mappings":";;;;;;;;;;;;;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A,IAC7D,WAAA,EAAa,KAAA;AAAA,IACb,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,SAAS,mBAAA;AAAoB,GAC/B;AACA,EAAA,MAAM,KAAA,GAAQ,kBAAiB,IAAK,eAAA;AACpC,mBAA4B,aAAA,GAAgB,KAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n viewport?: { width: number; height: number } | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n): Promise<void> {\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=1`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n */\nasync function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n viewport: { width: number; height: number },\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n const page = await browser.newPage({ viewport });\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n await browser.close();\n}\n\n/**\n * Resize a PNG to target dimensions (nearest neighbor).\n */\nfunction resizePng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const resized = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n for (let x = 0; x < targetWidth; x++) {\n const srcX = Math.floor((x / targetWidth) * png.width);\n const srcY = Math.floor((y / targetHeight) * png.height);\n const srcIdx = (srcY * png.width + srcX) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n resized.data[dstIdx] = png.data[srcIdx]!;\n resized.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n resized.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n resized.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return resized;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nfunction compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n // Size mismatch = implementation failure\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n // Still generate a diff image for debugging (resize to larger)\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n const img1 = resizePng(raw1, width, height);\n const img2 = resizePng(raw2, width, height);\n const diff = new PNG({ width, height });\n pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold: 0.1 });\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n return {\n similarity: 0,\n diffPixels: width * height,\n totalPixels: width * height,\n width,\n height,\n };\n }\n\n const { width, height } = raw1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(raw1.data, raw2.data, diff.data, width, height, {\n threshold: 0.1,\n });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = Math.round((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Fetch Figma screenshot first to get its dimensions\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath);\n\n // Step 2: Read Figma screenshot dimensions, use as viewport for code rendering\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const viewport = options.viewport ?? { width: figmaPng.width, height: figmaPng.height };\n\n // Step 3: Render code screenshot at the same size\n await renderCodeScreenshot(options.codePath, codeScreenshotPath, viewport);\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"layout\",\n \"token\",\n \"component\",\n \"naming\",\n \"ai-readability\",\n \"handoff-risk\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n layout: \"Layout\",\n token: \"Design Token\",\n component: \"Component\",\n naming: \"Naming\",\n \"ai-readability\": \"AI Readability\",\n \"handoff-risk\": \"Handoff Risk\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n maxDepth: number;\n path: string[];\n siblings?: AnalysisNode[] | undefined;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n nodeId: string;\n nodePath: string;\n message: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Layout (11)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"fixed-width-in-responsive-context\"\n | \"missing-responsive-behavior\"\n | \"group-usage\"\n | \"fixed-size-in-auto-layout\"\n | \"missing-min-width\"\n | \"missing-max-width\"\n | \"deep-nesting\"\n | \"overflow-hidden-abuse\"\n | \"inconsistent-sibling-layout-direction\"\n // Token (7)\n | \"raw-color\"\n | \"raw-font\"\n | \"inconsistent-spacing\"\n | \"magic-number-spacing\"\n | \"raw-shadow\"\n | \"raw-opacity\"\n | \"multiple-fill-colors\"\n // Component (7)\n | \"missing-component\"\n | \"detached-instance\"\n | \"nested-instance-override\"\n | \"variant-not-used\"\n | \"component-property-unused\"\n | \"single-use-component\"\n | \"missing-component-description\"\n // Naming (5)\n | \"default-name\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\"\n | \"numeric-suffix-name\"\n | \"too-long-name\"\n // AI Readability (5)\n | \"ambiguous-structure\"\n | \"z-index-dependent-layout\"\n | \"missing-layout-hint\"\n | \"invisible-layer\"\n | \"empty-frame\"\n // Handoff Risk (5)\n | \"hardcode-risk\"\n | \"text-truncation-unhandled\"\n | \"image-no-placeholder\"\n | \"prototype-link-in-design\"\n | \"no-dev-status\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"layout\", \"handoff-risk\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { RuleConfig, RuleId } from \"../contracts/rule.js\";\n\n/**\n * Central configuration for all rules\n * Edit scores/severity here without touching rule logic\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ============================================\n // Layout (11 rules)\n // ============================================\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.3,\n enabled: true,\n },\n \"fixed-width-in-responsive-context\": {\n severity: \"risk\",\n score: -4,\n depthWeight: 1.3,\n enabled: true,\n },\n \"missing-responsive-behavior\": {\n severity: \"risk\",\n score: -4,\n depthWeight: 1.5,\n enabled: true,\n },\n \"group-usage\": {\n severity: \"risk\",\n score: -5,\n depthWeight: 1.2,\n enabled: true,\n },\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"missing-min-width\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"missing-max-width\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n \"overflow-hidden-abuse\": {\n severity: \"missing-info\",\n score: -3,\n enabled: true,\n },\n \"inconsistent-sibling-layout-direction\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n\n // ============================================\n // Token (7 rules)\n // ============================================\n \"raw-color\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"raw-font\": {\n severity: \"blocking\",\n score: -8,\n enabled: true,\n },\n \"inconsistent-spacing\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n options: {\n gridBase: 4,\n },\n },\n \"magic-number-spacing\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n options: {\n gridBase: 4,\n },\n },\n \"raw-shadow\": {\n severity: \"missing-info\",\n score: -3,\n enabled: true,\n },\n \"raw-opacity\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"multiple-fill-colors\": {\n severity: \"missing-info\",\n score: -3,\n enabled: true,\n options: {\n tolerance: 10,\n },\n },\n\n // ============================================\n // Component (7 rules)\n // ============================================\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"nested-instance-override\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"variant-not-used\": {\n severity: \"missing-info\",\n score: -3,\n enabled: true,\n },\n \"component-property-unused\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"single-use-component\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n \"missing-component-description\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n\n // ============================================\n // Naming (5 rules)\n // ============================================\n \"default-name\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"numeric-suffix-name\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n \"too-long-name\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n options: {\n maxLength: 50,\n },\n },\n\n // ============================================\n // AI Readability (5 rules)\n // ============================================\n \"ambiguous-structure\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.3,\n enabled: true,\n },\n \"z-index-dependent-layout\": {\n severity: \"risk\",\n score: -5,\n depthWeight: 1.3,\n enabled: true,\n },\n \"missing-layout-hint\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"invisible-layer\": {\n severity: \"blocking\",\n score: -10,\n enabled: true,\n },\n \"empty-frame\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n\n // ============================================\n // Handoff Risk (5 rules)\n // ============================================\n \"hardcode-risk\": {\n severity: \"risk\",\n score: -5,\n depthWeight: 1.5,\n enabled: true,\n },\n \"text-truncation-unhandled\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n },\n \"image-no-placeholder\": {\n severity: \"missing-info\",\n score: -3,\n enabled: true,\n },\n \"prototype-link-in-design\": {\n severity: \"missing-info\",\n score: -2,\n enabled: true,\n },\n \"no-dev-status\": {\n severity: \"missing-info\",\n score: -2,\n enabled: false, // Disabled by default\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on layout and handoff issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n if (\n !ruleId.includes(\"layout\") &&\n !ruleId.includes(\"handoff\") &&\n !ruleId.includes(\"responsive\")\n ) {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost AI readability and naming rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n if (\n ruleId.includes(\"ambiguous\") ||\n ruleId.includes(\"structure\") ||\n ruleId.includes(\"name\")\n ) {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Enable all rules, increase scores\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n enabled: true,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\n\n/**\n * Analysis issue with calculated score and metadata\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n const issues: AnalysisIssue[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n 0,\n [],\n undefined,\n undefined\n );\n\n return {\n file,\n issues,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n depth: number,\n path: string[],\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n maxDepth,\n path: nodePath,\n siblings,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Log but don't fail on rule errors\n console.error(`Rule \"${ruleId}\" threw error on node \"${node.name}\":`, error);\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n depth + 1,\n nodePath,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first) throw new Error(\"No nodes returned from Figma API\");\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse;\n\n // Extract fileKey from filename (e.g., ABC123.json -> ABC123)\n const fileKey = basename(filePath, \".json\");\n\n return transformFigmaResponse(fileKey, data);\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n return `https://www.figma.com/design/${fileKey}?node-id=${encodeURIComponent(nodeId)}`;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", \"utf-8\");\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input)) {\n const filePath = resolve(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.log(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or JSON file path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.log(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.log(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n return {\n file: transformFileNodesResponse(fileKey, response),\n nodeId,\n };\n }\n\n const response = await client.getFile(fileKey);\n return {\n file: transformFigmaResponse(fileKey, response),\n nodeId,\n };\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Style properties extracted from Tailwind/JSX code generated by Figma MCP get_design_context.\n * These are merged into AnalysisNode to enrich metadata-only nodes with style information.\n */\nexport interface ExtractedStyles {\n layoutMode?: \"HORIZONTAL\" | \"VERTICAL\";\n layoutPositioning?: \"AUTO\" | \"ABSOLUTE\";\n layoutSizingHorizontal?: \"FIXED\" | \"HUG\" | \"FILL\";\n layoutSizingVertical?: \"FIXED\" | \"HUG\" | \"FILL\";\n itemSpacing?: number;\n paddingLeft?: number;\n paddingRight?: number;\n paddingTop?: number;\n paddingBottom?: number;\n fills?: unknown[];\n effects?: unknown[];\n}\n\n/**\n * A code block from get_design_context, associated with a node ID.\n */\nexport interface DesignContextBlock {\n nodeId: string;\n code: string;\n}\n\n// Tailwind spacing scale: class suffix → px value\nconst SPACING_SCALE: Record<string, number> = {\n \"0\": 0, \"px\": 1, \"0.5\": 2, \"1\": 4, \"1.5\": 6, \"2\": 8, \"2.5\": 10,\n \"3\": 12, \"3.5\": 14, \"4\": 16, \"5\": 20, \"6\": 24, \"7\": 28, \"8\": 32,\n \"9\": 36, \"10\": 40, \"11\": 44, \"12\": 48, \"14\": 56, \"16\": 64,\n \"20\": 80, \"24\": 96, \"28\": 112, \"32\": 128, \"36\": 144, \"40\": 160,\n \"44\": 176, \"48\": 192, \"52\": 208, \"56\": 224, \"60\": 240, \"64\": 256,\n \"72\": 288, \"80\": 320, \"96\": 384,\n};\n\nfunction resolveSpacing(value: string): number | undefined {\n // Arbitrary value: gap-[12px]\n const arbMatch = value.match(/^\\[(\\d+(?:\\.\\d+)?)px\\]$/);\n if (arbMatch?.[1]) return parseFloat(arbMatch[1]);\n return SPACING_SCALE[value];\n}\n\n/**\n * Extract style properties from a className string (Tailwind classes).\n */\nexport function extractStylesFromClasses(classes: string): ExtractedStyles {\n const styles: ExtractedStyles = {};\n const tokens = classes.split(/\\s+/);\n\n for (const token of tokens) {\n // Layout direction\n if (token === \"flex\" || token === \"flex-row\") {\n styles.layoutMode = \"HORIZONTAL\";\n } else if (token === \"flex-col\") {\n styles.layoutMode = \"VERTICAL\";\n }\n\n // Positioning\n else if (token === \"absolute\") {\n styles.layoutPositioning = \"ABSOLUTE\";\n } else if (token === \"relative\" || token === \"static\") {\n styles.layoutPositioning = \"AUTO\";\n }\n\n // Sizing\n else if (token === \"w-full\") {\n styles.layoutSizingHorizontal = \"FILL\";\n } else if (token === \"h-full\") {\n styles.layoutSizingVertical = \"FILL\";\n } else if (token === \"w-fit\") {\n styles.layoutSizingHorizontal = \"HUG\";\n } else if (token === \"h-fit\") {\n styles.layoutSizingVertical = \"HUG\";\n } else if (token.match(/^w-\\[.+\\]$/) || token.match(/^w-\\d/)) {\n styles.layoutSizingHorizontal = \"FIXED\";\n } else if (token.match(/^h-\\[.+\\]$/) || token.match(/^h-\\d/)) {\n styles.layoutSizingVertical = \"FIXED\";\n }\n\n // Gap → itemSpacing\n else if (token.startsWith(\"gap-\")) {\n const val = token.slice(4);\n const px = resolveSpacing(val);\n if (px !== undefined) styles.itemSpacing = px;\n }\n\n // Padding\n else if (token.startsWith(\"p-\") && !token.startsWith(\"pl-\") && !token.startsWith(\"pr-\") && !token.startsWith(\"pt-\") && !token.startsWith(\"pb-\") && !token.startsWith(\"px-\") && !token.startsWith(\"py-\")) {\n const val = token.slice(2);\n const px = resolveSpacing(val);\n if (px !== undefined) {\n styles.paddingLeft = px;\n styles.paddingRight = px;\n styles.paddingTop = px;\n styles.paddingBottom = px;\n }\n } else if (token.startsWith(\"px-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) {\n styles.paddingLeft = px;\n styles.paddingRight = px;\n }\n } else if (token.startsWith(\"py-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) {\n styles.paddingTop = px;\n styles.paddingBottom = px;\n }\n } else if (token.startsWith(\"pl-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) styles.paddingLeft = px;\n } else if (token.startsWith(\"pr-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) styles.paddingRight = px;\n } else if (token.startsWith(\"pt-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) styles.paddingTop = px;\n } else if (token.startsWith(\"pb-\")) {\n const px = resolveSpacing(token.slice(3));\n if (px !== undefined) styles.paddingBottom = px;\n }\n\n // Background color → fills\n else if (token.startsWith(\"bg-[\")) {\n const colorMatch = token.match(/^bg-\\[(.+)\\]$/);\n if (colorMatch?.[1]) {\n const color = colorMatch[1];\n if (!styles.fills) styles.fills = [];\n if (color.startsWith(\"var(\")) {\n // Design token reference: bg-[var(--md-sys-color-surface)]\n styles.fills.push({ type: \"SOLID\", color: {}, boundVariable: color });\n } else {\n // Raw color: bg-[#FF0000]\n styles.fills.push({ type: \"SOLID\", color: parseHexColor(color) });\n }\n }\n }\n\n // Shadow → effects\n else if (token === \"shadow\" || token.startsWith(\"shadow-\")) {\n if (!styles.effects) styles.effects = [];\n styles.effects.push({ type: \"DROP_SHADOW\" });\n }\n }\n\n return styles;\n}\n\nfunction parseHexColor(hex: string): Record<string, number> {\n const clean = hex.replace(\"#\", \"\");\n if (clean.length === 6 || clean.length === 8) {\n return {\n r: parseInt(clean.slice(0, 2), 16) / 255,\n g: parseInt(clean.slice(2, 4), 16) / 255,\n b: parseInt(clean.slice(4, 6), 16) / 255,\n a: clean.length === 8 ? parseInt(clean.slice(6, 8), 16) / 255 : 1,\n };\n }\n return { r: 0, g: 0, b: 0, a: 1 };\n}\n\n/**\n * Extract className values from the root-level JSX element in a code block.\n * Returns classes from the first/outermost div/element's className.\n */\nfunction extractRootClasses(code: string): string {\n // Match the first className=\"...\" in the JSX\n const match = code.match(/className=\"([^\"]+)\"/);\n return match?.[1] ?? \"\";\n}\n\n/**\n * Extract all className values from entire code block.\n * Returns aggregated style info for all elements.\n */\nfunction extractAllClasses(code: string): string[] {\n const classes: string[] = [];\n const regex = /className=\"([^\"]+)\"/g;\n let match: RegExpExecArray | null;\n while ((match = regex.exec(code)) !== null) {\n if (match[1]) classes.push(match[1]);\n }\n return classes;\n}\n\n/**\n * Parse a get_design_context code response to extract style hints\n * for enriching AnalysisNode properties.\n *\n * The code is React+Tailwind generated by Figma MCP. We extract:\n * - Root element styles (layoutMode, padding, gap, sizing)\n * - Color fills (bg-[#hex] or bg-[var(...)])\n * - Shadow effects\n * - Layout positioning (absolute/relative)\n */\nexport function parseDesignContextCode(code: string): ExtractedStyles {\n const rootClasses = extractRootClasses(code);\n const rootStyles = extractStylesFromClasses(rootClasses);\n\n // Also scan all elements for fills and effects to capture deeper style info\n const allClasses = extractAllClasses(code);\n const aggregatedFills: unknown[] = [...(rootStyles.fills ?? [])];\n const aggregatedEffects: unknown[] = [...(rootStyles.effects ?? [])];\n\n for (const cls of allClasses) {\n const styles = extractStylesFromClasses(cls);\n if (styles.fills) {\n for (const fill of styles.fills) aggregatedFills.push(fill);\n }\n if (styles.effects) {\n for (const effect of styles.effects) aggregatedEffects.push(effect);\n }\n }\n\n return {\n ...rootStyles,\n ...(aggregatedFills.length > 0 ? { fills: aggregatedFills } : {}),\n ...(aggregatedEffects.length > 0 ? { effects: aggregatedEffects } : {}),\n };\n}\n\n/**\n * Parse the comment header from get_design_context code to extract node metadata.\n * Format: \"/* NodeName — 905x680 COMPONENT, vertical auto-layout *\\/\"\n */\nexport function parseCodeHeader(code: string): {\n name?: string;\n width?: number;\n height?: number;\n type?: string;\n hasAutoLayout?: boolean;\n layoutDirection?: \"HORIZONTAL\" | \"VERTICAL\";\n} {\n const headerMatch = code.match(/\\/\\*\\s*(.+?)\\s*\\*\\//);\n if (!headerMatch?.[1]) return {};\n\n const header = headerMatch[1];\n const result: ReturnType<typeof parseCodeHeader> = {};\n\n // Extract name (before \" — \")\n const nameParts = header.split(\" — \");\n if (nameParts[0]) result.name = nameParts[0].trim();\n\n // Extract dimensions\n const dimMatch = header.match(/(\\d+)x(\\d+)/);\n if (dimMatch?.[1] && dimMatch[2]) {\n result.width = parseInt(dimMatch[1]);\n result.height = parseInt(dimMatch[2]);\n }\n\n // Extract type\n const typeMatch = header.match(/\\b(COMPONENT|FRAME|INSTANCE|GROUP|SECTION)\\b/);\n if (typeMatch?.[1]) result.type = typeMatch[1];\n\n // Auto-layout detection\n if (header.includes(\"no auto-layout\")) {\n result.hasAutoLayout = false;\n } else if (header.includes(\"auto-layout\")) {\n result.hasAutoLayout = true;\n if (header.includes(\"vertical auto-layout\")) result.layoutDirection = \"VERTICAL\";\n else if (header.includes(\"horizontal auto-layout\")) result.layoutDirection = \"HORIZONTAL\";\n }\n\n return result;\n}\n\n/**\n * Merge extracted styles into an AnalysisNode (mutates the node).\n * Only sets properties that are not already present on the node.\n */\nexport function enrichNodeWithStyles(node: AnalysisNode, styles: ExtractedStyles): void {\n if (styles.layoutMode && !node.layoutMode) node.layoutMode = styles.layoutMode;\n if (styles.layoutPositioning && !node.layoutPositioning) node.layoutPositioning = styles.layoutPositioning;\n if (styles.layoutSizingHorizontal && !node.layoutSizingHorizontal) node.layoutSizingHorizontal = styles.layoutSizingHorizontal;\n if (styles.layoutSizingVertical && !node.layoutSizingVertical) node.layoutSizingVertical = styles.layoutSizingVertical;\n if (styles.itemSpacing !== undefined && node.itemSpacing === undefined) node.itemSpacing = styles.itemSpacing;\n if (styles.paddingLeft !== undefined && node.paddingLeft === undefined) node.paddingLeft = styles.paddingLeft;\n if (styles.paddingRight !== undefined && node.paddingRight === undefined) node.paddingRight = styles.paddingRight;\n if (styles.paddingTop !== undefined && node.paddingTop === undefined) node.paddingTop = styles.paddingTop;\n if (styles.paddingBottom !== undefined && node.paddingBottom === undefined) node.paddingBottom = styles.paddingBottom;\n if (styles.fills && !node.fills) node.fills = styles.fills;\n if (styles.effects && !node.effects) node.effects = styles.effects;\n}\n","import type { AnalysisFile, AnalysisNode, AnalysisNodeType } from \"../contracts/figma-node.js\";\nimport { parseDesignContextCode, parseCodeHeader, enrichNodeWithStyles } from \"./tailwind-parser.js\";\n\n/**\n * Map MCP XML tag names to Figma AnalysisNodeType\n */\nconst TAG_TYPE_MAP: Record<string, AnalysisNodeType> = {\n canvas: \"CANVAS\",\n frame: \"FRAME\",\n group: \"GROUP\",\n section: \"SECTION\",\n component: \"COMPONENT\",\n \"component-set\": \"COMPONENT_SET\",\n instance: \"INSTANCE\",\n rectangle: \"RECTANGLE\",\n \"rounded-rectangle\": \"RECTANGLE\",\n ellipse: \"ELLIPSE\",\n vector: \"VECTOR\",\n text: \"TEXT\",\n line: \"LINE\",\n \"boolean-operation\": \"BOOLEAN_OPERATION\",\n star: \"STAR\",\n \"regular-polygon\": \"REGULAR_POLYGON\",\n slice: \"SLICE\",\n sticky: \"STICKY\",\n table: \"TABLE\",\n \"table-cell\": \"TABLE_CELL\",\n symbol: \"COMPONENT\",\n slot: \"FRAME\",\n};\n\ninterface ParsedXmlNode {\n tag: string;\n attrs: Record<string, string>;\n children: ParsedXmlNode[];\n}\n\n/**\n * Minimal XML parser for MCP metadata output.\n * Handles self-closing tags and nested elements.\n */\nfunction parseXml(xml: string): ParsedXmlNode[] {\n const nodes: ParsedXmlNode[] = [];\n const stack: ParsedXmlNode[] = [];\n // Match opening tags (with attrs), closing tags, and self-closing tags\n const tagRegex = /<(\\/?)([\\w-]+)([^>]*?)(\\/?)>/g;\n let match: RegExpExecArray | null;\n\n while ((match = tagRegex.exec(xml)) !== null) {\n const isClosing = match[1] === \"/\";\n const tagName = match[2]!;\n const attrString = match[3] ?? \"\";\n const isSelfClosing = match[4] === \"/\";\n\n if (isClosing) {\n // Pop from stack\n const finished = stack.pop();\n if (finished) {\n const parent = stack[stack.length - 1];\n if (parent) {\n parent.children.push(finished);\n } else {\n nodes.push(finished);\n }\n }\n } else {\n const attrs = parseAttributes(attrString);\n const node: ParsedXmlNode = { tag: tagName, attrs, children: [] };\n\n if (isSelfClosing) {\n const parent = stack[stack.length - 1];\n if (parent) {\n parent.children.push(node);\n } else {\n nodes.push(node);\n }\n } else {\n stack.push(node);\n }\n }\n }\n\n // Flush remaining stack\n while (stack.length > 0) {\n const finished = stack.pop()!;\n const parent = stack[stack.length - 1];\n if (parent) {\n parent.children.push(finished);\n } else {\n nodes.push(finished);\n }\n }\n\n return nodes;\n}\n\nfunction parseAttributes(attrString: string): Record<string, string> {\n const attrs: Record<string, string> = {};\n const attrRegex = /([\\w-]+)=\"([^\"]*)\"/g;\n let match: RegExpExecArray | null;\n while ((match = attrRegex.exec(attrString)) !== null) {\n const key = match[1];\n const value = match[2];\n if (key && value !== undefined) {\n attrs[key] = value;\n }\n }\n return attrs;\n}\n\n/**\n * Convert a parsed XML node to an AnalysisNode\n */\nfunction toAnalysisNode(xmlNode: ParsedXmlNode): AnalysisNode {\n const type = TAG_TYPE_MAP[xmlNode.tag] ?? \"FRAME\";\n const id = xmlNode.attrs[\"id\"] ?? \"0:0\";\n const name = xmlNode.attrs[\"name\"] ?? xmlNode.tag;\n const hidden = xmlNode.attrs[\"hidden\"] === \"true\";\n\n const x = parseFloat(xmlNode.attrs[\"x\"] ?? \"0\");\n const y = parseFloat(xmlNode.attrs[\"y\"] ?? \"0\");\n const width = parseFloat(xmlNode.attrs[\"width\"] ?? \"0\");\n const height = parseFloat(xmlNode.attrs[\"height\"] ?? \"0\");\n\n const node: AnalysisNode = {\n id,\n name,\n type,\n visible: !hidden,\n absoluteBoundingBox: { x, y, width, height },\n };\n\n if (xmlNode.children.length > 0) {\n node.children = xmlNode.children.map(toAnalysisNode);\n }\n\n return node;\n}\n\n/**\n * Parse MCP get_metadata XML output into an AnalysisFile.\n *\n * The XML represents a subtree of the Figma file. We wrap it in a\n * DOCUMENT node and fill in minimal file metadata.\n */\nexport function parseMcpMetadataXml(\n xml: string,\n fileKey: string,\n fileName?: string\n): AnalysisFile {\n const parsed = parseXml(xml);\n\n // The root XML elements become children of the document\n const children = parsed.map(toAnalysisNode);\n\n // If there's exactly one root element, use it directly as the document root\n // Otherwise wrap in a DOCUMENT node\n let document: AnalysisNode;\n if (children.length === 1 && children[0]) {\n document = children[0];\n } else {\n document = {\n id: \"0:0\",\n name: \"Document\",\n type: \"DOCUMENT\",\n visible: true,\n children,\n };\n }\n\n return {\n fileKey,\n name: fileName ?? fileKey,\n lastModified: new Date().toISOString(),\n version: \"mcp\",\n document,\n components: {},\n styles: {},\n };\n}\n\n/**\n * Enrich an AnalysisFile (from get_metadata) with style data extracted\n * from get_design_context code output.\n *\n * The design context code is React+Tailwind generated for a specific node.\n * We parse Tailwind classes to extract layout, color, spacing, and effect\n * properties, then merge them into matching AnalysisNodes in the tree.\n *\n * @param file - AnalysisFile from parseMcpMetadataXml\n * @param designContextCode - Code string from get_design_context\n * @param targetNodeId - The node ID that get_design_context was called for (optional)\n */\nexport function enrichWithDesignContext(\n file: AnalysisFile,\n designContextCode: string,\n targetNodeId?: string,\n): void {\n const header = parseCodeHeader(designContextCode);\n const styles = parseDesignContextCode(designContextCode);\n\n // If header provides auto-layout info, use it\n if (header.hasAutoLayout === true && header.layoutDirection) {\n if (!styles.layoutMode) styles.layoutMode = header.layoutDirection;\n } else if (header.hasAutoLayout === false) {\n // Explicitly no auto-layout — don't set layoutMode\n delete styles.layoutMode;\n }\n\n // Find the target node and enrich it\n if (targetNodeId) {\n const node = findNodeById(file.document, targetNodeId);\n if (node) {\n enrichNodeWithStyles(node, styles);\n enrichChildrenFromCode(node, designContextCode);\n return;\n }\n }\n\n // Fallback: enrich the root document node\n enrichNodeWithStyles(file.document, styles);\n enrichChildrenFromCode(file.document, designContextCode);\n}\n\n/**\n * Try to enrich child nodes by scanning the full code for className patterns.\n * For each child, extract classes from JSX elements that match the child's name.\n */\nfunction enrichChildrenFromCode(parent: AnalysisNode, code: string): void {\n if (!parent.children) return;\n\n for (const child of parent.children) {\n // Look for comments like \"{/* ChildName */}\" or \"{/* ChildName — ... */}\"\n const escapedName = child.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const commentPattern = new RegExp(\n `\\\\{/\\\\*\\\\s*${escapedName}(?:\\\\s*—[^*]*)?\\\\s*\\\\*/\\\\}\\\\s*\\\\n\\\\s*<\\\\w+[^>]*className=\"([^\"]*)\"`,\n );\n const match = code.match(commentPattern);\n if (match?.[1]) {\n const childStyles = parseDesignContextCode(\n `<div className=\"${match[1]}\">`,\n );\n enrichNodeWithStyles(child, childStyles);\n }\n\n // Recurse into children\n if (child.children) {\n enrichChildrenFromCode(child, code);\n }\n }\n}\n\nfunction findNodeById(node: AnalysisNode, id: string): AnalysisNode | undefined {\n if (node.id === id) return node;\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, id);\n if (found) return found;\n }\n }\n return undefined;\n}\n","import type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport { parseMcpMetadataXml } from \"../adapters/figma-mcp-adapter.js\";\nimport { transformFigmaResponse } from \"../adapters/figma-transformer.js\";\n\n/**\n * Parse design data passed directly from Figma MCP or other sources.\n *\n * Accepts:\n * - XML string from Figma MCP get_metadata\n * - JSON string of an AnalysisFile object\n * - JSON string of a Figma REST API GetFileResponse\n */\nexport function parseDesignData(\n data: string,\n fileKey: string,\n fileName?: string\n): AnalysisFile {\n const trimmed = data.trim();\n\n // Detect XML (starts with <)\n if (trimmed.startsWith(\"<\")) {\n return parseMcpMetadataXml(trimmed, fileKey, fileName);\n }\n\n // Try JSON\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n\n // If it already looks like AnalysisFile (has fileKey + document)\n if (\"fileKey\" in parsed && \"document\" in parsed) {\n return parsed as unknown as AnalysisFile;\n }\n\n // If it looks like Figma REST API response (has document + name but no fileKey)\n if (\"document\" in parsed && \"name\" in parsed) {\n return transformFigmaResponse(fileKey, parsed as unknown as GetFileResponse);\n }\n\n throw new Error(\n \"Unrecognized designData format. Expected XML from Figma MCP get_metadata, AnalysisFile JSON, or Figma REST API JSON.\"\n );\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.8.8\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"CLI tool that analyzes Figma design structures for development-friendliness and AI-friendliness scores\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"clean\": \"rm -rf dist\"\n },\n \"files\": [\n \"dist\",\n \"docs/REFERENCE.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n effects: z.array(z.unknown()).optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { z } from \"zod\";\nimport { SeveritySchema } from \"./severity.js\";\n\nexport const IssueSchema = z.object({\n nodeId: z.string(),\n nodePath: z.string(),\n figmaDeepLink: z.string().url(),\n ruleId: z.string(),\n message: z.string(),\n severity: SeveritySchema,\n});\n\nexport type Issue = z.infer<typeof IssueSchema>;\n","import { z } from \"zod\";\nimport { CategorySchema } from \"./category.js\";\n\nexport const CategoryScoreSchema = z.object({\n category: CategorySchema,\n score: z.number().min(0).max(100),\n maxScore: z.number().min(0).max(100),\n issueCount: z.object({\n error: z.number().int().min(0),\n warning: z.number().int().min(0),\n info: z.number().int().min(0),\n }),\n});\n\nexport type CategoryScore = z.infer<typeof CategoryScoreSchema>;\n","import { z } from \"zod\";\nimport { CategoryScoreSchema } from \"./score.js\";\nimport { IssueSchema } from \"./issue.js\";\n\nexport const ReportMetadataSchema = z.object({\n fileKey: z.string(),\n fileName: z.string(),\n analyzedAt: z.string().datetime(),\n version: z.string(),\n});\n\nexport type ReportMetadata = z.infer<typeof ReportMetadataSchema>;\n\nexport const ReportSchema = z.object({\n metadata: ReportMetadataSchema,\n totalScore: z.number().min(0).max(100),\n categoryScores: z.array(CategoryScoreSchema),\n issues: z.array(IssueSchema),\n summary: z.object({\n totalNodes: z.number().int().min(0),\n analyzedNodes: z.number().int().min(0),\n errorCount: z.number().int().min(0),\n warningCount: z.number().int().min(0),\n infoCount: z.number().int().min(0),\n }),\n});\n\nexport type Report = z.infer<typeof ReportSchema>;\n","/**\n * Name patterns for nodes that should be excluded from certain rule checks.\n * These are typically decorative, structural, or overlay elements where\n * issues like naming, absolute positioning, etc. are intentional.\n *\n * Matches if the name contains any of these words (case-insensitive).\n */\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\n/**\n * Check if a node name matches excluded patterns.\n */\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nfunction isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\";\n}\n\nfunction hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nfunction hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\n// ============================================\n// no-auto-layout\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"layout\",\n why: \"Frames without Auto Layout require manual positioning for every element\",\n impact: \"Layout breaks on content changes, harder to maintain and scale\",\n fix: \"Apply Auto Layout to the frame with appropriate direction and spacing\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"FRAME\") return null;\n if (hasAutoLayout(node)) return null;\n // Skip if frame has no children (might be intentional placeholder)\n if (!node.children || node.children.length === 0) return null;\n\n return {\n ruleId: noAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `Frame \"${node.name}\" has no Auto Layout`,\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"layout\",\n why: \"Absolute positioning inside Auto Layout breaks the automatic flow\",\n impact: \"Element will not respond to sibling changes, may overlap unexpectedly\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nimport { isExcludedName } from \"../excluded-names.js\";\n\n/**\n * Check if a node is small relative to its parent (decoration/badge pattern).\n * Returns true if the node is less than 25% of the parent's width AND height.\n */\nfunction isSmallRelativeToParent(node: AnalysisNode, parent: AnalysisNode): boolean {\n const nodeBB = node.absoluteBoundingBox;\n const parentBB = parent.absoluteBoundingBox;\n if (!nodeBB || !parentBB) return false;\n if (parentBB.width === 0 || parentBB.height === 0) return false;\n\n const widthRatio = nodeBB.width / parentBB.width;\n const heightRatio = nodeBB.height / parentBB.height;\n return widthRatio < 0.25 && heightRatio < 0.25;\n}\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n // Exception: vector/graphic nodes (icons, illustrations — absolute positioning is expected)\n if (node.type === \"VECTOR\" || node.type === \"BOOLEAN_OPERATION\" || node.type === \"LINE\" || node.type === \"ELLIPSE\" || node.type === \"STAR\" || node.type === \"REGULAR_POLYGON\") return null;\n\n // Exception: intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return null;\n\n // Exception: small decoration relative to parent (< 25% size)\n if (isSmallRelativeToParent(node, context.parent)) return null;\n\n // Exception: inside a component definition (designer's intentional layout)\n if (context.parent.type === \"COMPONENT\") return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses absolute positioning inside Auto Layout parent \"${context.parent.name}\". If intentional (badge, overlay, close button), rename to badge-*, overlay-*, close-* to suppress this warning.`,\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-width-in-responsive-context\n// ============================================\n\nconst fixedWidthInResponsiveContextDef: RuleDefinition = {\n id: \"fixed-width-in-responsive-context\",\n name: \"Fixed Width in Responsive Context\",\n category: \"layout\",\n why: \"Fixed width inside Auto Layout prevents responsive behavior\",\n impact: \"Content will not adapt to container size changes\",\n fix: \"Use 'Fill' or 'Hug' instead of fixed width\",\n};\n\nconst fixedWidthInResponsiveContextCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (!node.absoluteBoundingBox) return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return null;\n\n return {\n ruleId: fixedWidthInResponsiveContextDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has fixed width inside Auto Layout`,\n };\n};\n\nexport const fixedWidthInResponsiveContext = defineRule({\n definition: fixedWidthInResponsiveContextDef,\n check: fixedWidthInResponsiveContextCheck,\n});\n\n// ============================================\n// missing-responsive-behavior\n// ============================================\n\nconst missingResponsiveBehaviorDef: RuleDefinition = {\n id: \"missing-responsive-behavior\",\n name: \"Missing Responsive Behavior\",\n category: \"layout\",\n why: \"Elements without constraints won't adapt to different screen sizes\",\n impact: \"Layout will break or look wrong on different devices\",\n fix: \"Set appropriate constraints (left/right, top/bottom, scale, etc.)\",\n};\n\nconst missingResponsiveBehaviorCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n // Skip if inside Auto Layout (Auto Layout handles responsiveness)\n if (context.parent && hasAutoLayout(context.parent)) return null;\n // Skip root-level frames (they define the viewport)\n if (context.depth < 2) return null;\n\n // Check for missing layout mode and no parent auto layout\n if (!hasAutoLayout(node) && !node.layoutAlign) {\n return {\n ruleId: missingResponsiveBehaviorDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has no responsive behavior configured`,\n };\n }\n\n return null;\n};\n\nexport const missingResponsiveBehavior = defineRule({\n definition: missingResponsiveBehaviorDef,\n check: missingResponsiveBehaviorCheck,\n});\n\n// ============================================\n// group-usage\n// ============================================\n\nconst groupUsageDef: RuleDefinition = {\n id: \"group-usage\",\n name: \"Group Usage\",\n category: \"layout\",\n why: \"Groups don't support Auto Layout and have limited layout control\",\n impact: \"Harder to maintain consistent spacing and alignment\",\n fix: \"Convert Group to Frame and apply Auto Layout\",\n};\n\nconst groupUsageCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"GROUP\") return null;\n\n return {\n ruleId: groupUsageDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is a Group - consider converting to Frame with Auto Layout`,\n };\n};\n\nexport const groupUsage = defineRule({\n definition: groupUsageDef,\n check: groupUsageCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"layout\",\n why: \"Fixed sizes inside Auto Layout limit flexibility\",\n impact: \"Element won't adapt to content or container changes\",\n fix: \"Consider using 'Hug' for content-driven sizing\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n // Only check containers, not leaf nodes\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n // Skip if it's intentionally a small fixed element (icon, avatar, etc.)\n const { width, height } = node.absoluteBoundingBox;\n if (width <= 48 && height <= 48) return null;\n\n // This is a heuristic - in practice you'd check layoutSizingHorizontal/Vertical\n // For now, we flag containers that might benefit from flexible sizing\n return null; // Disabled for now - needs more context from Figma API\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-min-width\n// ============================================\n\nconst missingMinWidthDef: RuleDefinition = {\n id: \"missing-min-width\",\n name: \"Missing Min Width\",\n category: \"layout\",\n why: \"Without min-width, containers can collapse to unusable sizes\",\n impact: \"Text truncation or layout collapse on narrow screens\",\n fix: \"Set a minimum width constraint on the container\",\n};\n\nconst missingMinWidthCheck: RuleCheckFn = (node, context) => {\n // Only check containers and text-containing nodes\n if (!isContainerNode(node) && !hasTextContent(node)) return null;\n // Skip small fixed elements (icons, dividers)\n if (node.absoluteBoundingBox) {\n const { width, height } = node.absoluteBoundingBox;\n if (width <= 48 && height <= 24) return null;\n }\n // Skip if not in Auto Layout context\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n // Check for min-width in boundVariables or explicit constraint\n // This is a simplified check - full implementation needs more Figma data\n return null; // Needs minWidth property from Figma API\n};\n\nexport const missingMinWidth = defineRule({\n definition: missingMinWidthDef,\n check: missingMinWidthCheck,\n});\n\n// ============================================\n// missing-max-width\n// ============================================\n\nconst missingMaxWidthDef: RuleDefinition = {\n id: \"missing-max-width\",\n name: \"Missing Max Width\",\n category: \"layout\",\n why: \"Without max-width, content can stretch too wide on large screens\",\n impact: \"Poor readability and layout on wide screens\",\n fix: \"Set a maximum width constraint, especially for text containers\",\n};\n\nconst missingMaxWidthCheck: RuleCheckFn = (node, _context) => {\n // Only check containers and text-containing nodes\n if (!isContainerNode(node) && !hasTextContent(node)) return null;\n // Skip small elements\n if (node.absoluteBoundingBox) {\n const { width } = node.absoluteBoundingBox;\n if (width <= 200) return null;\n }\n\n // Check for max-width constraint\n // This is a simplified check - full implementation needs more Figma data\n return null; // Needs maxWidth property from Figma API\n};\n\nexport const missingMaxWidth = defineRule({\n definition: missingMaxWidthDef,\n check: missingMaxWidthCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"layout\",\n why: \"Deep nesting makes the structure hard to understand and maintain\",\n impact: \"Increases complexity, harder to debug layout issues\",\n fix: \"Flatten the structure by removing unnecessary wrapper frames\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.depth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is nested ${context.depth} levels deep (max: ${maxDepth})`,\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n// ============================================\n// overflow-hidden-abuse\n// ============================================\n\nconst overflowHiddenAbuseDef: RuleDefinition = {\n id: \"overflow-hidden-abuse\",\n name: \"Overflow Hidden Abuse\",\n category: \"layout\",\n why: \"Using clip content to hide layout problems masks underlying issues\",\n impact: \"Content may be unintentionally cut off, problems harder to diagnose\",\n fix: \"Fix the underlying layout issue instead of hiding overflow\",\n};\n\nconst overflowHiddenAbuseCheck: RuleCheckFn = (_node, _context) => {\n // This would check for clipsContent property\n // Simplified for now - needs more Figma API data\n return null;\n};\n\nexport const overflowHiddenAbuse = defineRule({\n definition: overflowHiddenAbuseDef,\n check: overflowHiddenAbuseCheck,\n});\n\n// ============================================\n// inconsistent-sibling-layout-direction\n// ============================================\n\nconst inconsistentSiblingLayoutDirectionDef: RuleDefinition = {\n id: \"inconsistent-sibling-layout-direction\",\n name: \"Inconsistent Sibling Layout Direction\",\n category: \"layout\",\n why: \"Sibling containers with mixed layout directions without clear reason create confusion\",\n impact: \"Harder to understand and maintain the design structure\",\n fix: \"Use consistent layout direction for similar sibling elements\",\n};\n\nconst inconsistentSiblingLayoutDirectionCheck: RuleCheckFn = (node, context) => {\n // Only check container nodes with siblings\n if (!isContainerNode(node)) return null;\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Get layout directions of sibling containers\n const siblingContainers = context.siblings.filter(\n (s) => isContainerNode(s) && s.id !== node.id\n );\n\n if (siblingContainers.length === 0) return null;\n\n const myDirection = node.layoutMode;\n if (!myDirection || myDirection === \"NONE\") return null;\n\n // Check if siblings have different directions\n const siblingDirections = siblingContainers\n .map((s) => s.layoutMode)\n .filter((d) => d && d !== \"NONE\");\n\n if (siblingDirections.length === 0) return null;\n\n // If all siblings have the same direction, but this node is different\n const allSameSiblingDirection = siblingDirections.every(\n (d) => d === siblingDirections[0]\n );\n\n if (allSameSiblingDirection && siblingDirections[0] !== myDirection) {\n // Check for valid patterns: parent row -> child column (card layout)\n if (context.parent?.layoutMode === \"HORIZONTAL\" && myDirection === \"VERTICAL\") {\n return null; // This is a valid card-in-row pattern\n }\n\n return {\n ruleId: inconsistentSiblingLayoutDirectionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has ${myDirection} layout while siblings use ${siblingDirections[0]}`,\n };\n }\n\n return null;\n};\n\nexport const inconsistentSiblingLayoutDirection = defineRule({\n definition: inconsistentSiblingLayoutDirectionDef,\n check: inconsistentSiblingLayoutDirectionCheck,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nfunction hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nfunction hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-color\n// ============================================\n\nconst rawColorDef: RuleDefinition = {\n id: \"raw-color\",\n name: \"Raw Color\",\n category: \"token\",\n why: \"Raw hex colors are not connected to the design system\",\n impact: \"Color changes require manual updates across the entire design\",\n fix: \"Use a color style or variable instead of raw hex values\",\n};\n\nconst rawColorCheck: RuleCheckFn = (node, context) => {\n // Skip nodes without fills\n if (!node.fills || !Array.isArray(node.fills)) return null;\n if (node.fills.length === 0) return null;\n\n // Check if fill style is applied\n if (hasStyleReference(node, \"fill\")) return null;\n\n // Check if color variable is bound\n if (hasBoundVariable(node, \"fills\")) return null;\n\n // Check each fill for raw colors\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n return {\n ruleId: rawColorDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses raw color without style or variable`,\n };\n }\n }\n\n return null;\n};\n\nexport const rawColor = defineRule({\n definition: rawColorDef,\n check: rawColorCheck,\n});\n\n// ============================================\n// raw-font\n// ============================================\n\nconst rawFontDef: RuleDefinition = {\n id: \"raw-font\",\n name: \"Raw Font\",\n category: \"token\",\n why: \"Text without text styles is disconnected from the type system\",\n impact: \"Typography changes require manual updates across the design\",\n fix: \"Apply a text style to maintain consistency\",\n};\n\nconst rawFontCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"TEXT\") return null;\n\n // Check if text style is applied\n if (hasStyleReference(node, \"text\")) return null;\n\n // Check for text variable bindings\n if (hasBoundVariable(node, \"fontFamily\") || hasBoundVariable(node, \"fontSize\")) {\n return null;\n }\n\n return {\n ruleId: rawFontDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has no text style applied`,\n };\n};\n\nexport const rawFont = defineRule({\n definition: rawFontDef,\n check: rawFontCheck,\n});\n\n// ============================================\n// inconsistent-spacing\n// ============================================\n\nconst inconsistentSpacingDef: RuleDefinition = {\n id: \"inconsistent-spacing\",\n name: \"Inconsistent Spacing\",\n category: \"token\",\n why: \"Spacing values outside the grid system break visual consistency\",\n impact: \"Inconsistent visual rhythm and harder to maintain\",\n fix: \"Use spacing values from the design system grid (e.g., 8pt increments)\",\n};\n\nconst inconsistentSpacingCheck: RuleCheckFn = (node, context, options) => {\n const gridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"inconsistent-spacing\", \"gridBase\", 4);\n\n // Check padding values\n const paddings = [\n node.paddingLeft,\n node.paddingRight,\n node.paddingTop,\n node.paddingBottom,\n ].filter((p): p is number => p !== undefined && p > 0);\n\n for (const padding of paddings) {\n if (!isOnGrid(padding, gridBase)) {\n return {\n ruleId: inconsistentSpacingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has padding ${padding}px not on ${gridBase}pt grid`,\n };\n }\n }\n\n // Check item spacing\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n if (!isOnGrid(node.itemSpacing, gridBase)) {\n return {\n ruleId: inconsistentSpacingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has item spacing ${node.itemSpacing}px not on ${gridBase}pt grid`,\n };\n }\n }\n\n return null;\n};\n\nexport const inconsistentSpacing = defineRule({\n definition: inconsistentSpacingDef,\n check: inconsistentSpacingCheck,\n});\n\n// ============================================\n// magic-number-spacing\n// ============================================\n\nconst magicNumberSpacingDef: RuleDefinition = {\n id: \"magic-number-spacing\",\n name: \"Magic Number Spacing\",\n category: \"token\",\n why: \"Arbitrary spacing values make the system harder to understand\",\n impact: \"Unpredictable spacing, harder to create consistent layouts\",\n fix: \"Round spacing to the nearest grid value or use spacing tokens\",\n};\n\nconst magicNumberSpacingCheck: RuleCheckFn = (node, context, options) => {\n const gridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"magic-number-spacing\", \"gridBase\", 4);\n\n // Similar to inconsistent-spacing but focuses on finding \"magic\" numbers\n // Magic numbers are often odd values like 13, 17, 23, etc.\n const allSpacings = [\n node.paddingLeft,\n node.paddingRight,\n node.paddingTop,\n node.paddingBottom,\n node.itemSpacing,\n ].filter((s): s is number => s !== undefined && s > 0);\n\n for (const spacing of allSpacings) {\n // Check if it's not on grid AND not a common intentional value\n const commonValues = [1, 2, 4]; // Allow 1, 2, 4 as intentional small values\n if (!isOnGrid(spacing, gridBase) && !commonValues.includes(spacing)) {\n // Only flag truly \"magic\" numbers (prime-ish, odd values)\n if (spacing % 2 !== 0 && spacing > 4) {\n return {\n ruleId: magicNumberSpacingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses magic number spacing: ${spacing}px`,\n };\n }\n }\n }\n\n return null;\n};\n\nexport const magicNumberSpacing = defineRule({\n definition: magicNumberSpacingDef,\n check: magicNumberSpacingCheck,\n});\n\n// ============================================\n// raw-shadow\n// ============================================\n\nconst rawShadowDef: RuleDefinition = {\n id: \"raw-shadow\",\n name: \"Raw Shadow\",\n category: \"token\",\n why: \"Shadow effects without styles are disconnected from the design system\",\n impact: \"Shadow changes require manual updates across the design\",\n fix: \"Create and apply an effect style for shadows\",\n};\n\nconst rawShadowCheck: RuleCheckFn = (node, context) => {\n if (!node.effects || !Array.isArray(node.effects)) return null;\n if (node.effects.length === 0) return null;\n\n // Check if effect style is applied\n if (hasStyleReference(node, \"effect\")) return null;\n\n // Check for shadow effects\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (\n effectObj[\"type\"] === \"DROP_SHADOW\" ||\n effectObj[\"type\"] === \"INNER_SHADOW\"\n ) {\n return {\n ruleId: rawShadowDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has shadow effect without effect style`,\n };\n }\n }\n\n return null;\n};\n\nexport const rawShadow = defineRule({\n definition: rawShadowDef,\n check: rawShadowCheck,\n});\n\n// ============================================\n// raw-opacity\n// ============================================\n\nconst rawOpacityDef: RuleDefinition = {\n id: \"raw-opacity\",\n name: \"Raw Opacity\",\n category: \"token\",\n why: \"Hardcoded opacity values are not connected to design tokens\",\n impact: \"Opacity changes require manual updates\",\n fix: \"Use opacity variables or consider if opacity is truly needed\",\n};\n\nconst rawOpacityCheck: RuleCheckFn = (node, _context) => {\n // Check if opacity variable is bound\n if (hasBoundVariable(node, \"opacity\")) return null;\n\n // This would need to check node opacity property\n // Simplified for now - needs more Figma API data\n return null;\n};\n\nexport const rawOpacity = defineRule({\n definition: rawOpacityDef,\n check: rawOpacityCheck,\n});\n\n// ============================================\n// multiple-fill-colors\n// ============================================\n\nconst multipleFillColorsDef: RuleDefinition = {\n id: \"multiple-fill-colors\",\n name: \"Multiple Fill Colors\",\n category: \"token\",\n why: \"Similar but slightly different colors indicate inconsistent token usage\",\n impact: \"Visual inconsistency and harder to maintain brand colors\",\n fix: \"Consolidate to a single color token or style\",\n};\n\nconst multipleFillColorsCheck: RuleCheckFn = (_node, _context, _options) => {\n // This rule needs to analyze colors across multiple nodes\n // It's better suited for a post-processing analysis phase\n // Simplified implementation - would need global context\n return null;\n};\n\nexport const multipleFillColors = defineRule({\n definition: multipleFillColorsDef,\n check: multipleFillColorsCheck,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nfunction isComponentInstance(node: AnalysisNode): boolean {\n return node.type === \"INSTANCE\";\n}\n\nfunction isComponent(node: AnalysisNode): boolean {\n return node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\";\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n// ============================================\n// missing-component\n// ============================================\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"component\",\n why: \"Repeated identical structures should be componentized\",\n impact: \"Changes require manual updates in multiple places\",\n fix: \"Create a component from the repeated structure\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // Only check at frame level\n if (node.type !== \"FRAME\") return null;\n\n const minRepetitions = (options?.[\"minRepetitions\"] as number) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n // Collect frame names in the file (cached per analysis run would be better)\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n\n if (sameNameFrames && sameNameFrames.length >= minRepetitions) {\n // Only report on the first occurrence to avoid duplicate issues\n if (sameNameFrames[0] === node.id) {\n return {\n ruleId: missingComponentDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" appears ${sameNameFrames.length} times - consider making it a component`,\n };\n }\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"component\",\n why: \"Detached instances lose their connection to the source component\",\n impact: \"Updates to the component won't propagate to this instance\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a similar name\n const components = context.file.components;\n const nodeName = node.name.toLowerCase();\n\n for (const [, component] of Object.entries(components)) {\n if (nodeName.includes(component.name.toLowerCase())) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" may be a detached instance of component \"${component.name}\"`,\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// nested-instance-override\n// ============================================\n\nconst nestedInstanceOverrideDef: RuleDefinition = {\n id: \"nested-instance-override\",\n name: \"Nested Instance Override\",\n category: \"component\",\n why: \"Excessive overrides in instances make components harder to maintain\",\n impact: \"Component updates may not work as expected\",\n fix: \"Create a variant or new component for significantly different use cases\",\n};\n\nconst nestedInstanceOverrideCheck: RuleCheckFn = (node, context) => {\n if (!isComponentInstance(node)) return null;\n\n // Check for component property overrides\n if (!node.componentProperties) return null;\n\n const overrideCount = Object.keys(node.componentProperties).length;\n\n // Flag if there are too many overrides\n if (overrideCount > 5) {\n return {\n ruleId: nestedInstanceOverrideDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has ${overrideCount} property overrides - consider creating a variant`,\n };\n }\n\n return null;\n};\n\nexport const nestedInstanceOverride = defineRule({\n definition: nestedInstanceOverrideDef,\n check: nestedInstanceOverrideCheck,\n});\n\n// ============================================\n// variant-not-used\n// ============================================\n\nconst variantNotUsedDef: RuleDefinition = {\n id: \"variant-not-used\",\n name: \"Variant Not Used\",\n category: \"component\",\n why: \"Using instances but not leveraging variants defeats their purpose\",\n impact: \"Manual changes instead of using designed variants\",\n fix: \"Use the appropriate variant instead of overriding the default\",\n};\n\nconst variantNotUsedCheck: RuleCheckFn = (_node, _context) => {\n // This would require checking if an instance is using default variant\n // when other variants exist that better match the current state\n // Needs more context from component definitions\n return null;\n};\n\nexport const variantNotUsed = defineRule({\n definition: variantNotUsedDef,\n check: variantNotUsedCheck,\n});\n\n// ============================================\n// component-property-unused\n// ============================================\n\nconst componentPropertyUnusedDef: RuleDefinition = {\n id: \"component-property-unused\",\n name: \"Component Property Unused\",\n category: \"component\",\n why: \"Component properties should be utilized to expose customization\",\n impact: \"Hardcoded values that should be configurable\",\n fix: \"Connect the value to a component property\",\n};\n\nconst componentPropertyUnusedCheck: RuleCheckFn = (node, _context) => {\n if (!isComponent(node)) return null;\n\n // Check if component has property definitions but children don't use them\n if (!node.componentPropertyDefinitions) return null;\n\n const definedProps = Object.keys(node.componentPropertyDefinitions);\n if (definedProps.length === 0) return null;\n\n // This would require checking if properties are actually bound\n // Simplified for now\n return null;\n};\n\nexport const componentPropertyUnused = defineRule({\n definition: componentPropertyUnusedDef,\n check: componentPropertyUnusedCheck,\n});\n\n// ============================================\n// single-use-component\n// ============================================\n\nconst singleUseComponentDef: RuleDefinition = {\n id: \"single-use-component\",\n name: \"Single Use Component\",\n category: \"component\",\n why: \"Components used only once add complexity without reuse benefit\",\n impact: \"Unnecessary abstraction increases maintenance overhead\",\n fix: \"Consider inlining if this component won't be reused\",\n};\n\nconst singleUseComponentCheck: RuleCheckFn = (node, context) => {\n if (!isComponent(node)) return null;\n\n // Count instances of this component in the file\n let instanceCount = 0;\n\n function countInstances(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId === node.id) {\n instanceCount++;\n }\n if (n.children) {\n for (const child of n.children) {\n countInstances(child);\n }\n }\n }\n\n countInstances(context.file.document);\n\n if (instanceCount === 1) {\n return {\n ruleId: singleUseComponentDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `Component \"${node.name}\" is only used once`,\n };\n }\n\n return null;\n};\n\nexport const singleUseComponent = defineRule({\n definition: singleUseComponentDef,\n check: singleUseComponentCheck,\n});\n\n// ============================================\n// missing-component-description\n// ============================================\n\n/**\n * Module-level Set for deduplication across nodes within a single analysis run.\n * Tracks componentIds that have already been flagged to avoid duplicate issues\n * when many INSTANCE nodes reference the same component.\n *\n * Note: This Set persists for the lifetime of the module (i.e., the process).\n * The analysis engine is expected to clear it between runs if needed, but since\n * each CLI invocation starts a fresh process this is safe in practice.\n */\nconst seenMissingDescriptionComponentIds = new Set<string>();\n\nconst missingComponentDescriptionDef: RuleDefinition = {\n id: \"missing-component-description\",\n name: \"Missing Component Description\",\n category: \"component\",\n why: \"Component descriptions in Figma are the primary channel for communicating intent, usage guidelines, and prop expectations to developers. Without them, developers must reverse-engineer purpose from visual appearance alone.\",\n impact: \"Increases implementation ambiguity, especially for icon-only components, compound components with multiple variants, and components whose names are variant key strings that give no prose context.\",\n fix: \"Open the component in Figma, select it, and add a description in the right-hand panel under the component's properties. Include: what the component is, when to use it, any accessibility or interaction notes, and the owning team or design token set if applicable.\",\n};\n\nconst missingComponentDescriptionCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\") return null;\n\n const componentId = node.componentId;\n if (!componentId) return null;\n\n const componentMeta = context.file.components[componentId];\n if (!componentMeta) return null;\n\n if (componentMeta.description.trim() !== \"\") return null;\n\n // Deduplicate: emit at most one issue per unique componentId\n if (seenMissingDescriptionComponentIds.has(componentId)) return null;\n seenMissingDescriptionComponentIds.add(componentId);\n\n return {\n ruleId: missingComponentDescriptionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `Component \"${componentMeta.name}\" has no description. Descriptions help developers understand purpose and usage.`,\n };\n};\n\nexport const missingComponentDescription = defineRule({\n definition: missingComponentDescriptionDef,\n check: missingComponentDescriptionCheck,\n});\n\n/**\n * Reset deduplication state between analysis runs.\n * Call this at the start of each analysis if the process is long-running\n * (e.g. MCP server mode).\n */\nexport function resetMissingComponentDescriptionState(): void {\n seenMissingDescriptionComponentIds.clear();\n}\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isExcludedName } from \"../excluded-names.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nconst DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nconst NON_SEMANTIC_NAMES = [\n \"rectangle\",\n \"ellipse\",\n \"vector\",\n \"line\",\n \"polygon\",\n \"star\",\n \"path\",\n \"shape\",\n \"image\",\n \"fill\",\n \"stroke\",\n];\n\nfunction isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\nfunction isNonSemanticName(name: string): boolean {\n const normalized = name.toLowerCase().trim();\n return NON_SEMANTIC_NAMES.includes(normalized);\n}\n\nfunction hasNumericSuffix(name: string): boolean {\n return /\\s+\\d+$/.test(name);\n}\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n// ============================================\n// default-name\n// ============================================\n\nconst defaultNameDef: RuleDefinition = {\n id: \"default-name\",\n name: \"Default Name\",\n category: \"naming\",\n why: \"Default names like 'Frame 123' provide no context about the element's purpose\",\n impact: \"Designers and developers cannot understand the structure\",\n fix: \"Rename with a descriptive, semantic name (e.g., 'Header', 'ProductCard')\",\n};\n\nconst defaultNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n if (!isDefaultName(node.name)) return null;\n\n return {\n ruleId: defaultNameDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is a default name - provide a meaningful name`,\n };\n};\n\nexport const defaultName = defineRule({\n definition: defaultNameDef,\n check: defaultNameCheck,\n});\n\n// ============================================\n// non-semantic-name\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"naming\",\n why: \"Names like 'Rectangle' describe shape, not purpose\",\n impact: \"Structure is hard to understand without context\",\n fix: \"Use names that describe what the element represents (e.g., 'Divider', 'Avatar')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n if (!isNonSemanticName(node.name)) return null;\n\n // Allow non-semantic names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is a non-semantic name - describe its purpose`,\n };\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"naming\",\n why: \"Mixed naming conventions at the same level create confusion\",\n impact: \"Harder to navigate and maintain the design\",\n fix: \"Use a consistent naming convention for sibling elements\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// numeric-suffix-name\n// ============================================\n\nconst numericSuffixNameDef: RuleDefinition = {\n id: \"numeric-suffix-name\",\n name: \"Numeric Suffix Name\",\n category: \"naming\",\n why: \"Names with numeric suffixes often indicate copy-paste duplication\",\n impact: \"Suggests the element might need componentization\",\n fix: \"Remove the suffix or create a component if duplicated\",\n};\n\nconst numericSuffixNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n if (isDefaultName(node.name)) return null; // Already caught by default-name\n if (!hasNumericSuffix(node.name)) return null;\n\n return {\n ruleId: numericSuffixNameDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has a numeric suffix - consider renaming`,\n };\n};\n\nexport const numericSuffixName = defineRule({\n definition: numericSuffixNameDef,\n check: numericSuffixNameCheck,\n});\n\n// ============================================\n// too-long-name\n// ============================================\n\nconst tooLongNameDef: RuleDefinition = {\n id: \"too-long-name\",\n name: \"Too Long Name\",\n category: \"naming\",\n why: \"Very long names are hard to read and use in code\",\n impact: \"Clutters the layer panel and makes selectors unwieldy\",\n fix: \"Shorten the name while keeping it descriptive\",\n};\n\nconst tooLongNameCheck: RuleCheckFn = (node, context, options) => {\n if (!node.name) return null;\n\n const maxLength = (options?.[\"maxLength\"] as number) ??\n getRuleOption(\"too-long-name\", \"maxLength\", 50);\n\n if (node.name.length <= maxLength) return null;\n\n return {\n ruleId: tooLongNameDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name.substring(0, 30)}...\" is ${node.name.length} chars (max: ${maxLength})`,\n };\n};\n\nexport const tooLongName = defineRule({\n definition: tooLongNameDef,\n check: tooLongNameCheck,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nfunction hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nfunction isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\";\n}\n\nfunction hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ============================================\n// ambiguous-structure\n// ============================================\n\nconst ambiguousStructureDef: RuleDefinition = {\n id: \"ambiguous-structure\",\n name: \"Ambiguous Structure\",\n category: \"ai-readability\",\n why: \"Overlapping nodes without Auto Layout create ambiguous visual hierarchy\",\n impact: \"AI cannot reliably determine the reading order or structure\",\n fix: \"Use Auto Layout to create clear, explicit structure\",\n};\n\nconst ambiguousStructureCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null; // Auto Layout provides clear structure\n if (!node.children || node.children.length < 2) return null;\n\n // Check for overlapping children\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n\n if (childA && childB && hasOverlappingBounds(childA, childB)) {\n // Check if this is intentional layering (both visible)\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: ambiguousStructureDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has overlapping children without Auto Layout`,\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const ambiguousStructure = defineRule({\n definition: ambiguousStructureDef,\n check: ambiguousStructureCheck,\n});\n\n// ============================================\n// z-index-dependent-layout\n// ============================================\n\nconst zIndexDependentLayoutDef: RuleDefinition = {\n id: \"z-index-dependent-layout\",\n name: \"Z-Index Dependent Layout\",\n category: \"ai-readability\",\n why: \"Using overlapping layers to create visual layout is hard to interpret\",\n impact: \"Code generation may misinterpret the intended layout\",\n fix: \"Restructure using Auto Layout to express the visual relationship explicitly\",\n};\n\nconst zIndexDependentLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (!node.children || node.children.length < 2) return null;\n\n // Look for patterns where position overlap is used to create visual effects\n // e.g., badge on card, avatar overlapping header\n let significantOverlapCount = 0;\n\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n\n if (!childA || !childB) continue;\n if (childA.visible === false || childB.visible === false) continue;\n\n const boxA = childA.absoluteBoundingBox;\n const boxB = childB.absoluteBoundingBox;\n\n if (!boxA || !boxB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n // Calculate overlap percentage\n const overlapX = Math.min(boxA.x + boxA.width, boxB.x + boxB.width) -\n Math.max(boxA.x, boxB.x);\n const overlapY = Math.min(boxA.y + boxA.height, boxB.y + boxB.height) -\n Math.max(boxA.y, boxB.y);\n\n if (overlapX > 0 && overlapY > 0) {\n const overlapArea = overlapX * overlapY;\n const smallerArea = Math.min(\n boxA.width * boxA.height,\n boxB.width * boxB.height\n );\n\n // If overlap is significant (> 20% of smaller element)\n if (overlapArea > smallerArea * 0.2) {\n significantOverlapCount++;\n }\n }\n }\n }\n }\n\n if (significantOverlapCount > 0) {\n return {\n ruleId: zIndexDependentLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses layer stacking for layout (${significantOverlapCount} overlaps)`,\n };\n }\n\n return null;\n};\n\nexport const zIndexDependentLayout = defineRule({\n definition: zIndexDependentLayoutDef,\n check: zIndexDependentLayoutCheck,\n});\n\n// ============================================\n// missing-layout-hint\n// ============================================\n\nconst missingLayoutHintDef: RuleDefinition = {\n id: \"missing-layout-hint\",\n name: \"Missing Layout Hint\",\n category: \"ai-readability\",\n why: \"Complex nesting without Auto Layout makes structure unpredictable\",\n impact: \"AI may generate incorrect code due to ambiguous relationships\",\n fix: \"Add Auto Layout or simplify the nesting structure\",\n};\n\nconst missingLayoutHintCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n // Check for nested containers without layout hints\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n\n // If there are multiple nested containers without layout direction\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n\n if (withoutLayout.length >= 2) {\n return {\n ruleId: missingLayoutHintDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has ${withoutLayout.length} nested containers without layout hints`,\n };\n }\n }\n\n return null;\n};\n\nexport const missingLayoutHint = defineRule({\n definition: missingLayoutHintDef,\n check: missingLayoutHintCheck,\n});\n\n// ============================================\n// invisible-layer\n// ============================================\n\nconst invisibleLayerDef: RuleDefinition = {\n id: \"invisible-layer\",\n name: \"Invisible Layer\",\n category: \"ai-readability\",\n why: \"Hidden layers add noise and may confuse analysis tools\",\n impact: \"Exported code may include unnecessary elements\",\n fix: \"Delete hidden layers or move them to a separate 'archive' page\",\n};\n\nconst invisibleLayerCheck: RuleCheckFn = (node, context) => {\n if (node.visible !== false) return null;\n\n // Skip if parent is also invisible (only report top-level invisible)\n if (context.parent?.visible === false) return null;\n\n return {\n ruleId: invisibleLayerDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is hidden - consider removing if not needed`,\n };\n};\n\nexport const invisibleLayer = defineRule({\n definition: invisibleLayerDef,\n check: invisibleLayerCheck,\n});\n\n// ============================================\n// empty-frame\n// ============================================\n\nconst emptyFrameDef: RuleDefinition = {\n id: \"empty-frame\",\n name: \"Empty Frame\",\n category: \"ai-readability\",\n why: \"Empty frames add noise and may indicate incomplete design\",\n impact: \"Generates unnecessary wrapper elements in code\",\n fix: \"Remove the frame or add content\",\n};\n\nconst emptyFrameCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"FRAME\") return null;\n if (node.children && node.children.length > 0) return null;\n\n // Allow empty frames that are clearly placeholders (small size)\n if (node.absoluteBoundingBox) {\n const { width, height } = node.absoluteBoundingBox;\n // Allow small placeholder frames (icons, spacers)\n if (width <= 48 && height <= 48) return null;\n }\n\n return {\n ruleId: emptyFrameDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" is an empty frame`,\n };\n};\n\nexport const emptyFrame = defineRule({\n definition: emptyFrameDef,\n check: emptyFrameCheck,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\nfunction hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nfunction isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\";\n}\n\nfunction isTextNode(node: AnalysisNode): boolean {\n return node.type === \"TEXT\";\n}\n\nfunction isImageNode(node: AnalysisNode): boolean {\n // Images are often rectangles with image fills\n if (node.type === \"RECTANGLE\" && node.fills) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"IMAGE\") return true;\n }\n }\n return false;\n}\n\n// ============================================\n// hardcode-risk\n// ============================================\n\nconst hardcodeRiskDef: RuleDefinition = {\n id: \"hardcode-risk\",\n name: \"Hardcode Risk\",\n category: \"handoff-risk\",\n why: \"Absolute positioning with fixed values creates inflexible layouts\",\n impact: \"Layout will break when content changes or on different screens\",\n fix: \"Use Auto Layout with relative positioning\",\n};\n\nconst hardcodeRiskCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n\n // Check for absolute positioning\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n // Check if parent has Auto Layout\n if (context.parent && hasAutoLayout(context.parent)) {\n return {\n ruleId: hardcodeRiskDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" uses absolute positioning with fixed values`,\n };\n }\n\n return null;\n};\n\nexport const hardcodeRisk = defineRule({\n definition: hardcodeRiskDef,\n check: hardcodeRiskCheck,\n});\n\n// ============================================\n// text-truncation-unhandled\n// ============================================\n\nconst textTruncationUnhandledDef: RuleDefinition = {\n id: \"text-truncation-unhandled\",\n name: \"Text Truncation Unhandled\",\n category: \"handoff-risk\",\n why: \"Text nodes without truncation handling may overflow\",\n impact: \"Long text will break the layout\",\n fix: \"Set text truncation (ellipsis) or ensure container can grow\",\n};\n\nconst textTruncationUnhandledCheck: RuleCheckFn = (node, context) => {\n if (!isTextNode(node)) return null;\n\n // Check if parent is Auto Layout with fixed size\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n\n // Check if text has fixed width in the Auto Layout direction\n // This is a heuristic - would need more Figma API data for accuracy\n // Parent direction would be: context.parent.layoutMode\n\n // If parent is horizontal and text doesn't have truncation configured\n // Simplified check - full implementation would examine text truncation property\n if (node.absoluteBoundingBox) {\n const { width } = node.absoluteBoundingBox;\n // Flag if text is in a constrained space but long\n if (node.characters && node.characters.length > 50 && width < 300) {\n return {\n ruleId: textTruncationUnhandledDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" may need text truncation handling`,\n };\n }\n }\n\n return null;\n};\n\nexport const textTruncationUnhandled = defineRule({\n definition: textTruncationUnhandledDef,\n check: textTruncationUnhandledCheck,\n});\n\n// ============================================\n// image-no-placeholder\n// ============================================\n\nconst imageNoPlaceholderDef: RuleDefinition = {\n id: \"image-no-placeholder\",\n name: \"Image No Placeholder\",\n category: \"handoff-risk\",\n why: \"Images without placeholder state may cause layout shifts\",\n impact: \"Poor user experience during image loading\",\n fix: \"Define a placeholder state or background color\",\n};\n\nconst imageNoPlaceholderCheck: RuleCheckFn = (node, context) => {\n if (!isImageNode(node)) return null;\n\n // Check if there's a background color or placeholder indicator\n // This is a heuristic - images should have fallback fills\n if (node.fills && Array.isArray(node.fills) && node.fills.length === 1) {\n const fill = node.fills[0] as Record<string, unknown>;\n if (fill[\"type\"] === \"IMAGE\") {\n return {\n ruleId: imageNoPlaceholderDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" image has no placeholder fill`,\n };\n }\n }\n\n return null;\n};\n\nexport const imageNoPlaceholder = defineRule({\n definition: imageNoPlaceholderDef,\n check: imageNoPlaceholderCheck,\n});\n\n// ============================================\n// prototype-link-in-design\n// ============================================\n\nconst prototypeLinkInDesignDef: RuleDefinition = {\n id: \"prototype-link-in-design\",\n name: \"Prototype Link in Design\",\n category: \"handoff-risk\",\n why: \"Prototype connections may affect how the design is interpreted\",\n impact: \"Developers may misunderstand which elements should be interactive\",\n fix: \"Document interactions separately or use clear naming\",\n};\n\nconst prototypeLinkInDesignCheck: RuleCheckFn = (_node, _context) => {\n // This would require checking prototype/interaction data\n // Not available in basic node structure - needs more Figma API data\n return null;\n};\n\nexport const prototypeLinkInDesign = defineRule({\n definition: prototypeLinkInDesignDef,\n check: prototypeLinkInDesignCheck,\n});\n\n// ============================================\n// no-dev-status\n// ============================================\n\nconst noDevStatusDef: RuleDefinition = {\n id: \"no-dev-status\",\n name: \"No Dev Status\",\n category: \"handoff-risk\",\n why: \"Without dev status, developers cannot know if a design is ready\",\n impact: \"May implement designs that are still in progress\",\n fix: \"Mark frames as 'Ready for Dev' or 'Completed' when appropriate\",\n};\n\nconst noDevStatusCheck: RuleCheckFn = (node, context) => {\n // Only check top-level frames (likely screens/pages)\n if (node.type !== \"FRAME\") return null;\n if (context.depth > 1) return null;\n\n // Check for devStatus\n if (node.devStatus) return null;\n\n return {\n ruleId: noDevStatusDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: `\"${node.name}\" has no dev status set`,\n };\n};\n\nexport const noDevStatus = defineRule({\n definition: noDevStatusDef,\n check: noDevStatusCheck,\n});\n","import { z } from \"zod\";\n\nexport const SamplingStrategySchema = z.enum([\"all\", \"top-issues\", \"random\"]);\nexport type SamplingStrategy = z.infer<typeof SamplingStrategySchema>;\n\nexport const CalibrationStatusSchema = z.enum([\n \"pending\",\n \"analyzing\",\n \"converting\",\n \"evaluating\",\n \"tuning\",\n \"completed\",\n \"failed\",\n]);\nexport type CalibrationStatus = z.infer<typeof CalibrationStatusSchema>;\n\nexport const CalibrationConfigSchema = z.object({\n input: z.string(),\n token: z.string().optional(),\n targetNodeId: z.string().optional(),\n maxConversionNodes: z.number().int().positive().default(20),\n samplingStrategy: SamplingStrategySchema.default(\"top-issues\"),\n outputPath: z.string().default(\"logs/calibration/calibration-report.md\"),\n});\n\nexport type CalibrationConfig = z.infer<typeof CalibrationConfigSchema>;\n\nexport interface CalibrationRun {\n config: CalibrationConfig;\n status: CalibrationStatus;\n startedAt: string;\n completedAt?: string;\n error?: string;\n}\n","import { z } from \"zod\";\nimport type { AnalysisResult } from \"@/core/engine/rule-engine.js\";\nimport type { ScoreReport } from \"@/core/engine/scoring.js\";\nimport type { RuleId } from \"@/core/contracts/rule.js\";\nimport type { Severity } from \"@/core/contracts/severity.js\";\n\nexport const NodeIssueSummarySchema = z.object({\n nodeId: z.string(),\n nodePath: z.string(),\n totalScore: z.number(),\n issueCount: z.number(),\n flaggedRuleIds: z.array(z.string()),\n severities: z.array(z.string()),\n});\n\nexport type NodeIssueSummary = z.infer<typeof NodeIssueSummarySchema>;\n\nexport interface AnalysisAgentInput {\n analysisResult: AnalysisResult;\n}\n\nexport interface AnalysisAgentOutput {\n analysisResult: AnalysisResult;\n scoreReport: ScoreReport;\n nodeIssueSummaries: NodeIssueSummary[];\n}\n\nexport interface NodeIssueDetail {\n ruleId: RuleId;\n severity: Severity;\n calculatedScore: number;\n message: string;\n}\n","import { z } from \"zod\";\n\nexport const DifficultySchema = z.enum([\"easy\", \"moderate\", \"hard\", \"failed\"]);\nexport type Difficulty = z.infer<typeof DifficultySchema>;\n\nexport const RuleRelatedStruggleSchema = z.object({\n ruleId: z.string(),\n description: z.string(),\n actualImpact: DifficultySchema,\n});\n\nexport type RuleRelatedStruggle = z.infer<typeof RuleRelatedStruggleSchema>;\n\nexport const UncoveredStruggleSchema = z.object({\n description: z.string(),\n suggestedCategory: z.string(),\n estimatedImpact: DifficultySchema,\n});\n\nexport type UncoveredStruggle = z.infer<typeof UncoveredStruggleSchema>;\n\nexport const ConversionRecordSchema = z.object({\n nodeId: z.string(),\n nodePath: z.string(),\n generatedCode: z.string(),\n difficulty: DifficultySchema,\n notes: z.string(),\n ruleRelatedStruggles: z.array(RuleRelatedStruggleSchema),\n uncoveredStruggles: z.array(UncoveredStruggleSchema),\n durationMs: z.number(),\n});\n\nexport type ConversionRecord = z.infer<typeof ConversionRecordSchema>;\n\nexport interface ConversionExecutorResult {\n generatedCode: string;\n difficulty: Difficulty;\n notes: string;\n ruleRelatedStruggles: RuleRelatedStruggle[];\n uncoveredStruggles: UncoveredStruggle[];\n}\n\nexport type ConversionExecutor = (\n nodeId: string,\n fileKey: string,\n flaggedRuleIds: string[]\n) => Promise<ConversionExecutorResult>;\n\nexport interface ConversionAgentInput {\n fileKey: string;\n nodes: Array<{\n nodeId: string;\n nodePath: string;\n flaggedRuleIds: string[];\n }>;\n}\n\nexport interface ConversionAgentOutput {\n records: ConversionRecord[];\n skippedNodeIds: string[];\n}\n","import { z } from \"zod\";\nimport { DifficultySchema } from \"./conversion-agent.js\";\nimport { SeveritySchema } from \"@/core/contracts/severity.js\";\n\nexport const MismatchTypeSchema = z.enum([\n \"overscored\",\n \"underscored\",\n \"missing-rule\",\n \"validated\",\n]);\nexport type MismatchType = z.infer<typeof MismatchTypeSchema>;\n\nexport const MismatchCaseSchema = z.object({\n type: MismatchTypeSchema,\n nodeId: z.string(),\n nodePath: z.string(),\n ruleId: z.string().optional(),\n currentScore: z.number().optional(),\n currentSeverity: SeveritySchema.optional(),\n actualDifficulty: DifficultySchema,\n reasoning: z.string(),\n});\n\nexport type MismatchCase = z.infer<typeof MismatchCaseSchema>;\n\nexport interface EvaluationAgentInput {\n nodeIssueSummaries: Array<{\n nodeId: string;\n nodePath: string;\n flaggedRuleIds: string[];\n }>;\n conversionRecords: Array<{\n nodeId: string;\n nodePath: string;\n difficulty: string;\n ruleRelatedStruggles: Array<{\n ruleId: string;\n description: string;\n actualImpact: string;\n }>;\n uncoveredStruggles: Array<{\n description: string;\n suggestedCategory: string;\n estimatedImpact: string;\n }>;\n }>;\n ruleScores: Record<string, { score: number; severity: string }>;\n}\n\nexport interface EvaluationAgentOutput {\n mismatches: MismatchCase[];\n validatedRules: string[];\n}\n","import { z } from \"zod\";\nimport { SeveritySchema } from \"@/core/contracts/severity.js\";\n\nexport const ConfidenceSchema = z.enum([\"high\", \"medium\", \"low\"]);\nexport type Confidence = z.infer<typeof ConfidenceSchema>;\n\nexport const ScoreAdjustmentSchema = z.object({\n ruleId: z.string(),\n currentScore: z.number(),\n proposedScore: z.number(),\n currentSeverity: SeveritySchema,\n proposedSeverity: SeveritySchema.optional(),\n reasoning: z.string(),\n confidence: ConfidenceSchema,\n supportingCases: z.number(),\n});\n\nexport type ScoreAdjustment = z.infer<typeof ScoreAdjustmentSchema>;\n\nexport const NewRuleProposalSchema = z.object({\n suggestedId: z.string(),\n category: z.string(),\n description: z.string(),\n suggestedSeverity: SeveritySchema,\n suggestedScore: z.number(),\n reasoning: z.string(),\n supportingCases: z.number(),\n});\n\nexport type NewRuleProposal = z.infer<typeof NewRuleProposalSchema>;\n\nexport interface TuningAgentInput {\n mismatches: Array<{\n type: string;\n nodeId: string;\n nodePath: string;\n ruleId?: string | undefined;\n currentScore?: number | undefined;\n currentSeverity?: string | undefined;\n actualDifficulty: string;\n reasoning: string;\n }>;\n ruleScores: Record<string, { score: number; severity: string }>;\n}\n\nexport interface TuningAgentOutput {\n adjustments: ScoreAdjustment[];\n newRuleProposals: NewRuleProposal[];\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES } from \"../contracts/category.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { VERSION } from \"../../index.js\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Severity weights for density calculation\n */\nconst SEVERITY_DENSITY_WEIGHT: Record<Severity, number> = {\n blocking: 3.0,\n risk: 2.0,\n \"missing-info\": 1.0,\n suggestion: 0.5,\n};\n\n/**\n * Total rules per category\n */\nconst TOTAL_RULES_PER_CATEGORY: Record<Category, number> = {\n layout: 11,\n token: 7,\n component: 6,\n naming: 5,\n \"ai-readability\": 5,\n \"handoff-risk\": 5,\n};\n\n/**\n * Category weights for overall score (all equal by default)\n */\nconst CATEGORY_WEIGHT: Record<Category, number> = {\n layout: 1.0,\n token: 1.0,\n component: 1.0,\n naming: 1.0,\n \"ai-readability\": 1.0,\n \"handoff-risk\": 1.0,\n};\n\n/**\n * Score composition weights\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - unique rules / total category rules) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n */\nexport function calculateScores(result: AnalysisResult): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n }\n\n // Count issues by severity per category and track unique rules\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n categoryScores[category].weightedIssueCount += SEVERITY_DENSITY_WEIGHT[severity];\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n const totalRules = TOTAL_RULES_PER_CATEGORY[category];\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: fewer unique rules = higher score (issues are concentrated)\n // If no issues, diversity score is 100 (perfect)\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const diversityRatio = uniqueRules.size / totalRules;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as weighted average of categories\n let totalWeight = 0;\n let weightedSum = 0;\n\n for (const category of CATEGORIES) {\n const weight = CATEGORY_WEIGHT[category];\n weightedSum += categoryScores[category].percentage * weight;\n totalWeight += weight;\n }\n\n const overallPercentage = totalWeight > 0\n ? Math.round(weightedSum / totalWeight)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n lines.push(` Total: ${report.summary.totalIssues}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n const labels: Record<Category, string> = {\n layout: \"Layout\",\n token: \"Design Token\",\n component: \"Component\",\n naming: \"Naming\",\n \"ai-readability\": \"AI Readability\",\n \"handoff-risk\": \"Handoff Risk\",\n };\n return labels[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n return {\n version: VERSION,\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n issueCount: result.issues.length,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n summary: formatScoreSummary(scores),\n };\n}\n","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n layout:\n \"Auto Layout, responsive constraints, nesting depth, absolute positioning\",\n token: \"Design token binding for colors, fonts, shadows, spacing grid\",\n component: \"Component reuse, detached instances, variant coverage\",\n naming: \"Semantic layer names, naming conventions, default names\",\n \"ai-readability\":\n \"Structure clarity for AI code generation, z-index, empty frames\",\n \"handoff-risk\":\n \"Hardcoded values, text truncation, image placeholders, dev status\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/** Severity to CSS dot class (for plugin UI) */\nexport function severityDotClass(sev: string): string {\n const map: Record<string, string> = {\n blocking: \"dot-blocking\",\n risk: \"dot-risk\",\n \"missing-info\": \"dot-missing\",\n suggestion: \"dot-suggestion\",\n };\n return map[sev] ?? \"dot-missing\";\n}\n\n/** Severity to CSS score class (for plugin UI) */\nexport function severityScoreClass(sev: string): string {\n const map: Record<string, string> = {\n blocking: \"score-blocking\",\n risk: \"score-risk\",\n \"missing-info\": \"score-missing\",\n suggestion: \"score-suggestion\",\n };\n return map[sev] ?? \"score-missing\";\n}\n\n/** Severity to Tailwind dot class (for report-html / web app) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"bg-red-500\",\n risk: \"bg-amber-500\",\n \"missing-info\": \"bg-zinc-400\",\n suggestion: \"bg-green-500\",\n };\n return map[sev];\n}\n\n/** Severity to Tailwind badge class (for report-html / web app) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"bg-red-500/10 text-red-600 border-red-500/20\",\n risk: \"bg-amber-500/10 text-amber-600 border-amber-500/20\",\n \"missing-info\": \"bg-zinc-500/10 text-zinc-600 border-zinc-500/20\",\n suggestion: \"bg-green-500/10 text-green-600 border-green-500/20\",\n };\n return map[sev];\n}\n\n/** Score percentage to Tailwind badge style (for report-html / web app) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"bg-green-500/10 text-green-700 border-green-500/20\";\n if (pct >= 50) return \"bg-amber-500/10 text-amber-700 border-amber-500/20\";\n return \"bg-red-500/10 text-red-700 border-red-500/20\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg block\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" class=\"stroke-border\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\" class=\"font-sans\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg block\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" class=\"stroke-border\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\" class=\"font-sans\">${pct}</text>\n </svg>`;\n}\n","// Report HTML module - shadcn/ui styled HTML report generation\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult, AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n SEVERITY_LABELS,\n CATEGORY_DESCRIPTIONS,\n SEVERITY_ORDER,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n scoreBadgeStyle,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\nimport { VERSION } from \"../../index.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\n// ---- Main ----\n\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const screenshotMap = new Map(\n (options?.nodeScreenshots ?? []).map((ns) => [ns.nodeId, ns])\n );\n const figmaToken = options?.figmaToken;\n const quickWins = getQuickWins(result.issues, 5);\n const issuesByCategory = groupIssuesByCategory(result.issues);\n\n return `<!DOCTYPE html>\n<html lang=\"en\" class=\"antialiased\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <script src=\"https://cdn.tailwindcss.com\"></script>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <script>\n tailwind.config = {\n theme: {\n extend: {\n fontFamily: { sans: ['Inter', 'ui-sans-serif', 'system-ui', '-apple-system', 'sans-serif'] },\n colors: {\n border: 'hsl(240 5.9% 90%)',\n ring: 'hsl(240 5.9% 10%)',\n background: 'hsl(0 0% 100%)',\n foreground: 'hsl(240 10% 3.9%)',\n muted: { DEFAULT: 'hsl(240 4.8% 95.9%)', foreground: 'hsl(240 3.8% 46.1%)' },\n card: { DEFAULT: 'hsl(0 0% 100%)', foreground: 'hsl(240 10% 3.9%)' },\n },\n borderRadius: { lg: '0.5rem', md: 'calc(0.5rem - 2px)', sm: 'calc(0.5rem - 4px)' },\n }\n }\n }\n </script>\n <style>\n details summary::-webkit-details-marker { display: none; }\n details summary::marker { content: \"\"; }\n details summary { list-style: none; }\n .gauge-fill { transition: stroke-dashoffset 0.8s cubic-bezier(0.4,0,0.2,1); }\n @media print {\n .no-print { display: none !important; }\n .topbar-print { position: static !important; background: white !important; color: hsl(240 10% 3.9%) !important; }\n }\n </style>\n</head>\n<body class=\"bg-muted font-sans text-foreground min-h-screen\">\n\n <!-- Top Bar -->\n <header class=\"topbar-print sticky top-0 z-50 bg-zinc-950 text-white border-b border-zinc-800\">\n <div class=\"max-w-[960px] mx-auto px-6 py-3 flex items-center gap-4\">\n <span class=\"font-semibold text-sm tracking-tight\">CanICode</span>\n <span class=\"text-zinc-400 text-sm truncate\">${esc(file.name)}</span>\n <span class=\"ml-auto text-zinc-500 text-xs no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"max-w-[960px] mx-auto px-6 pb-16\">\n\n <!-- Overall Score -->\n <section class=\"flex flex-col items-center pt-12 pb-6\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"mt-3 text-center\">\n <span class=\"text-lg font-semibold\">${scores.overall.percentage}</span>\n <span class=\"text-muted-foreground text-sm ml-1\">/ 100</span>\n </div>\n <p class=\"text-muted-foreground text-sm mt-1\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"bg-card border border-border rounded-lg shadow-sm p-6 mb-6\">\n <div class=\"grid grid-cols-3 sm:grid-cols-6 gap-4\">\n${CATEGORIES.map(cat => {\n const cs = scores.byCategory[cat];\n const desc = CATEGORY_DESCRIPTIONS[cat];\n return ` <a href=\"#cat-${cat}\" class=\"flex flex-col items-center group relative cursor-pointer no-underline text-foreground hover:opacity-80 transition-opacity\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"text-xs font-medium mt-2.5 text-center leading-tight\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"text-[11px] text-muted-foreground\">${cs.issueCount} issues</span>\n <div class=\"absolute bottom-full mb-2 left-1/2 -translate-x-1/2 hidden group-hover:block bg-zinc-900 text-white text-xs px-3 py-2 rounded-md whitespace-nowrap z-10 shadow-lg pointer-events-none\">\n ${esc(desc)}\n <div class=\"absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-zinc-900\"></div>\n </div>\n </a>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"bg-card border border-border rounded-lg shadow-sm p-4 mb-6\">\n <div class=\"flex flex-wrap items-center justify-center gap-6\">\n ${renderSummaryDot(\"bg-red-500\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"bg-amber-500\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"bg-zinc-400\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"bg-green-500\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"border-l border-border pl-6 flex items-center gap-2\">\n <span class=\"text-xl font-bold tracking-tight\">${scores.summary.totalIssues}</span>\n <span class=\"text-sm text-muted-foreground\">Total</span>\n </div>\n </div>\n </section>\n\n${quickWins.length > 0 ? renderOpportunities(quickWins, file.fileKey) : \"\"}\n\n <!-- Categories -->\n <div class=\"space-y-3\">\n${CATEGORIES.map(cat => renderCategory(cat, scores, issuesByCategory.get(cat) ?? [], file.fileKey, screenshotMap, figmaToken)).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"mt-12 pt-6 border-t border-border text-center\">\n <p class=\"text-sm text-muted-foreground\">Generated by <span class=\"font-semibold text-foreground\">CanICode</span> <span class=\"text-muted-foreground/60\">v${VERSION}</span></p>\n <p class=\"text-xs text-muted-foreground/60 mt-1\">${new Date().toLocaleString()} · ${result.nodeCount} nodes · Max depth ${result.maxDepth}</p>\n </footer>\n\n </main>\n\n${figmaToken ? ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const rule = btn.dataset.rule;\n const message = btn.dataset.message;\n const path = btn.dataset.path;\n const fix = btn.dataset.fix;\n const why = btn.dataset.why;\n const impact = btn.dataset.impact;\n\n const commentBody = '[CanICode] ' + rule + '\\\\n\\\\nFix: ' + fix + '\\\\nWhy: ' + why + '\\\\nImpact: ' + impact + '\\\\n\\\\n' + message + '\\\\nNode: ' + path;\n\n btn.disabled = true;\n btn.textContent = 'Sending...';\n\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: nodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) throw new Error(await res.text());\n btn.textContent = 'Sent \\\\u2713';\n btn.classList.remove('hover:bg-muted');\n btn.classList.add('text-green-600', 'border-green-500/30');\n } catch (e) {\n btn.textContent = 'Failed \\\\u2717';\n btn.classList.remove('hover:bg-muted');\n btn.classList.add('text-red-600', 'border-red-500/30');\n btn.disabled = false;\n console.error('Failed to post Figma comment:', e);\n }\n }\n </script>` : \"\"}\n</body>\n</html>`;\n}\n\n// ---- Components ----\n\nfunction renderSummaryDot(dotClass: string, count: number, label: string): string {\n return `<div class=\"flex items-center gap-2\">\n <span class=\"w-2.5 h-2.5 rounded-full ${dotClass}\"></span>\n <span class=\"text-lg font-bold tracking-tight\">${count}</span>\n <span class=\"text-sm text-muted-foreground\">${label}</span>\n </div>`;\n}\n\n\nfunction renderOpportunities(issues: AnalysisIssue[], fileKey: string): string {\n const maxAbs = issues.reduce((m, i) => Math.max(m, Math.abs(i.calculatedScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"bg-card border border-border rounded-lg shadow-sm mb-6 overflow-hidden\">\n <div class=\"px-6 py-4 border-b border-border\">\n <h2 class=\"text-sm font-semibold flex items-center gap-2\">\n <span class=\"w-2 h-2 rounded-full bg-red-500\"></span>\n Opportunities\n </h2>\n <p class=\"text-xs text-muted-foreground mt-1\">Top blocking issues — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"divide-y divide-border\">\n${issues.map(issue => {\n const def = issue.rule.definition;\n const link = buildFigmaDeepLink(fileKey, issue.violation.nodeId);\n const barW = Math.round((Math.abs(issue.calculatedScore) / maxAbs) * 100);\n return ` <div class=\"px-6 py-3 flex items-center gap-4 hover:bg-muted/50 transition-colors\">\n <div class=\"flex-1 min-w-0\">\n <div class=\"text-sm font-medium truncate\">${esc(def.name)}</div>\n <div class=\"text-xs text-muted-foreground truncate mt-0.5\">${esc(issue.violation.message)}</div>\n </div>\n <div class=\"w-32 flex items-center gap-2 shrink-0\">\n <div class=\"flex-1 h-1.5 bg-muted rounded-full overflow-hidden\">\n <div class=\"h-full bg-red-500 rounded-full\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"text-xs font-medium text-red-600 w-12 text-right\">${issue.calculatedScore}</span>\n </div>\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" class=\"text-xs text-muted-foreground hover:text-foreground shrink-0 no-print\">Figma →</a>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nfunction renderCategory(\n cat: Category,\n scores: ScoreReport,\n issues: AnalysisIssue[],\n fileKey: string,\n screenshotMap: Map<string, NodeScreenshot>,\n figmaToken?: string\n): string {\n const cs = scores.byCategory[cat];\n const hasProblems = issues.some(i => i.config.severity === \"blocking\" || i.config.severity === \"risk\");\n\n const bySeverity = new Map<Severity, AnalysisIssue[]>();\n for (const sev of SEVERITY_ORDER) bySeverity.set(sev, []);\n for (const issue of issues) bySeverity.get(issue.config.severity)?.push(issue);\n\n return `\n <details id=\"cat-${cat}\" class=\"bg-card border border-border rounded-lg shadow-sm overflow-hidden group\"${hasProblems ? \" open\" : \"\"}>\n <summary class=\"px-5 py-3.5 flex items-center gap-3 cursor-pointer hover:bg-muted/50 transition-colors select-none\">\n <span class=\"inline-flex items-center justify-center w-10 h-6 rounded-md text-xs font-bold border ${scoreBadgeStyle(cs.percentage)}\">${cs.percentage}</span>\n <div class=\"flex-1 min-w-0\">\n <div class=\"text-sm font-semibold\">${CATEGORY_LABELS[cat]}</div>\n <div class=\"text-xs text-muted-foreground\">${esc(CATEGORY_DESCRIPTIONS[cat])}</div>\n </div>\n <span class=\"text-xs text-muted-foreground\">${cs.issueCount} issues</span>\n <svg class=\"w-4 h-4 text-muted-foreground transition-transform group-open:rotate-180 shrink-0 no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"border-t border-border\">\n${issues.length === 0\n ? ' <div class=\"px-5 py-4 text-sm text-green-600 font-medium\">No issues found</div>'\n : SEVERITY_ORDER\n .filter(sev => (bySeverity.get(sev)?.length ?? 0) > 0)\n .map(sev => renderSeverityGroup(sev, bySeverity.get(sev) ?? [], fileKey, screenshotMap, figmaToken))\n .join(\"\\n\")\n}\n </div>\n </details>`;\n}\n\nfunction renderSeverityGroup(\n sev: Severity,\n issues: AnalysisIssue[],\n fileKey: string,\n screenshotMap: Map<string, NodeScreenshot>,\n figmaToken?: string\n): string {\n return ` <div class=\"px-5 py-3\">\n <div class=\"flex items-center gap-2 mb-2\">\n <span class=\"w-2 h-2 rounded-full ${severityDot(sev)}\"></span>\n <span class=\"text-xs font-semibold uppercase tracking-wider\">${SEVERITY_LABELS[sev]}</span>\n <span class=\"text-xs text-muted-foreground ml-auto\">${issues.length}</span>\n </div>\n <div class=\"space-y-1\">\n${issues.map(issue => renderIssueRow(issue, fileKey, screenshotMap, figmaToken)).join(\"\\n\")}\n </div>\n </div>`;\n}\n\nfunction renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n screenshotMap: Map<string, NodeScreenshot>,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const def = issue.rule.definition;\n const link = buildFigmaDeepLink(fileKey, issue.violation.nodeId);\n const screenshot = screenshotMap.get(issue.violation.nodeId);\n\n const screenshotHtml = screenshot\n ? `<div class=\"mt-3\"><a href=\"${link}\" target=\"_blank\" rel=\"noopener\"><img src=\"data:image/png;base64,${screenshot.screenshotBase64}\" alt=\"${esc(screenshot.nodePath)}\" class=\"max-w-[240px] border border-border rounded-md\"></a></div>`\n : \"\";\n\n return ` <details class=\"border border-border rounded-md overflow-hidden\">\n <summary class=\"flex items-center gap-2.5 px-3 py-2 text-sm cursor-pointer hover:bg-muted/50 transition-colors\">\n <span class=\"w-1.5 h-1.5 rounded-full ${severityDot(sev)} shrink-0\"></span>\n <span class=\"font-medium shrink-0\">${esc(def.name)}</span>\n <span class=\"text-muted-foreground truncate text-xs flex-1\">${esc(issue.violation.message)}</span>\n <span class=\"inline-flex items-center px-1.5 py-0.5 text-[10px] font-medium rounded border ${severityBadge(sev)} shrink-0\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"px-3 py-3 bg-muted/30 border-t border-border text-sm space-y-2\">\n <div class=\"font-mono text-xs text-muted-foreground break-all\">${esc(issue.violation.nodePath)}</div>\n <div class=\"text-muted-foreground leading-relaxed space-y-1\">\n <p><span class=\"font-medium text-foreground\">Why:</span> ${esc(def.why)}</p>\n <p><span class=\"font-medium text-foreground\">Impact:</span> ${esc(def.impact)}</p>\n <p><span class=\"font-medium text-foreground\">Fix:</span> ${esc(def.fix)}</p>\n </div>${screenshotHtml}\n <div class=\"flex items-center gap-2 mt-1 no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" class=\"inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium border border-border rounded-md hover:bg-muted transition-colors\">Open in Figma <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(issue.violation.nodeId)}\" data-rule=\"${esc(def.name)}\" data-message=\"${esc(issue.violation.message)}\" data-path=\"${esc(issue.violation.nodePath)}\" data-fix=\"${esc(def.fix)}\" data-why=\"${esc(def.why)}\" data-impact=\"${esc(def.impact)}\" class=\"inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium border border-border rounded-md hover:bg-muted transition-colors cursor-pointer\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Utils ----\n\nfunction getQuickWins(issues: AnalysisIssue[], limit: number): AnalysisIssue[] {\n return issues\n .filter(issue => issue.config.severity === \"blocking\")\n .sort((a, b) => a.calculatedScore - b.calculatedScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\nconst esc = escapeHtml;\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../../contracts/severity.js\";\nimport type { RuleConfig } from \"../../contracts/rule.js\";\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n colorTolerance: z.number().int().positive().optional(),\n rules: z.record(z.string(), RuleOverrideSchema).optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply global colorTolerance\n if (overrides.colorTolerance !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"tolerance\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, tolerance: overrides.colorTolerance },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","import { z } from \"zod\";\nimport { CategorySchema } from \"../../contracts/category.js\";\nimport { SeveritySchema } from \"../../contracts/severity.js\";\n\nexport const MatchConditionSchema = z.object({\n // Node type conditions\n type: z.array(z.string()).optional(),\n notType: z.array(z.string()).optional(),\n\n // Name conditions (case-insensitive, substring match)\n nameContains: z.string().optional(),\n nameNotContains: z.string().optional(),\n namePattern: z.string().optional(),\n\n // Size conditions\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n\n // Layout conditions\n hasAutoLayout: z.boolean().optional(),\n hasChildren: z.boolean().optional(),\n minChildren: z.number().optional(),\n maxChildren: z.number().optional(),\n\n // Component conditions\n isComponent: z.boolean().optional(),\n isInstance: z.boolean().optional(),\n hasComponentId: z.boolean().optional(),\n\n // Visibility\n isVisible: z.boolean().optional(),\n\n // Fill/style conditions\n hasFills: z.boolean().optional(),\n hasStrokes: z.boolean().optional(),\n hasEffects: z.boolean().optional(),\n\n // Depth condition\n minDepth: z.number().optional(),\n maxDepth: z.number().optional(),\n});\n\nexport type MatchCondition = z.infer<typeof MatchConditionSchema>;\n\nexport const CustomRuleSchema = z.object({\n id: z.string(),\n category: CategorySchema,\n severity: SeveritySchema,\n score: z.number().int().max(0),\n match: MatchConditionSchema,\n message: z.string().optional(),\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n // Backward compat: silently ignore the old prompt field\n prompt: z.string().optional(),\n});\n\nexport type CustomRule = z.infer<typeof CustomRuleSchema>;\n\nexport const CustomRulesFileSchema = z.array(CustomRuleSchema);\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { Rule, RuleConfig, RuleViolation, RuleContext } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { CustomRulesFileSchema, type CustomRule } from \"./custom-rule-schema.js\";\n\n/**\n * Load custom rules from a JSON file and return Rule objects + their configs\n */\nexport async function loadCustomRules(filePath: string): Promise<{\n rules: Rule[];\n configs: Record<string, RuleConfig>;\n}> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n const customRules = CustomRulesFileSchema.parse(parsed);\n\n const rules: Rule[] = [];\n const configs: Record<string, RuleConfig> = {};\n\n for (const cr of customRules) {\n // Skip rules that only have a prompt (old format) and no match conditions\n if (!cr.match) continue;\n\n rules.push(toRule(cr));\n configs[cr.id] = {\n severity: cr.severity,\n score: cr.score,\n enabled: true,\n };\n }\n\n return { rules, configs };\n}\n\nfunction toRule(cr: CustomRule): Rule {\n return {\n definition: {\n id: cr.id,\n name: cr.id.replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase()),\n category: cr.category,\n why: cr.why,\n impact: cr.impact,\n fix: cr.fix,\n },\n check: createPatternCheck(cr),\n };\n}\n\n/**\n * Create a check function that evaluates all match conditions against a node.\n * ALL conditions must pass (AND logic) for the rule to fire.\n */\nfunction createPatternCheck(cr: CustomRule) {\n return (\n node: AnalysisNode,\n context: RuleContext,\n ): RuleViolation | null => {\n // Skip non-visual nodes\n if (node.type === \"DOCUMENT\" || node.type === \"CANVAS\") return null;\n\n const match = cr.match;\n\n // Type checks\n if (match.type && !match.type.includes(node.type)) return null;\n if (match.notType && match.notType.includes(node.type)) return null;\n\n // Name checks (case-insensitive)\n if (match.nameContains !== undefined && !node.name.toLowerCase().includes(match.nameContains.toLowerCase())) return null;\n if (match.nameNotContains !== undefined && node.name.toLowerCase().includes(match.nameNotContains.toLowerCase())) return null;\n if (match.namePattern !== undefined && !new RegExp(match.namePattern, \"i\").test(node.name)) return null;\n\n // Size checks\n const bbox = node.absoluteBoundingBox;\n if (match.minWidth !== undefined && (!bbox || bbox.width < match.minWidth)) return null;\n if (match.maxWidth !== undefined && (!bbox || bbox.width > match.maxWidth)) return null;\n if (match.minHeight !== undefined && (!bbox || bbox.height < match.minHeight)) return null;\n if (match.maxHeight !== undefined && (!bbox || bbox.height > match.maxHeight)) return null;\n\n // Layout checks\n if (match.hasAutoLayout === true && !node.layoutMode) return null;\n if (match.hasAutoLayout === false && node.layoutMode) return null;\n if (match.hasChildren === true && (!node.children || node.children.length === 0)) return null;\n if (match.hasChildren === false && node.children && node.children.length > 0) return null;\n if (match.minChildren !== undefined && (!node.children || node.children.length < match.minChildren)) return null;\n if (match.maxChildren !== undefined && node.children && node.children.length > match.maxChildren) return null;\n\n // Component checks\n if (match.isComponent === true && node.type !== \"COMPONENT\" && node.type !== \"COMPONENT_SET\") return null;\n if (match.isComponent === false && (node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\")) return null;\n if (match.isInstance === true && node.type !== \"INSTANCE\") return null;\n if (match.isInstance === false && node.type === \"INSTANCE\") return null;\n if (match.hasComponentId === true && !node.componentId) return null;\n if (match.hasComponentId === false && node.componentId) return null;\n\n // Visibility\n if (match.isVisible === true && !node.visible) return null;\n if (match.isVisible === false && node.visible) return null;\n\n // Fill/stroke/effect checks\n if (match.hasFills === true && (!node.fills || node.fills.length === 0)) return null;\n if (match.hasFills === false && node.fills && node.fills.length > 0) return null;\n if (match.hasStrokes === true && (!node.strokes || node.strokes.length === 0)) return null;\n if (match.hasStrokes === false && node.strokes && node.strokes.length > 0) return null;\n if (match.hasEffects === true && (!node.effects || node.effects.length === 0)) return null;\n if (match.hasEffects === false && node.effects && node.effects.length > 0) return null;\n\n // Depth checks\n if (match.minDepth !== undefined && context.depth < match.minDepth) return null;\n if (match.maxDepth !== undefined && context.depth > match.maxDepth) return null;\n\n // ALL conditions passed — flag this node\n const msg = (cr.message ?? `\"${node.name}\" matched custom rule \"${cr.id}\"`)\n .replace(/\\{name\\}/g, node.name)\n .replace(/\\{type\\}/g, node.type);\n\n return {\n ruleId: cr.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n message: msg,\n };\n };\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile } from \"../core/engine/loader.js\";\nimport { parseDesignData } from \"../core/engine/design-data-parser.js\";\nimport { enrichWithDesignContext } from \"../core/adapters/figma-mcp-adapter.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/custom/config-loader.js\";\nimport { loadCustomRules } from \"../core/rules/custom/custom-rule-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\n\n// Load .env for FIGMA_TOKEN\nconfig();\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst server = new McpServer({\n name: \"canicode\",\n version: pkg.version,\n});\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nTwo ways to provide design data:\n1. designData — Pass Figma node data directly (from Figma MCP get_metadata). Recommended when using Figma MCP.\n2. input — Figma URL (fetches via REST API, requires FIGMA_TOKEN).\n\nTypical flow with Figma MCP (recommended, no token needed):\n Step 1: Call the official Figma MCP's get_metadata tool to get the node tree\n Step 2: Call the official Figma MCP's get_design_context tool on the same node to get style data\n Step 3: Pass get_metadata result as designData and get_design_context code as designContext to this tool\n\nThe designContext parameter enriches analysis with style information (colors, layout, spacing, effects)\nthat get_metadata alone cannot provide. Without it, token and layout rules may not fire.\n\nIMPORTANT — Before calling this tool, check which data source is available:\n- If the official Figma MCP (https://mcp.figma.com/mcp) is connected: use get_metadata + get_design_context → designData + designContext flow. No token needed.\n- If Figma MCP is NOT connected: use the input parameter with a Figma URL. This requires a FIGMA_TOKEN.\n Tell the user: \"The official Figma MCP server is not connected. To use without a token, set it up:\n claude mcp add -s project -t http figma https://mcp.figma.com/mcp\n Otherwise, provide a Figma API token via FIGMA_TOKEN env var or the token parameter.\"`,\n {\n designData: z.string().optional().describe(\"Figma node data from Figma MCP get_metadata (XML or JSON). Pass this instead of input when using Figma MCP.\"),\n designContext: z.string().optional().describe(\"Code output from Figma MCP get_design_context. Enriches designData with style info (colors, layout, spacing, effects). Highly recommended alongside designData.\"),\n input: z.string().optional().describe(\"Figma URL. Used when designData is not provided. Requires FIGMA_TOKEN.\"),\n fileKey: z.string().optional().describe(\"Figma file key (used with designData to generate deep links)\"),\n fileName: z.string().optional().describe(\"Figma file name (used with designData for display)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n customRulesPath: z.string().optional().describe(\"Path to custom rules JSON file\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ designData, designContext, input, fileKey, fileName, token, preset, targetNodeId, configPath, customRulesPath }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n let file;\n let nodeId: string | undefined;\n\n if (designData) {\n // Direct data from Figma MCP\n file = parseDesignData(designData, fileKey ?? \"unknown\", fileName);\n\n // Enrich with design context if provided\n if (designContext) {\n enrichWithDesignContext(file, designContext, targetNodeId);\n }\n } else if (input) {\n // Fetch via REST API or load from fixture\n const loaded = await loadFile(input, token);\n file = loaded.file;\n nodeId = loaded.nodeId;\n } else {\n throw new Error(\"Provide either designData (from Figma MCP) or input (Figma URL).\");\n }\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n if (customRulesPath) {\n const { rules, configs: customConfigs } = await loadCustomRules(customRulesPath);\n for (const rule of rules) {\n ruleRegistry.register(rule);\n }\n configs = { ...configs, ...customConfigs };\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n });\n\n const scores = calculateScores(result);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // Open report in browser\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: designData ? \"mcp-data\" : \"url\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- custom-rules: How to add project-specific checks\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"rules\", \"config\", \"custom-rules\", \"visual-compare\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from REFERENCE.md)\n const inlineTopics: Record<string, string> = {\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -- npx -y -p canicode canicode-mcp\nclaude mcp add -s project -t http figma https://mcp.figma.com/mcp\n\\`\\`\\`\n\nWith Figma API token (no Figma MCP needed):\n\\`\\`\\`bash\nclaude mcp add canicode -e FIGMA_TOKEN=figd_xxxxxxxxxxxxx -- npx -y -p canicode canicode-mcp\n\\`\\`\\``,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (from Figma screenshot) | Viewport width override |\n| --height <px> | (from Figma screenshot) | Viewport height override |\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (scale=2)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to REFERENCE.md for config/custom-rules/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/REFERENCE.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/REFERENCE.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"custom-rules\": \"## Custom Rules\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nViewport is automatically matched to the Figma screenshot dimensions.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir }) => {\n try {\n const { visualCompare } = await import(\"../core/engine/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}
1
+ {"version":3,"sources":["../../src/core/comparison/visual-compare-helpers.ts","../../src/core/comparison/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/component-resolver.ts","../../src/core/contracts/figma-node.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../package.json","../../src/core/engine/scoring.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/render.ts","../../src/core/report-html/index.ts","../../src/core/rules/config-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/core/rules/node-semantics.ts","../../src/core/rules/rule-exceptions.ts","../../src/core/rules/rule-messages.ts","../../src/core/rules/structure/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/interaction/index.ts","../../src/mcp/server.ts"],"names":["resolve","statSync","readFileSync","width","height","mkdirSync","dirname","writeFileSync","existsSync","PNG","z","config","BATCH_SIZE","join","response","file","componentDefs","interactionDests","esc","readFile","version","require","visualCompare"],"mappings":";;;;;;;;;;;;;;;;;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AAA,MAAM,gBAAA,GAAyD;AAAA,IAC7D,WAAA,EAAa,KAAA;AAAA,IACb,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,SAAS,mBAAA;AAAoB,GAC/B;AACA,EAAA,MAAM,KAAA,GAAQ,kBAAiB,IAAK,eAAA;AACpC,mBAA4B,aAAA,GAAgB,KAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Pure helper functions extracted from visual-compare.ts.\n * These have no side effects beyond file I/O and can be tested directly.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, statSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Directory used for caching Figma screenshots. */\nexport const FIGMA_CACHE_DIR = \"/tmp/canicode-figma-cache\";\n\n/**\n * Known @1x screenshot widths from fixture convention.\n * Screenshots at these widths are captured at 1x scale (pixel width = logical width).\n * All other widths are assumed @2x (e.g., 2400px PNG = 1200px logical).\n */\nexport const KNOWN_1X_WIDTHS = [1920, 768];\n\n/**\n * Infer the export scale of a fixture screenshot based on its pixel width.\n * Uses KNOWN_1X_WIDTHS convention: 1920/768 = @1x, others = @2x.\n */\nexport function inferExportScale(pngWidth: number): number {\n return KNOWN_1X_WIDTHS.includes(pngWidth) ? 1 : 2;\n}\n\n/** Cache time-to-live: 1 hour. */\nexport const FIGMA_CACHE_TTL_MS = 60 * 60 * 1000;\n\n/**\n * Tolerance for detecting integer scale factors (@2x, @3x).\n * Broader tolerance because render/rounding errors accumulate at higher scales.\n */\nexport const SCALE_ROUNDING_TOLERANCE = 0.08;\n\n/**\n * Tolerance for detecting 1x (unity) scale.\n * Tighter to avoid false positives — misidentifying a scaled PNG as 1x.\n */\nexport const UNITY_SCALE_TOLERANCE = 0.02;\n\n/**\n * Get the cache path for a given fileKey + nodeId combination.\n */\nexport function getFigmaCachePath(fileKey: string, nodeId: string, scale: number): string {\n // Sanitize nodeId for use as filename (replace : with -)\n const safeNodeId = nodeId.replace(/:/g, \"-\");\n return resolve(FIGMA_CACHE_DIR, `${fileKey}_${safeNodeId}@${scale}x.png`);\n}\n\n/**\n * Check if a cached Figma screenshot exists and is still fresh (within TTL).\n */\nexport function isCacheFresh(cachePath: string): boolean {\n try {\n const stats = statSync(cachePath);\n return Date.now() - stats.mtimeMs < FIGMA_CACHE_TTL_MS;\n } catch {\n // File doesn't exist or was removed between check and stat (TOCTOU safe)\n return false;\n }\n}\n\n/**\n * Infer device pixel ratio so the Playwright screenshot matches Figma PNG pixel dimensions.\n */\nexport function inferDeviceScaleFactor(\n pngW: number,\n pngH: number,\n logicalW: number,\n logicalH: number,\n fallback: number,\n): number {\n if (logicalW <= 0 || logicalH <= 0) return 1;\n const sx = pngW / logicalW;\n const sy = pngH / logicalH;\n const rounded = Math.round((sx + sy) / 2);\n if (rounded >= 2 && Math.abs(sx - rounded) < SCALE_ROUNDING_TOLERANCE && Math.abs(sy - rounded) < SCALE_ROUNDING_TOLERANCE) {\n return rounded;\n }\n if (Math.abs(sx - 1) < UNITY_SCALE_TOLERANCE && Math.abs(sy - 1) < UNITY_SCALE_TOLERANCE) return 1;\n return fallback >= 2 ? fallback : Math.max(1, Math.round(sx));\n}\n\n/**\n * Pad a PNG to target dimensions with a high-contrast fill color (magenta #FF00FF).\n * Unlike resize, padding preserves original pixels 1:1 and guarantees that\n * any size difference is counted as mismatched pixels by pixelmatch.\n *\n * Note: If both images contain magenta in the padded area, those pixels\n * will match — extremely rare in real designs but theoretically possible.\n */\nexport function padPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const padded = new PNG({ width: targetWidth, height: targetHeight });\n // Fill entire canvas with magenta (FF00FF) — guaranteed to differ from any real content\n for (let i = 0; i < padded.data.length; i += 4) {\n padded.data[i] = 255; // R\n padded.data[i + 1] = 0; // G\n padded.data[i + 2] = 255; // B\n padded.data[i + 3] = 255; // A\n }\n // Copy original pixels into top-left corner\n for (let y = 0; y < png.height; y++) {\n for (let x = 0; x < png.width; x++) {\n const srcIdx = (y * png.width + x) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n padded.data[dstIdx] = png.data[srcIdx]!;\n padded.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n padded.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n padded.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return padded;\n}\n\n/** Options for screenshot comparison. */\nexport interface CompareOptions {\n /** How to handle size mismatches: \"pad\" (magenta fill) or \"crop\" (min dimensions). Default: \"pad\". */\n sizeMismatch?: \"pad\" | \"crop\";\n /** pixelmatch threshold (0-1). Default: 0.1. */\n threshold?: number;\n}\n\n/**\n * Crop a PNG to target dimensions (top-left corner preserved).\n */\nexport function cropPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const cropped = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n png.data.copy(cropped.data, y * targetWidth * 4, y * png.width * 4, y * png.width * 4 + targetWidth * 4);\n }\n return cropped;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nexport function compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n options?: CompareOptions,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold ?? 0.1;\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n let img1: PNG = raw1;\n let img2: PNG = raw2;\n\n // Size mismatch — normalize to same dimensions\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n if (sizeMismatch === \"crop\") {\n const width = Math.min(raw1.width, raw2.width);\n const height = Math.min(raw1.height, raw2.height);\n img1 = cropPng(raw1, width, height);\n img2 = cropPng(raw2, width, height);\n } else {\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n img1 = padPng(raw1, width, height);\n img2 = padPng(raw2, width, height);\n }\n }\n\n const { width, height } = img1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = diffPixels === 0 ? 100 : Math.floor((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n// ── Root width expansion (for responsive comparison) ─────────────────────\n\n/**\n * Replace fixed root-element widths in HTML with fluid values so the layout\n * can expand to fill a wider viewport.\n *\n * Targets the first CSS rule that sets a pixel `width` on the root container\n * (commonly `.root`, `body > div`, etc.) and replaces it with `width: 100%`.\n * Also removes `min-width` pixel constraints.\n *\n * Originally from `src/experiments/ablation/run-condition.ts`.\n */\nexport function expandRootWidth(html: string): string {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return html;\n\n const style = styleMatch[0];\n // Find the first CSS rule block (the root element's rule)\n const firstRuleMatch = style.match(/([^{}]*\\{)([^}]*)\\}/);\n if (!firstRuleMatch) return html;\n\n const rulePrefix = firstRuleMatch[1]!; // e.g. \".root {\"\n const ruleBody = firstRuleMatch[2]!; // e.g. \" width: 375px; min-width: 375px; \"\n\n // Replace width and min-width only inside the first rule\n const newBody = ruleBody\n .replace(/(?<![-\\w])width:\\s*\\d+px/, \"width: 100%\")\n .replace(/min-width:\\s*\\d+px/g, \"min-width: 0\");\n\n const newRule = `${rulePrefix}${newBody}}`;\n const newStyle = style.replace(firstRuleMatch[0], newRule);\n return html.replace(style, newStyle);\n}\n\n// ── Code metrics (shared with ablation helpers) ─────────────────────────\n\n/** Count unique CSS class selectors in an HTML string's <style> block. */\nexport function countCssClasses(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const classes = styleMatch[0].match(/\\.[a-zA-Z][\\w-]*\\s*[{,:]/g);\n return new Set(classes?.map((c) => c.replace(/\\s*[{,:]$/, \"\"))).size;\n}\n\n/** Count unique CSS custom property definitions in an HTML string's <style> block. */\nexport function countCssVariables(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const vars = styleMatch[0].match(/--[\\w-]+\\s*:/g);\n return new Set(vars?.map((v) => v.replace(/\\s*:$/, \"\"))).size;\n}\n\n/** Compute code metrics from an HTML string. */\nexport function computeCodeMetrics(html: string): {\n htmlBytes: number;\n htmlLines: number;\n cssClassCount: number;\n cssVariableCount: number;\n} {\n return {\n htmlBytes: Buffer.byteLength(html, \"utf-8\"),\n htmlLines: html.split(\"\\n\").length,\n cssClassCount: countCssClasses(html),\n cssVariableCount: countCssVariables(html),\n };\n}\n","/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, existsSync, copyFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { PNG } from \"pngjs\";\nimport {\n FIGMA_CACHE_DIR,\n getFigmaCachePath,\n isCacheFresh,\n inferDeviceScaleFactor,\n inferExportScale,\n compareScreenshots,\n expandRootWidth,\n type CompareOptions,\n} from \"./visual-compare-helpers.js\";\n\n/** Result of a visual comparison between Figma design and rendered code. */\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\n/** Options for the visual comparison pipeline. */\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n /**\n * Logical CSS viewport (CSS pixels). Omit a dimension to infer from the Figma PNG\n * using `figmaExportScale`. When the whole object is omitted, both dimensions are inferred.\n */\n viewport?: { width?: number; height?: number } | undefined;\n /**\n * Figma Images API `scale` and assumed scale for fixture `figma.png` (e.g. from `save-fixture`).\n * Default 2 matches REST exports and avoids comparing a @2x PNG against a 1× Playwright capture.\n */\n figmaExportScale?: number | undefined;\n /**\n * Path to a local Figma screenshot file. When provided, skips URL-based fetch\n * and uses this file directly as the ground truth. Useful for responsive comparison\n * where multiple fixture screenshots exist at different viewports.\n */\n figmaScreenshotPath?: string | undefined;\n /**\n * When true, replace the root element's fixed pixel width with `width: 100%`\n * before rendering. This allows the layout to expand to fill the viewport,\n * which is needed for responsive comparison (e.g., 375px design rendered at 768px).\n */\n expandRoot?: boolean | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API, with file-based caching.\n * Cache key: fileKey + nodeId. Cache location: /tmp/canicode-figma-cache/. TTL: 1 hour.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n scale: number,\n): Promise<void> {\n const cachePath = getFigmaCachePath(fileKey, nodeId, scale);\n\n // Return cached version if fresh\n if (isCacheFresh(cachePath)) {\n mkdirSync(dirname(outputPath), { recursive: true });\n copyFileSync(cachePath, outputPath);\n return;\n }\n\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=${scale}`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n\n // Write to output path\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n\n // Save to cache\n mkdirSync(FIGMA_CACHE_DIR, { recursive: true });\n writeFileSync(cachePath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n * @param deviceScaleFactor - Pass 2 when the Figma reference is @2x and `viewport` is logical CSS size.\n */\nexport async function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n logicalViewport: { width: number; height: number },\n deviceScaleFactor: number = 1,\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n try {\n const context = await browser.newContext({\n viewport: logicalViewport,\n deviceScaleFactor,\n });\n const page = await context.newPage();\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n } finally {\n await browser.close();\n }\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Figma screenshot — use local file if provided, otherwise fetch via API\n if (options.figmaScreenshotPath) {\n if (!existsSync(options.figmaScreenshotPath)) {\n throw new Error(`Figma screenshot not found: ${options.figmaScreenshotPath}`);\n }\n mkdirSync(dirname(figmaScreenshotPath), { recursive: true });\n copyFileSync(options.figmaScreenshotPath, figmaScreenshotPath);\n } else if (!existsSync(figmaScreenshotPath)) {\n const fetchScale = options.figmaExportScale ?? 2;\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath, fetchScale);\n if (!existsSync(figmaScreenshotPath)) {\n throw new Error(`Figma screenshot was not created at expected path: ${figmaScreenshotPath}`);\n }\n }\n\n // Step 2: Logical viewport + deviceScaleFactor so code.png matches figma.png pixels (@2x, etc.)\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n // Auto-detect export scale from PNG width when using local screenshot (KNOWN_1X_WIDTHS convention)\n const exportScale = options.figmaExportScale ?? inferExportScale(figmaPng.width);\n const hasViewportOverride = options.viewport !== undefined;\n let logicalW: number;\n let logicalH: number;\n let deviceScaleFactor: number;\n\n if (!hasViewportOverride) {\n logicalW = Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH = Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = exportScale;\n } else {\n logicalW =\n options.viewport!.width ?? Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH =\n options.viewport!.height ?? Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = inferDeviceScaleFactor(\n figmaPng.width,\n figmaPng.height,\n logicalW,\n logicalH,\n exportScale,\n );\n }\n\n // Step 3: Render code screenshot at matching physical resolution\n let renderPath = options.codePath;\n if (options.expandRoot) {\n const originalHtml = readFileSync(resolve(options.codePath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderPath = resolve(outputDir, \"code-expanded.html\");\n writeFileSync(renderPath, expandedHtml);\n }\n await renderCodeScreenshot(\n renderPath,\n codeScreenshotPath,\n { width: logicalW, height: logicalH },\n deviceScaleFactor,\n );\n\n // Validate both screenshots exist before comparing\n if (!existsSync(codeScreenshotPath)) {\n throw new Error(`Code screenshot was not created at expected path: ${codeScreenshotPath}`);\n }\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n\n/** Options for renderAndCompare. */\nexport interface RenderAndCompareOptions {\n /** How to handle size mismatches. Default: \"pad\". */\n sizeMismatch?: CompareOptions[\"sizeMismatch\"];\n /** Output file suffix (e.g. \"baseline\", \"stripped-layout\"). */\n suffix?: string;\n /** pixelmatch threshold. Default: 0.1. */\n threshold?: number;\n /** Replace root element's fixed width with 100% before rendering. */\n expandRoot?: boolean;\n}\n\n/**\n * Render HTML → screenshot, then compare against a Figma screenshot.\n * Handles export scale inference and size normalization.\n *\n * Extracted from ablation helpers to be shared by calibration + experiments.\n */\nexport async function renderAndCompare(\n htmlPath: string,\n figmaScreenshotPath: string,\n outputDir: string,\n options?: RenderAndCompareOptions,\n): Promise<{ similarity: number }> {\n const suffix = options?.suffix ?? \"output\";\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold;\n\n const figmaImage = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const figmaWidth = figmaImage.width;\n const exportScale = inferExportScale(figmaWidth);\n const logicalW = Math.max(1, Math.round(figmaWidth / exportScale));\n const logicalH = Math.max(1, Math.round(figmaImage.height / exportScale));\n\n let renderHtmlPath = htmlPath;\n if (options?.expandRoot) {\n const originalHtml = readFileSync(resolve(htmlPath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderHtmlPath = resolve(outputDir, `code-expanded-${suffix}.html`);\n writeFileSync(renderHtmlPath, expandedHtml);\n }\n const codePngPath = resolve(outputDir, `code-${suffix}.png`);\n await renderCodeScreenshot(renderHtmlPath, codePngPath, { width: logicalW, height: logicalH }, exportScale);\n\n const figmaCopyPath = resolve(outputDir, `figma-${suffix}.png`);\n copyFileSync(figmaScreenshotPath, figmaCopyPath);\n\n const diffPath = resolve(outputDir, `diff-${suffix}.png`);\n const compareOpts: CompareOptions = { sizeMismatch };\n if (threshold !== undefined) compareOpts.threshold = threshold;\n return compareScreenshots(figmaCopyPath, codePngPath, diffPath, compareOpts);\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"pixel-critical\",\n \"responsive-critical\",\n \"code-quality\",\n \"token-management\",\n \"semantic\",\n \"interaction\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n \"pixel-critical\": \"Pixel Critical\",\n \"responsive-critical\": \"Responsive Critical\",\n \"code-quality\": \"Code Quality\",\n \"token-management\": \"Token Management\",\n \"semantic\": \"Semantic\",\n \"interaction\": \"Interaction\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n /** Depth relative to the nearest COMPONENT/INSTANCE ancestor. Resets at component boundaries. */\n componentDepth: number;\n maxDepth: number;\n path: string[];\n /** Ancestor node types from root to parent (excludes current node). */\n ancestorTypes: string[];\n siblings?: AnalysisNode[] | undefined;\n /** Per-analysis shared state. Created fresh for each analysis run, eliminating module-level mutable state. */\n analysisState: Map<string, unknown>;\n}\n\n/**\n * Get or initialize per-analysis state for a rule.\n * Each key gets its own lazily-initialized state that persists for the duration of one analysis run.\n */\nexport function getAnalysisState<T>(context: RuleContext, key: string, init: () => T): T {\n if (context.analysisState.has(key)) {\n return context.analysisState.get(key) as T;\n }\n const value = init();\n context.analysisState.set(key, value);\n return value;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n subType?: string;\n nodeId: string;\n nodePath: string;\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Pixel Critical — layout issues that directly affect pixel accuracy (ΔV ≥ 5%)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"non-layout-container\"\n // Responsive Critical — size issues that break at different viewports (ΔV ≥ 15%)\n | \"fixed-size-in-auto-layout\"\n | \"missing-size-constraint\"\n // Code Quality — structural issues affecting code reuse (ΔV ≈ 0%, CSS classes -8~15)\n | \"missing-component\"\n | \"detached-instance\"\n | \"variant-structure-mismatch\"\n | \"deep-nesting\"\n // Token Management — raw values without design tokens\n | \"raw-value\"\n | \"irregular-spacing\"\n // Interaction — missing state variants and prototype links for interactive components\n | \"missing-interaction-state\"\n | \"missing-prototype\"\n // Semantic — naming issues with negligible pixel impact (ΔV < 2%)\n | \"non-standard-naming\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"pixel-critical\", \"responsive-critical\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { Category } from \"../contracts/category.js\";\nimport type { RuleConfig, RuleId } from \"../contracts/rule.js\";\n\n/**\n * Maps each rule ID to its category.\n * Categories are based on ablation experiment data (PR #149, #150):\n * - pixel-critical: ΔV ≥ 5% — layout info removal directly degrades pixel accuracy\n * - responsive-critical: ΔV ≥ 15% at expanded viewport — size info critical for responsive\n * - code-quality: ΔV ≈ 0% but CSS classes -8~15 — affects code structure, not pixels\n * - token-management: raw values without design tokens — wrong input = wrong output\n * - semantic: ΔV < 2%, negligible code difference — naming and semantic issues\n */\nexport const RULE_ID_CATEGORY: Record<RuleId, Category> = {\n // Pixel Critical\n \"no-auto-layout\": \"pixel-critical\",\n \"absolute-position-in-auto-layout\": \"pixel-critical\",\n \"non-layout-container\": \"pixel-critical\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"responsive-critical\",\n \"missing-size-constraint\": \"responsive-critical\",\n // Code Quality\n \"missing-component\": \"code-quality\",\n \"detached-instance\": \"code-quality\",\n \"variant-structure-mismatch\": \"code-quality\",\n \"deep-nesting\": \"code-quality\",\n // Token Management\n \"raw-value\": \"token-management\",\n \"irregular-spacing\": \"token-management\",\n // Interaction\n \"missing-interaction-state\": \"interaction\",\n \"missing-prototype\": \"interaction\",\n // Semantic\n \"non-standard-naming\": \"semantic\",\n \"non-semantic-name\": \"semantic\",\n \"inconsistent-naming-convention\": \"semantic\",\n};\n\n/**\n * Central configuration for all rules.\n * Scores based on ablation experiment + AI implementation interview (#200):\n * - pixel-critical: -10 ~ -7 (layout strip caused ΔV +5.4%)\n * - responsive-critical: -8 ~ -6 (size-constraints ΔV +15.9% at responsive viewports)\n * - code-quality: -7 ~ -3 (CSS classes -8~15, no pixel impact)\n * - token-management: -5 ~ -4 (wrong input = wrong output, irregular spacing actively causes errors)\n * - interaction: -1 (uncalibrated — no metric to validate, kept minimal #210)\n * - semantic: -4 ~ -1 (non-semantic-name upgraded per interview — causes actual implementation errors)\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ── Pixel Critical ──\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.3,\n enabled: true,\n },\n \"non-layout-container\": {\n severity: \"blocking\",\n score: -8,\n depthWeight: 1.2,\n enabled: true,\n },\n\n // ── Responsive Critical ──\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"missing-size-constraint\": {\n severity: \"risk\",\n score: -8,\n enabled: true,\n },\n\n // ── Code Quality ──\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 2,\n structureMinRepetitions: 2,\n maxFingerprintDepth: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"variant-structure-mismatch\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -3,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n\n // ── Token Management ──\n \"raw-value\": {\n severity: \"missing-info\",\n score: -4,\n enabled: true,\n },\n \"irregular-spacing\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n options: {\n gridBase: 2,\n },\n },\n\n // ── Interaction ──\n \"missing-interaction-state\": {\n severity: \"suggestion\",\n score: -1, // uncalibrated: no metric to validate score (#210), kept at -1 to preserve category visibility\n enabled: true,\n },\n \"missing-prototype\": {\n severity: \"missing-info\",\n score: -3,\n enabled: false, // disabled: interactionDestinations data missing from fixtures (#139)\n },\n\n // ── Semantic ──\n \"non-standard-naming\": {\n severity: \"suggestion\",\n score: -3, // higher than other naming rules: non-standard state names break interaction detection pipeline\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on pixel-critical and responsive-critical issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category !== \"pixel-critical\" && category !== \"responsive-critical\") {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost pixel-critical and token-management rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category === \"pixel-critical\" || category === \"token-management\") {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Increase scores but respect disabled rules\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\n\n/**\n * Analysis issue with calculated score and metadata\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n}\n\n/**\n * Information about a rule that threw during analysis\n */\nexport interface RuleFailure {\n ruleId: string;\n nodeName: string;\n nodeId: string;\n error: string;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n failedRules: RuleFailure[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Fresh per-analysis state — eliminates module-level mutable state in rules\n const analysisState = new Map<string, unknown>();\n\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n const issues: AnalysisIssue[] = [];\n const failedRules: RuleFailure[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n failedRules,\n 0,\n [],\n [],\n 0,\n analysisState,\n undefined,\n undefined\n );\n\n return {\n file,\n issues,\n failedRules,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n failedRules: RuleFailure[],\n depth: number,\n path: string[],\n ancestorTypes: string[],\n componentDepth: number,\n analysisState: Map<string, unknown>,\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Reset componentDepth at component boundaries\n const isComponentBoundary = node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\" || node.type === \"INSTANCE\";\n const currentComponentDepth = isComponentBoundary ? 0 : componentDepth;\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n componentDepth: currentComponentDepth,\n maxDepth,\n path: nodePath,\n ancestorTypes,\n siblings,\n analysisState,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Track failure and continue — never let one rule break the whole analysis\n failedRules.push({\n ruleId,\n nodeName: node.name,\n nodeId: node.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n const childAncestorTypes = [...ancestorTypes, node.type];\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n failedRules,\n depth + 1,\n nodePath,\n childAncestorTypes,\n currentComponentDepth + 1,\n analysisState,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Get original image fill URLs by imageRef.\n * Returns a mapping of imageRef → download URL for all image fills in the file.\n */\n async getImageFills(fileKey: string): Promise<Record<string, string>> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}/images`;\n const response = await fetch(url, {\n headers: { \"X-Figma-Token\": this.token },\n });\n if (!response.ok) {\n const error = await response.text().catch(() => \"\");\n throw new FigmaClientError(\n `Failed to fetch image fills: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n const data = await response.json() as { meta?: { images?: Record<string, string> } };\n return data.meta?.images ?? {};\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size constraints (responsive)\n if (\"minWidth\" in node && typeof node.minWidth === \"number\") {\n base.minWidth = node.minWidth;\n }\n if (\"maxWidth\" in node && typeof node.maxWidth === \"number\") {\n base.maxWidth = node.maxWidth;\n }\n if (\"minHeight\" in node && typeof node.minHeight === \"number\") {\n base.minHeight = node.minHeight;\n }\n if (\"maxHeight\" in node && typeof node.maxHeight === \"number\") {\n base.maxHeight = node.maxHeight;\n }\n if (\"layoutGrow\" in node && node.layoutGrow !== undefined) {\n base.layoutGrow = node.layoutGrow as 0 | 1;\n }\n if (\"constraints\" in node && node.constraints) {\n base.constraints = node.constraints as AnalysisNode[\"constraints\"];\n }\n\n // Wrap (flex-wrap)\n if (\"layoutWrap\" in node && node.layoutWrap) {\n base.layoutWrap = node.layoutWrap as AnalysisNode[\"layoutWrap\"];\n }\n if (\"counterAxisSpacing\" in node && typeof node.counterAxisSpacing === \"number\") {\n base.counterAxisSpacing = node.counterAxisSpacing;\n }\n if (\"counterAxisAlignContent\" in node && node.counterAxisAlignContent) {\n base.counterAxisAlignContent =\n node.counterAxisAlignContent as AnalysisNode[\"counterAxisAlignContent\"];\n }\n\n // Grid layout (container)\n if (\"gridRowCount\" in node && typeof node.gridRowCount === \"number\") {\n base.gridRowCount = node.gridRowCount;\n }\n if (\"gridColumnCount\" in node && typeof node.gridColumnCount === \"number\") {\n base.gridColumnCount = node.gridColumnCount;\n }\n if (\"gridRowGap\" in node && typeof node.gridRowGap === \"number\") {\n base.gridRowGap = node.gridRowGap;\n }\n if (\"gridColumnGap\" in node && typeof node.gridColumnGap === \"number\") {\n base.gridColumnGap = node.gridColumnGap;\n }\n if (\"gridColumnsSizing\" in node && typeof node.gridColumnsSizing === \"string\") {\n base.gridColumnsSizing = node.gridColumnsSizing;\n }\n if (\"gridRowsSizing\" in node && typeof node.gridRowsSizing === \"string\") {\n base.gridRowsSizing = node.gridRowsSizing;\n }\n\n // Grid layout (child)\n if (\"gridChildHorizontalAlign\" in node && node.gridChildHorizontalAlign) {\n base.gridChildHorizontalAlign =\n node.gridChildHorizontalAlign as AnalysisNode[\"gridChildHorizontalAlign\"];\n }\n if (\"gridChildVerticalAlign\" in node && node.gridChildVerticalAlign) {\n base.gridChildVerticalAlign =\n node.gridChildVerticalAlign as AnalysisNode[\"gridChildVerticalAlign\"];\n }\n if (\"gridRowSpan\" in node && typeof node.gridRowSpan === \"number\") {\n base.gridRowSpan = node.gridRowSpan;\n }\n if (\"gridColumnSpan\" in node && typeof node.gridColumnSpan === \"number\") {\n base.gridColumnSpan = node.gridColumnSpan;\n }\n if (\"gridRowAnchorIndex\" in node && typeof node.gridRowAnchorIndex === \"number\") {\n base.gridRowAnchorIndex = node.gridRowAnchorIndex;\n }\n if (\"gridColumnAnchorIndex\" in node && typeof node.gridColumnAnchorIndex === \"number\") {\n base.gridColumnAnchorIndex = node.gridColumnAnchorIndex;\n }\n\n // Overflow / clip\n if (\"clipsContent\" in node && typeof node.clipsContent === \"boolean\") {\n base.clipsContent = node.clipsContent;\n }\n if (\"overflowDirection\" in node && node.overflowDirection) {\n base.overflowDirection =\n node.overflowDirection as AnalysisNode[\"overflowDirection\"];\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"strokeWeight\" in node && typeof node.strokeWeight === \"number\") {\n base.strokeWeight = node.strokeWeight;\n }\n if (\"individualStrokeWeights\" in node && node.individualStrokeWeights) {\n base.individualStrokeWeights = node.individualStrokeWeights as Record<string, number>;\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n if (\"cornerRadius\" in node && typeof node.cornerRadius === \"number\") {\n base.cornerRadius = node.cornerRadius;\n }\n if (\"opacity\" in node && typeof node.opacity === \"number\" && node.opacity < 1) {\n base.opacity = node.opacity;\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n if (\"textTruncation\" in node && (node.textTruncation === \"DISABLED\" || node.textTruncation === \"ENDING\")) {\n base.textTruncation = node.textTruncation;\n }\n if (\"maxLines\" in node && typeof node.maxLines === \"number\") {\n base.maxLines = node.maxLines;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Prototype interactions\n if (\"interactions\" in node && Array.isArray(node.interactions) && node.interactions.length > 0) {\n base.interactions = node.interactions;\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first)\n throw new Error(\n \"No nodes returned from Figma API — the node-id in the URL may be invalid or deleted. \" +\n \"Try selecting the frame in Figma and copying the link again.\"\n );\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\n/**\n * Transform component master nodes from a /v1/files/{key}/nodes response.\n * Each requested node ID is transformed into an AnalysisNode if present.\n */\nexport function transformComponentMasterNodes(\n response: GetFileNodesResponse,\n requestedIds: string[]\n): Record<string, AnalysisNode> {\n const result: Record<string, AnalysisNode> = {};\n for (const id of requestedIds) {\n const entry = response.nodes[id];\n if (entry?.document) {\n result[id] = transformNode(entry.document);\n }\n }\n return result;\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import type { FigmaClient } from \"./figma-client.js\";\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { transformComponentMasterNodes } from \"./figma-transformer.js\";\n\nconst BATCH_SIZE = 50;\n\n/**\n * Recursively collect all unique componentId values from INSTANCE nodes.\n */\nexport function collectComponentIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId) {\n ids.add(n.componentId);\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Recursively collect all unique interaction destination IDs from nodes.\n * These are the node IDs that interactions (e.g., ON_HOVER → CHANGE_TO) point to.\n */\nexport function collectInteractionDestinationIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.interactions && Array.isArray(n.interactions)) {\n for (const interaction of n.interactions) {\n const i = interaction as {\n trigger?: { type?: string };\n actions?: Array<{ destinationId?: string; navigation?: string }>;\n };\n if (i.trigger?.type === \"ON_HOVER\" && i.actions) {\n for (const action of i.actions) {\n if (action.navigation === \"CHANGE_TO\" && action.destinationId) {\n ids.add(action.destinationId);\n }\n }\n }\n }\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Resolve component master node trees via multi-pass fetching.\n *\n * Pass 1: collect component IDs from the document tree, fetch their masters.\n * Pass 2+: collect component IDs from fetched masters that were not in previous passes.\n * Repeats up to maxPasses (default 2).\n *\n * Batches API calls at BATCH_SIZE IDs per request.\n * Skips IDs that return null (e.g. external library components).\n */\nexport async function resolveComponentDefinitions(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n maxPasses = 2\n): Promise<Record<string, AnalysisNode>> {\n const allDefinitions: Record<string, AnalysisNode> = {};\n const resolvedIds = new Set<string>();\n\n // Pass 1: collect from the original document\n let pendingIds = collectComponentIds(document);\n\n for (let pass = 0; pass < maxPasses; pass++) {\n // Filter out already-resolved IDs\n const idsToFetch = [...pendingIds].filter((id) => !resolvedIds.has(id));\n if (idsToFetch.length === 0) break;\n\n // Fetch in batches\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDefinitions[id] = node;\n }\n } catch (err) {\n // Skip failed batches (e.g. external library components)\n console.debug(`[component-resolver] batch fetch failed (${batch.length} ids):`, err);\n }\n }\n\n // Mark all attempted IDs as resolved (even if they failed/returned null)\n for (const id of idsToFetch) {\n resolvedIds.add(id);\n }\n\n // Collect new IDs only from masters fetched in this pass (not all accumulated)\n pendingIds = new Set<string>();\n for (const id of idsToFetch) {\n const node = allDefinitions[id];\n if (node) {\n for (const nestedId of collectComponentIds(node)) {\n if (!resolvedIds.has(nestedId)) {\n pendingIds.add(nestedId);\n }\n }\n }\n }\n }\n\n return allDefinitions;\n}\n\n/**\n * Resolve interaction destination nodes (e.g., hover variants).\n *\n * Collects all destinationId values from interactions in the document,\n * excludes those already in componentDefinitions, and fetches them.\n */\nexport async function resolveInteractionDestinations(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n existingDefinitions?: Record<string, AnalysisNode>,\n): Promise<Record<string, AnalysisNode>> {\n const destIds = collectInteractionDestinationIds(document);\n if (destIds.size === 0) return {};\n\n const allDestinations: Record<string, AnalysisNode> = {};\n const idsToFetch: string[] = [];\n\n for (const id of destIds) {\n const existing = existingDefinitions?.[id];\n if (existing) {\n allDestinations[id] = existing;\n } else {\n idsToFetch.push(id);\n }\n }\n\n if (idsToFetch.length === 0) return allDestinations;\n\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDestinations[id] = node;\n }\n } catch (err) {\n console.debug(`[component-resolver] interaction destination fetch failed (${batch.length} ids):`, err);\n }\n }\n\n return allDestinations;\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n \"SLOT\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\", \"GRID\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\nexport const LayoutConstraintSchema = z.object({\n horizontal: z.enum([\"LEFT\", \"RIGHT\", \"CENTER\", \"LEFT_RIGHT\", \"SCALE\"]),\n vertical: z.enum([\"TOP\", \"BOTTOM\", \"CENTER\", \"TOP_BOTTOM\", \"SCALE\"]),\n});\nexport type LayoutConstraint = z.infer<typeof LayoutConstraintSchema>;\n\nexport const LayoutWrapSchema = z.enum([\"NO_WRAP\", \"WRAP\"]);\nexport type LayoutWrap = z.infer<typeof LayoutWrapSchema>;\n\nexport const OverflowDirectionSchema = z.enum([\n \"HORIZONTAL_SCROLLING\",\n \"VERTICAL_SCROLLING\",\n \"HORIZONTAL_AND_VERTICAL_SCROLLING\",\n \"NONE\",\n]);\nexport type OverflowDirection = z.infer<typeof OverflowDirectionSchema>;\n\nexport const GridChildAlignSchema = z.enum([\"AUTO\", \"MIN\", \"CENTER\", \"MAX\"]);\nexport type GridChildAlign = z.infer<typeof GridChildAlignSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size constraints (responsive)\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n layoutGrow: z.union([z.literal(0), z.literal(1)]).optional(),\n constraints: LayoutConstraintSchema.optional(),\n\n // Wrap (flex-wrap)\n layoutWrap: LayoutWrapSchema.optional(),\n counterAxisSpacing: z.number().optional(),\n counterAxisAlignContent: z.enum([\"AUTO\", \"SPACE_BETWEEN\"]).optional(),\n\n // Grid layout (container)\n gridRowCount: z.number().optional(),\n gridColumnCount: z.number().optional(),\n gridRowGap: z.number().optional(),\n gridColumnGap: z.number().optional(),\n gridColumnsSizing: z.string().optional(),\n gridRowsSizing: z.string().optional(),\n\n // Grid layout (child)\n gridChildHorizontalAlign: GridChildAlignSchema.optional(),\n gridChildVerticalAlign: GridChildAlignSchema.optional(),\n gridRowSpan: z.number().optional(),\n gridColumnSpan: z.number().optional(),\n gridRowAnchorIndex: z.number().optional(),\n gridColumnAnchorIndex: z.number().optional(),\n\n // Overflow / clip\n clipsContent: z.boolean().optional(),\n overflowDirection: OverflowDirectionSchema.optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n strokeWeight: z.number().optional(),\n individualStrokeWeights: z.record(z.string(), z.number()).optional(),\n effects: z.array(z.unknown()).optional(),\n cornerRadius: z.number().optional(),\n opacity: z.number().optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n textTruncation: z.enum([\"DISABLED\", \"ENDING\"]).optional(),\n maxLines: z.number().optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Prototype interactions\n interactions: z.array(z.unknown()).optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n sourceUrl: z.string().optional(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n componentDefinitions: z.record(z.string(), AnalysisNodeSchema).optional(),\n interactionDestinations: z.record(z.string(), AnalysisNodeSchema).optional(),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport { AnalysisNodeSchema } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Extract fileKey from fixture path.\n * - fixtures/name/data.json → name (directory-based fixture)\n * - fixtures/name.json → name (legacy flat fixture)\n */\nfunction extractFileKey(filePath: string): string {\n const fileName = basename(filePath, \".json\");\n if (fileName === \"data\") {\n // Directory-based fixture: use parent directory name\n return basename(dirname(filePath));\n }\n return fileName;\n}\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse & {\n componentDefinitions?: Record<string, unknown>;\n interactionDestinations?: Record<string, unknown>;\n };\n\n const fileKey = extractFileKey(filePath);\n\n const file = transformFigmaResponse(fileKey, data);\n\n // Preserve componentDefinitions from previously-saved fixtures\n if (data.componentDefinitions) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.componentDefinitions)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] componentDefinitions[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.componentDefinitions = parsed;\n }\n }\n\n // Preserve interactionDestinations from previously-saved fixtures\n if (data.interactionDestinations) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.interactionDestinations)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] interactionDestinations[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.interactionDestinations = parsed;\n }\n }\n\n return file;\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\n/**\n * Extract the commentable node ID from a potentially nested instance path.\n * Instance-internal IDs like \"I3010:7457;1442:7704\" use semicolons to\n * separate path segments. The Figma Comments API only accepts simple IDs\n * (e.g. \"3010:7457\"), so we take the first segment and strip the \"I\" prefix.\n */\nexport function toCommentableNodeId(nodeId: string): string {\n const firstSegment = nodeId.split(\";\")[0]!;\n return firstSegment.replace(/^I/, \"\");\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n // Strip instance-internal path to top-level node:\n // \"I175:7425;1442:7704\" → \"175:7425\" → \"175-7425\"\n const topNodeId = toCommentableNodeId(nodeId).replace(/:/g, \"-\");\n return `https://www.figma.com/design/${fileKey}?node-id=${topNodeId}`;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction hardenPermissions(path: string, mode: number): void {\n if (process.platform !== \"win32\") {\n chmodSync(path, mode);\n }\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n hardenPermissions(dir, 0o700);\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n hardenPermissions(CONFIG_PATH, 0o600);\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(AIREADY_DIR);\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { resolveComponentDefinitions, resolveInteractionDestinations } from \"../adapters/component-resolver.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\n/** Check if input string is a Figma URL. */\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\n/** Check if input string is a JSON file path. */\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\n/**\n * Check if input is a fixture directory (contains data.json).\n */\nexport function isFixtureDir(input: string): boolean {\n const resolved = resolve(input);\n if (!existsSync(resolved)) return false;\n try {\n if (!statSync(resolved).isDirectory()) return false;\n } catch {\n return false;\n }\n return existsSync(join(resolved, \"data.json\"));\n}\n\n/**\n * Resolve fixture input to data.json path.\n * Input: fixtures/name/ or fixtures/name → fixtures/name/data.json\n */\nexport function resolveFixturePath(input: string): string {\n if (isJsonFile(input)) return resolve(input);\n return resolve(join(input, \"data.json\"));\n}\n\n/**\n * Load a Figma file from a URL, JSON file, or fixture directory.\n * Resolves component master node trees for accurate analysis.\n */\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input) || isFixtureDir(input)) {\n const filePath = resolveFixturePath(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.error(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or fixture directory path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.error(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.error(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n const file = transformFileNodesResponse(fileKey, response);\n\n // Resolve component master node trees for accurate analysis\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n }\n\n const response = await client.getFile(fileKey);\n const file = transformFigmaResponse(fileKey, response);\n\n // Full file fetch may still miss component masters from external libraries\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.9.0\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"Score your Figma designs with AI-calibrated rules. CLI + MCP server.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"sync-docs\": \"tsx scripts/sync-rule-docs.ts\",\n \"clean\": \"rm -rf dist\"\n },\n \"files\": [\n \"dist\",\n \"docs/CUSTOMIZATION.md\",\n \".claude/skills/design-to-code/PROMPT.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"pnpm\": {\n \"overrides\": {\n \"picomatch\": \"4.0.4\",\n \"path-to-regexp\": \"8.4.0\"\n }\n },\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.80.0\",\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES, CATEGORY_LABELS } from \"../contracts/category.js\";\nimport type { RuleId, RuleConfig } from \"../contracts/rule.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { RULE_CONFIGS, RULE_ID_CATEGORY } from \"../rules/rule-config.js\";\nimport { version as VERSION } from \"../../../package.json\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Density weighting uses per-rule base |score| with sqrt damping (#226).\n *\n * Previously, each issue's |calculatedScore| was summed linearly — a rule\n * triggering N times contributed N× its score. This over-penalized designs\n * with many instances of the same issue (e.g., raw-value ×79 = -316 weight),\n * causing most real files to score Grade D/F with no differentiation.\n *\n * Now: same rule triggered N times contributes |score| × sqrt(N).\n * raw-value ×79 = 4 × sqrt(79) ≈ 36 instead of 316.\n * At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity.\n * At high counts the curve flattens — 79th occurrence adds ~0.2 vs 1st adding 4.\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n * Category importance is already encoded in rule scores (pixel-critical -10\n * vs semantic -4), so per-category weighting is unnecessary.\n */\n\n/**\n * Compute sum of |score| for all rules in each category from a given config map.\n * Used as denominator for severity-weighted diversity scoring.\n * Must use the same preset-adjusted config map that produced the analysis issues,\n * otherwise diversity ratios will be incorrect.\n */\nfunction computeTotalScorePerCategory(\n configs: Record<RuleId, RuleConfig>\n): Record<Category, number> {\n const totals = Object.fromEntries(\n CATEGORIES.map(c => [c, 0])\n ) as Record<Category, number>;\n\n for (const [id, config] of Object.entries(configs)) {\n const category = RULE_ID_CATEGORY[id as RuleId];\n if (category && config.enabled) {\n totals[category] += Math.abs(config.score);\n }\n }\n\n return totals;\n}\n\n/**\n * Score composition weights (initial intuition, pending calibration validation).\n *\n * Density (0.7): \"how many issues per node\" — measures issue volume relative to design size.\n * Designs with many issues per node are harder to implement accurately.\n *\n * Diversity (0.3): \"how many different rule types triggered\" — measures issue breadth.\n * A design that triggers 1 rule 50 times is easier to fix than one triggering 10 different rules.\n *\n * The 70:30 ratio prioritizes volume over variety. Rationale: a design with a single\n * systemic problem (e.g., all frames missing auto-layout) is still very hard to implement,\n * even though diversity is low. Density captures this; diversity adds a penalty for\n * designs with scattered, unrelated issues.\n *\n * Status: initial values. To be validated via /calibrate-loop against visual-compare results.\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor.\n * Even the worst design gets 5% instead of 0%. Rationale: a score of 0 implies\n * \"completely unimplementable\", but any Figma file with visible nodes provides\n * some structural information. The floor also avoids demoralizing UX — seeing 0%\n * feels like the tool failed, not that the design needs improvement.\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage.\n * Thresholds follow a 5-point interval pattern (95/90/85/80/75/70/65) with a wider\n * gap for D (50-64) and F (<50). This mirrors academic grading conventions where\n * the top tiers are tightly spaced and the failing range is broad.\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - weighted triggered rule scores / total category scores) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n *\n * @param result Analysis result with issues\n * @param configs Optional preset-adjusted config map used to produce the issues.\n * If not provided, diversity totals are reconstructed from issue.config values.\n */\nexport function calculateScores(\n result: AnalysisResult,\n configs?: Record<RuleId, RuleConfig>\n): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules and their base |score| per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n const ruleScorePerCategory = new Map<Category, Map<string, number>>();\n // Track issue counts per rule per category for sqrt damping (#226)\n const ruleIssueCountPerCategory = new Map<Category, Map<string, number>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n ruleScorePerCategory.set(category, new Map());\n ruleIssueCountPerCategory.set(category, new Map());\n }\n\n // Compute totals from the config map.\n // If configs provided: use preset-adjusted totals (recommended when using presets).\n // If not: fall back to static RULE_CONFIGS — only correct when issues were\n // produced with default RULE_CONFIGS, otherwise diversity ratios will be skewed.\n const totalScorePerCategory = computeTotalScorePerCategory(configs ?? RULE_CONFIGS);\n\n // Count issues by severity per category and track unique rules with scores\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n ruleScorePerCategory.get(category)!.set(ruleId, Math.abs(issue.config.score));\n // Accumulate per-rule issue count (using |calculatedScore| as weight unit)\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n ruleCountMap.set(ruleId, (ruleCountMap.get(ruleId) ?? 0) + 1);\n }\n\n // Compute weightedIssueCount with sqrt damping per rule (#226).\n // Same rule triggered N times contributes |score| × sqrt(N) instead of |score| × N.\n // Rationale: 79 raw-value issues represent one systemic problem, not 79× the difficulty.\n // First few occurrences identify the problem; subsequent ones have diminishing impact.\n // At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity for rare issues.\n for (const category of CATEGORIES) {\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const ruleScoreMap = ruleScorePerCategory.get(category)!;\n let dampedWeight = 0;\n for (const [ruleId, count] of ruleCountMap) {\n const ruleScore = ruleScoreMap.get(ruleId) ?? 0;\n dampedWeight += ruleScore * Math.sqrt(count);\n }\n categoryScores[category].weightedIssueCount = dampedWeight;\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: weighted by base rule |score| (config.score, not calculatedScore).\n // Uses base score intentionally — diversity measures \"what types of problems exist\",\n // not \"where they occur\". depthWeight affects density (volume penalty) but not diversity\n // (breadth penalty). A blocking rule (score -10) penalizes diversity more than a\n // suggestion (score -1), so low-severity-only designs correctly get high diversity scores.\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const ruleScores = ruleScorePerCategory.get(category)!;\n const weightedTriggered = Array.from(ruleScores.values()).reduce((sum, s) => sum + s, 0);\n const weightedTotal = totalScorePerCategory[category];\n const diversityRatio = weightedTotal > 0 ? weightedTriggered / weightedTotal : 0;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as simple average of categories\n // Category importance is already encoded in rule scores (weight baked in),\n // so no per-category weighting is needed.\n let categorySum = 0;\n for (const category of CATEGORIES) {\n categorySum += categoryScores[category].percentage;\n }\n\n const overallPercentage = CATEGORIES.length > 0\n ? Math.round(categorySum / CATEGORIES.length)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n lines.push(` Total: ${report.summary.totalIssues}`);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n return CATEGORY_LABELS[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: { fileKey?: string },\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n const issues = result.issues.map((issue) => ({\n ruleId: issue.violation.ruleId,\n ...(issue.violation.subType && { subType: issue.violation.subType }),\n severity: issue.config.severity,\n nodeId: issue.violation.nodeId,\n nodePath: issue.violation.nodePath,\n message: issue.violation.message,\n }));\n\n const json: Record<string, unknown> = {\n version: VERSION,\n analyzedAt: result.analyzedAt,\n ...(options?.fileKey && { fileKey: options.fileKey }),\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n issueCount: result.issues.length,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n issues,\n summary: formatScoreSummary(scores),\n };\n\n if (result.failedRules.length > 0) {\n json[\"failedRules\"] = result.failedRules;\n }\n\n return json;\n}","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n \"pixel-critical\":\n \"Auto Layout, absolute positioning, group usage — layout issues that directly affect pixel accuracy\",\n \"responsive-critical\":\n \"Fixed sizing, size constraints, responsive behavior — issues that break at different viewports\",\n \"code-quality\":\n \"Component reuse, detached instances, variant structure, nesting depth\",\n \"token-management\":\n \"Design token binding for colors, fonts, shadows, opacity, spacing grid\",\n \"interaction\":\n \"State variants for interactive components — hover, disabled, active, focus\",\n \"semantic\":\n \"Semantic layer names, naming conventions, default names\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n\n/** Severity to CSS modifier class (used with .rpt-dot, .rpt-issue-score) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Severity to CSS modifier class (used with .rpt-issue-score) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Score percentage to CSS modifier class (used with .rpt-badge) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"score-green\";\n if (pct >= 50) return \"score-amber\";\n return \"score-red\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${pct}</text>\n </svg>`;\n}\n","/**\n * Pure template functions for report HTML rendering.\n * No Node.js dependencies — usable in browser via CanICode.* globals.\n *\n * Single source of truth for all report UI:\n * - CLI: generateHtmlReport() wraps with <html> shell\n * - Web app: CanICode.renderReportBody() → innerHTML\n * - Figma plugin: CanICode.renderReportBody() → innerHTML\n *\n * Layout: category tabs → rule sections (static info) → node accordion (dynamic info)\n * Styled via self-contained CSS (app/shared/styles.css) — no Tailwind dependency.\n */\n\nimport type { Category } from \"../contracts/category.js\";\nimport type { AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { version as VERSION } from \"../../../package.json\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\n\n// ---- Data interface ----\n\nexport interface ReportData {\n fileName: string;\n fileKey: string;\n scores: ScoreReport;\n issues: AnalysisIssue[];\n nodeCount: number;\n maxDepth: number;\n figmaToken?: string;\n}\n\n/** Issues grouped by rule within a category */\ninterface RuleGroup {\n ruleId: string;\n ruleName: string;\n severity: string;\n severityClass: string;\n why: string;\n impact: string;\n fix: string;\n issues: AnalysisIssue[];\n totalScore: number;\n}\n\n// ---- Main render ----\n\n/**\n * Render the report body content (everything inside <main>).\n * Does NOT include <html>, <head>, <body> — caller wraps as needed.\n */\nexport function renderReportBody(data: ReportData): string {\n const { scores, issues, fileKey, figmaToken } = data;\n const issuesByCategory = groupIssuesByCategory(issues);\n const ruleOpportunities = getTopRules(issues, 5);\n\n return `\n <!-- Overall Score -->\n <section class=\"rpt-overall\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"rpt-score\">\n <span class=\"rpt-score-value\">${scores.overall.percentage}</span>\n <span class=\"rpt-score-max\">/ 100</span>\n </div>\n <p class=\"rpt-score-label\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"card rpt-gauges\">\n <div class=\"rpt-gauges-grid\">\n${CATEGORIES.map((cat) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" class=\"rpt-gauge-item\" data-tab=\"${cat}\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"rpt-gauge-label\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"rpt-gauge-count\">${cs.issueCount} issues</span>\n </button>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"card rpt-summary\">\n <div class=\"rpt-summary-inner\">\n ${renderSummaryDot(\"sev-blocking\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"sev-risk\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"sev-missing\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"sev-suggestion\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"rpt-summary-total\">\n <span class=\"rpt-summary-count\">${scores.summary.totalIssues}</span>\n <span class=\"rpt-summary-label\">Total</span>\n </div>\n </div>\n </section>\n\n${ruleOpportunities.length > 0 ? renderOpportunities(ruleOpportunities) : \"\"}\n\n <!-- Category Tabs -->\n <div class=\"rpt-tabs\">\n <div class=\"rpt-tab-list\" role=\"tablist\">\n${CATEGORIES.map((cat, i) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" role=\"tab\" class=\"rpt-tab${i === 0 ? \" active\" : \"\"}\" data-tab=\"${cat}\" aria-selected=\"${i === 0}\">${CATEGORY_LABELS[cat]} <span class=\"rpt-tab-count\">${cs.issueCount}</span></button>`;\n }).join(\"\\n\")}\n </div>\n\n${CATEGORIES.map((cat, i) => {\n const catIssues = issuesByCategory.get(cat) ?? [];\n const ruleGroups = groupIssuesByRule(catIssues);\n return ` <div class=\"rpt-tab-panel${i === 0 ? \" active\" : \"\"}\" data-panel=\"${cat}\" role=\"tabpanel\">\n${ruleGroups.length === 0\n ? ' <div class=\"rpt-cat-empty\">No issues found</div>'\n : ruleGroups.map(rg => renderRuleSection(rg, fileKey, figmaToken)).join(\"\\n\")\n}\n </div>`;\n }).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"rpt-footer\">\n <p class=\"rpt-footer-main\"><strong>CanICode</strong> <span style=\"opacity:0.5\">v${VERSION}</span></p>\n <p class=\"rpt-footer-meta\">${new Date().toLocaleString()} · ${data.nodeCount} nodes · Max depth ${data.maxDepth}</p>\n <p class=\"rpt-footer-links\"><a href=\"https://github.com/let-sunny/canicode/issues\" target=\"_blank\" rel=\"noopener\">Feedback</a> <span style=\"opacity:0.3\">&middot;</span> <a href=\"https://github.com/let-sunny/canicode/discussions/new?category=share-your-figma\" target=\"_blank\" rel=\"noopener\">Share your Figma</a></p>\n </footer>`;\n}\n\n// ---- Components ----\n\nexport function renderSummaryDot(sevClass: string, count: number, label: string): string {\n return `<div class=\"rpt-summary-item\">\n <span class=\"rpt-dot ${sevClass}\"></span>\n <span class=\"rpt-summary-count\">${count}</span>\n <span class=\"rpt-summary-label\">${label}</span>\n </div>`;\n}\n\nexport function renderOpportunities(ruleGroups: RuleGroup[]): string {\n const maxAbs = ruleGroups.reduce((m, rg) => Math.max(m, Math.abs(rg.totalScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"card rpt-opps\">\n <div class=\"rpt-opps-header\">\n <h2 class=\"rpt-opps-title\">\n <span class=\"rpt-dot sev-blocking\"></span>\n Opportunities\n </h2>\n <p class=\"rpt-opps-desc\">Top impact rules — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"rpt-opps-list\">\n${ruleGroups.map(rg => {\n const barW = Math.round((Math.abs(rg.totalScore) / maxAbs) * 100);\n const cat = rg.issues[0]?.rule.definition.category ?? \"\";\n return ` <div class=\"rpt-opps-item\" data-opp-rule=\"${esc(rg.ruleId)}\" data-opp-cat=\"${cat}\" style=\"cursor:pointer\">\n <div class=\"rpt-opps-info\">\n <div class=\"rpt-opps-name\">${esc(rg.ruleName)}</div>\n <div class=\"rpt-opps-msg\">${rg.issues.length} issues</div>\n </div>\n <div class=\"rpt-opps-bar-wrap\">\n <div class=\"rpt-opps-bar\">\n <div class=\"rpt-opps-bar-fill\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"rpt-opps-score\">${rg.totalScore}</span>\n </div>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nexport function renderRuleSection(\n rg: RuleGroup,\n fileKey: string,\n figmaToken?: string\n): string {\n const isOpen = rg.severity === \"blocking\" || rg.severity === \"risk\";\n return ` <details class=\"card rpt-rule\" data-rule=\"${esc(rg.ruleId)}\"${isOpen ? \" open\" : \"\"}>\n <summary class=\"rpt-rule-header\">\n <span class=\"rpt-badge score-red\">${rg.totalScore}</span>\n <span class=\"rpt-rule-title\">\n <span class=\"rpt-rule-name\">${esc(rg.ruleName)}</span>\n <span class=\"rpt-rule-meta\">\n <span class=\"rpt-dot-sm ${rg.severityClass}\"></span>\n ${esc(rg.severity)} · ${rg.issues.length} issues\n </span>\n <span class=\"rpt-rule-info\">\n <span class=\"rpt-rule-info-line\"><strong>Why:</strong> ${esc(rg.why)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Impact:</strong> ${esc(rg.impact)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Fix:</strong> ${esc(rg.fix)}</span>\n </span>\n </span>\n <svg class=\"rpt-rule-chevron no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"rpt-rule-issues\">\n${rg.issues.map(issue => renderIssueRow(issue, fileKey, figmaToken)).join(\"\\n\")}\n </div>\n </details>`;\n}\n\nexport function renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const v = issue.violation;\n const link = buildFigmaDeepLink(fileKey, v.nodeId);\n\n return ` <details class=\"rpt-issue\">\n <summary class=\"rpt-issue-header\">\n <span class=\"rpt-issue-msg\">${esc(v.message)}</span>\n <span class=\"rpt-issue-score ${severityBadge(sev)}\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"rpt-issue-body\">\n <div class=\"rpt-issue-suggestion\">${esc(v.suggestion)}</div>${v.guide ? `\n <div class=\"rpt-issue-guide\">${esc(v.guide)}</div>` : \"\"}\n <div class=\"rpt-issue-path\">${esc(v.nodePath)}</div>\n <div class=\"rpt-issue-actions no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" data-node-id=\"${esc(v.nodeId)}\" class=\"rpt-btn\">Go to node <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(v.nodeId)}\" data-message=\"${esc(v.message)} — ${esc(v.suggestion)}\" class=\"rpt-btn\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Interactions ----\n\n/**\n * Initialize tab switching + navigation for a rendered report.\n * Call after inserting renderReportBody() HTML into a container.\n * Uses 'any' to avoid DOM type dependency (this file targets Node.js).\n */\nexport function initReportInteractions(container: any): void {\n // Remove previous handler if re-initialized (e.g., re-analysis)\n if (container._rptHandler) {\n container.removeEventListener(\"click\", container._rptHandler);\n }\n function activate(cat: string, scrollTo: boolean) {\n container.querySelectorAll(\".rpt-tab\").forEach((t: any) => {\n const active = t.dataset.tab === cat;\n t.classList.toggle(\"active\", active);\n t.setAttribute(\"aria-selected\", String(active));\n });\n container.querySelectorAll(\".rpt-tab-panel\").forEach((p: any) => {\n p.classList.toggle(\"active\", p.dataset.panel === cat);\n });\n if (scrollTo) {\n const tabList = container.querySelector(\".rpt-tab-list\");\n if (tabList) tabList.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n }\n }\n function focusRule(ruleId: string) {\n const el = container.querySelector('[data-rule=\"' + ruleId + '\"]');\n if (el) {\n el.open = true;\n setTimeout(() => el.scrollIntoView({ behavior: \"smooth\", block: \"start\" }), 50);\n }\n }\n const handler = (e: any) => {\n const tab = e.target.closest(\"[data-tab]\");\n if (tab) {\n const isGauge = tab.classList.contains(\"rpt-gauge-item\");\n activate(tab.dataset.tab ?? \"\", isGauge);\n return;\n }\n const opp = e.target.closest(\"[data-opp-rule]\");\n if (opp) {\n const cat = opp.dataset.oppCat ?? \"\";\n const rule = opp.dataset.oppRule ?? \"\";\n if (cat) activate(cat, false);\n setTimeout(() => focusRule(rule), 50);\n }\n };\n container._rptHandler = handler;\n container.addEventListener(\"click\", handler);\n}\n\n// ---- Utils ----\n\n/** Get top N rules by total score impact */\nfunction getTopRules(issues: AnalysisIssue[], limit: number): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n return [...byRule.values()]\n .sort((a, b) => a.totalScore - b.totalScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\n/** Group issues by rule within a category, sorted by severity then score */\nfunction groupIssuesByRule(issues: AnalysisIssue[]): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n\n const SEVERITY_RANK: Record<string, number> = { blocking: 0, risk: 1, \"missing-info\": 2, suggestion: 3 };\n return [...byRule.values()].sort((a, b) => {\n const sevDiff = (SEVERITY_RANK[a.severity] ?? 4) - (SEVERITY_RANK[b.severity] ?? 4);\n return sevDiff !== 0 ? sevDiff : a.totalScore - b.totalScore;\n });\n}\n\nconst esc = escapeHtml;\n","// Report HTML module — full page generation for CLI\n// Rendering logic lives in render.ts (shared with web/plugin)\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { AnalysisResult } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { escapeHtml } from \"../ui-helpers.js\";\nimport { renderReportBody, initReportInteractions } from \"./render.js\";\nimport type { ReportData } from \"./render.js\";\n\ndeclare const __REPORT_CSS__: string;\nconst reportCss: string = __REPORT_CSS__;\n\nexport type { ReportData } from \"./render.js\";\nexport { renderReportBody, initReportInteractions } from \"./render.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\nconst esc = escapeHtml;\n\n/**\n * Generate a complete standalone HTML report page.\n * Used by CLI — opens in browser.\n */\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const figmaToken = options?.figmaToken;\n\n const data: ReportData = {\n fileName: file.name,\n fileKey: file.fileKey,\n scores,\n issues: result.issues,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n ...(figmaToken && { figmaToken }),\n };\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <style>\n${reportCss}\n .cli-topbar {\n background: #09090b; color: white;\n border-bottom: 1px solid #27272a;\n }\n .cli-topbar-inner {\n max-width: 960px; margin: 0 auto;\n padding: 12px 24px;\n display: flex; align-items: center; gap: 16px;\n }\n .cli-topbar-logo { font-weight: 600; font-size: 14px; letter-spacing: -0.01em; }\n .cli-topbar-file { color: #a1a1aa; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .cli-topbar-date { margin-left: auto; color: #71717a; font-size: 12px; }\n .cli-main { max-width: 960px; margin: 0 auto; padding: 0 24px 64px; }\n @media print {\n .cli-topbar { position: static !important; background: white !important; color: var(--fg) !important; }\n .cli-topbar-file { color: var(--fg-muted) !important; }\n }\n </style>\n</head>\n<body>\n\n <!-- Top Bar -->\n <header class=\"cli-topbar\">\n <div class=\"cli-topbar-inner\">\n <span class=\"cli-topbar-logo\">CanICode</span>\n <span class=\"cli-topbar-file\">${esc(file.name)}</span>\n <span class=\"cli-topbar-date no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"cli-main\">\n${renderReportBody(data)}\n </main>\n\n <script>(${String(initReportInteractions)})(document.querySelector('.cli-main'));</script>\n${figmaToken ? renderFigmaCommentScript(figmaToken) : \"\"}\n</body>\n</html>`;\n}\n\nfunction renderFigmaCommentScript(figmaToken: string): string {\n return ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const commentNodeId = nodeId.split(';')[0].replace(/^I/, '');\n const message = btn.dataset.message;\n const commentBody = '[CanICode] ' + message;\n btn.disabled = true;\n btn.textContent = 'Sending...';\n btn.title = '';\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: commentNodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) {\n const errBody = await res.text().catch(() => '');\n const errMsg = res.status === 400 ? 'Bad request' : res.status === 403 ? 'Token lacks file access' : res.status === 404 ? 'File not found' : res.status === 429 ? 'Rate limited' : 'HTTP ' + res.status;\n throw new Error(errMsg + (errBody ? ': ' + errBody.slice(0, 100) : ''));\n }\n btn.textContent = 'Sent';\n btn.classList.remove('rpt-btn-fail');\n btn.classList.add('rpt-btn-ok');\n } catch (e) {\n btn.textContent = 'Failed';\n btn.title = e.message || String(e);\n btn.classList.remove('rpt-btn-ok');\n btn.classList.add('rpt-btn-fail');\n btn.disabled = false;\n }\n }\n </script>`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../contracts/severity.js\";\nimport type { RuleConfig } from \"../contracts/rule.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\nconst VALID_RULE_IDS = new Set(Object.keys(RULE_CONFIGS));\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n rules: z.record(z.string(), RuleOverrideSchema)\n .superRefine((rules, ctx) => {\n const unknown = Object.keys(rules).filter((id) => !VALID_RULE_IDS.has(id));\n if (unknown.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unknown rule ID(s): ${unknown.join(\", \")}. Valid IDs: ${[...VALID_RULE_IDS].join(\", \")}`,\n });\n }\n })\n .optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","/**\n * Centralized node semantic classification.\n * All \"what is this node?\" logic lives here so rules share the same predicates.\n *\n * Categories:\n * - Container: layout containers (frame, group, component, instance)\n * - Visual: decorative/graphic elements (vector, shape, image)\n * - Interactive: user-interactable elements (button, link, tab, input, toggle)\n * - Overlay: elements that open on top (modal, drawer, dropdown)\n * - Carousel: elements that slide/swipe (carousel, slider, gallery)\n * - Token: style/variable binding checks\n * - Naming: name pattern classification\n */\n\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n// ── Container classification ─────────────────────────────────────────────────\n\nexport function isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\" || node.type === \"INSTANCE\";\n}\n\nexport function hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nexport function hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\nexport function hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ── Visual classification ────────────────────────────────────────────────────\n\nconst VISUAL_LEAF_TYPES = new Set([\n \"VECTOR\", \"BOOLEAN_OPERATION\", \"ELLIPSE\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\", \"RECTANGLE\",\n]);\n\nexport function isVisualLeafType(type: string): boolean {\n return VISUAL_LEAF_TYPES.has(type);\n}\n\nexport function hasImageFill(node: AnalysisNode): boolean {\n if (!Array.isArray(node.fills)) return false;\n return node.fills.some(\n (fill) =>\n typeof fill === \"object\" &&\n fill !== null &&\n (fill as { type?: unknown }).type === \"IMAGE\",\n );\n}\n\nexport function isVisualOnlyNode(node: AnalysisNode): boolean {\n if (VISUAL_LEAF_TYPES.has(node.type)) return true;\n const hasOnlyVisualChildren =\n node.children !== undefined &&\n node.children.length > 0 &&\n node.children.every((c) => VISUAL_LEAF_TYPES.has(c.type));\n // Image fill only counts as visual-only when there are no content children\n if (hasImageFill(node) && (!node.children || node.children.length === 0 || hasOnlyVisualChildren)) {\n return true;\n }\n if (hasOnlyVisualChildren) return true;\n return false;\n}\n\n// ── Interactive classification ───────────────────────────────────────────────\n\nexport type StatefulComponentType = \"button\" | \"link\" | \"tab\" | \"input\" | \"toggle\";\n\n/** Name patterns → interactive type mapping */\nexport const STATEFUL_PATTERNS: Array<{ pattern: RegExp; type: StatefulComponentType }> = [\n { pattern: /\\b(btn|button|cta)\\b/i, type: \"button\" },\n { pattern: /\\b(link|anchor)\\b/i, type: \"link\" },\n { pattern: /\\b(tab|tabs)\\b/i, type: \"tab\" },\n { pattern: /\\b(nav|navigation|menu|navbar)\\b/i, type: \"tab\" },\n { pattern: /\\b(input|text-?field|search-?bar|textarea)\\b/i, type: \"input\" },\n { pattern: /\\b(select|dropdown|combo-?box)\\b/i, type: \"input\" },\n { pattern: /\\b(toggle|switch|checkbox|radio)\\b/i, type: \"toggle\" },\n];\n\nexport function getStatefulComponentType(node: AnalysisNode): StatefulComponentType | null {\n if (!node.name) return null;\n for (const entry of STATEFUL_PATTERNS) {\n if (entry.pattern.test(node.name)) return entry.type;\n }\n return null;\n}\n\nexport function isStatefulComponent(node: AnalysisNode): boolean {\n return getStatefulComponentType(node) !== null;\n}\n\n/**\n * Standard state names across web + mobile platforms.\n * Used by missing-interaction-state (to detect presence) and\n * non-standard-naming (to flag non-standard names).\n *\n * Sources:\n * - CSS: :hover, :active, :focus, :disabled, :enabled — https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes\n * - Material Design 3: Hovered, Focused, Pressed, Dragged — https://m3.material.io/foundations/interaction/states\n * - UIKit: highlighted, selected, disabled, focused — https://developer.apple.com/documentation/uikit/uicontrol/state\n */\nexport const STANDARD_STATE_NAMES = new Set([\n // CSS pseudo-classes (web)\n \"default\", \"hover\", \"active\", \"focus\", \"focused\", \"disabled\", \"enabled\",\n // Material Design 3 (Android)\n \"pressed\", \"dragged\",\n // UIKit (iOS)\n \"highlighted\",\n // Common\n \"selected\",\n]);\n\n/**\n * Patterns that look like state names but aren't in the standard set.\n * Maps common non-standard names to their standard equivalent for suggestions.\n */\nexport const STATE_NAME_SUGGESTIONS: Record<string, string> = {\n on: \"active\",\n off: \"default\",\n clicked: \"pressed\",\n tapped: \"pressed\",\n inactive: \"disabled\",\n normal: \"default\",\n rest: \"default\",\n hovered: \"hover\",\n activated: \"active\",\n checked: \"selected\",\n unchecked: \"default\",\n};\n\n/** Pattern to detect state-like variant option names (broad match) */\nexport const STATE_LIKE_PATTERN = /\\b(on|off|clicked|tapped|inactive|normal|rest|hovered|activated|checked|unchecked)\\b/i;\n\n// ── Overlay / Carousel patterns ──────────────────────────────────────────────\n\n/** Elements that open on top of current view */\nexport const OVERLAY_PATTERN = /\\b(dropdown|select|combo-?box|popover|accordion|drawer|modal|bottom-?sheet|sheet|sidebar|panel|dialog|popup|toast)\\b/i;\n\n/** Elements that swipe/slide between items */\nexport const CAROUSEL_PATTERN = /\\b(carousel|slider|swiper|slide-?show|gallery)\\b/i;\n\nexport function isOverlayNode(node: AnalysisNode): boolean {\n return node.name !== undefined && OVERLAY_PATTERN.test(node.name);\n}\n\nexport function isCarouselNode(node: AnalysisNode): boolean {\n return node.name !== undefined && CAROUSEL_PATTERN.test(node.name);\n}\n\n// ── Token classification ─────────────────────────────────────────────────────\n\nexport function hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nexport function hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\n// ── Naming patterns ──────────────────────────────────────────────────────────\n\n/** Figma default name patterns (Frame 1, Group 2, etc.) */\nexport const DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nexport function isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\n/** Shape-only non-semantic names */\nexport const NON_SEMANTIC_NAMES = [\n \"rectangle\", \"ellipse\", \"vector\", \"line\", \"polygon\",\n \"star\", \"path\", \"shape\", \"image\", \"fill\", \"stroke\",\n];\n\nexport function isNonSemanticName(name: string): boolean {\n return NON_SEMANTIC_NAMES.includes(name.toLowerCase().trim());\n}\n\n// ── Exclusion ────────────────────────────────────────────────────────────────\n\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport type { RuleContext } from \"../contracts/rule.js\";\nimport { isVisualLeafType, isVisualOnlyNode, isExcludedName } from \"./node-semantics.js\";\n\n// ============================================\n// Auto-layout exceptions\n// ============================================\n\n/** Frames that don't need auto-layout (only visual-leaf children like icon paths) */\nexport function isAutoLayoutExempt(node: AnalysisNode): boolean {\n if (\n node.children &&\n node.children.length > 0 &&\n node.children.every((c) => isVisualLeafType(c.type))\n ) return true;\n\n return false;\n}\n\n// ============================================\n// Absolute-position exceptions\n// ============================================\n\n/** Nodes that are allowed to use absolute positioning inside auto-layout */\nexport function isAbsolutePositionExempt(node: AnalysisNode): boolean {\n if (isVisualOnlyNode(node)) return true;\n\n // Intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n\n// ============================================\n// Size-constraint exceptions\n// ============================================\n\n/** Nodes that don't need maxWidth even with FILL sizing */\nexport function isSizeConstraintExempt(node: AnalysisNode, context: RuleContext): boolean {\n // Already has maxWidth\n if (node.maxWidth !== undefined) return true;\n\n // Parent already has maxWidth — parent constrains the stretch\n if (context.parent?.maxWidth !== undefined) return true;\n\n // Root-level frames — they represent the screen itself\n if (context.depth <= 1) return true;\n\n return false;\n}\n\n// ============================================\n// Fixed-size exceptions\n// ============================================\n\n/** Nodes that are allowed to use fixed sizing inside auto-layout */\nexport function isFixedSizeExempt(node: AnalysisNode): boolean {\n // Visual-only nodes (icons, images, shapes) — intentionally fixed\n if (isVisualOnlyNode(node)) return true;\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n","/**\n * Centralized rule violation messages.\n * All message text lives here so CLI, web, plugin, and MCP share the same strings.\n *\n * Each message function returns { message, suggestion, guide? }:\n * - message: what's wrong (node-specific, dynamic)\n * - suggestion: how to fix it (node-specific, dynamic)\n * - guide: exemption hint (optional, when the rule auto-excludes certain cases)\n */\n\n// ── Message return type ─────────────────────────────────────────────────────\n\nexport interface ViolationMsg {\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n// ── Sub-type definitions ─────────────────────────────────────────────────────\n\nexport type RawValueSubType = \"color\" | \"font\" | \"shadow\" | \"opacity\" | \"spacing\";\nexport type NoAutoLayoutSubType = \"overlapping\" | \"nested\" | \"basic\";\nexport type FixedSizeSubType = \"both-axes\" | \"horizontal\";\nexport type MissingComponentSubType = \"unused-component\" | \"name-repetition\" | \"structure-repetition\" | \"style-override\";\n\n// ── raw-value ────────────────────────────────────────────────────────────────\n\nexport const rawValueMsg = {\n color: (name: string, hex: string): ViolationMsg => ({\n message: `\"${name}\" uses raw fill color ${hex} without style or variable`,\n suggestion: `Bind to a color token`,\n }),\n font: (name: string, fontDesc: string): ViolationMsg => ({\n message: `\"${name}\" uses raw font${fontDesc} without text style`,\n suggestion: `Apply a text style`,\n }),\n shadow: (name: string, shadowType: string, details: string): ViolationMsg => ({\n message: `\"${name}\" has ${shadowType}${details} without effect style`,\n suggestion: `Apply an effect style`,\n }),\n opacity: (name: string, pct: number): ViolationMsg => ({\n message: `\"${name}\" uses raw opacity (${pct}%) without a variable binding`,\n suggestion: `Bind opacity to a variable`,\n }),\n spacing: (name: string, label: string, value: number): ViolationMsg => ({\n message: `\"${name}\" uses raw ${label} (${value}px) without a variable binding`,\n suggestion: `Bind spacing to a variable`,\n }),\n};\n\n// ── irregular-spacing ────────────────────────────────────────────────────────\n\nexport type IrregularSpacingSubType = \"padding\" | \"gap\";\n\nexport const irregularSpacingMsg = (name: string, spacing: number, gridBase: number, nearest: number): ViolationMsg => ({\n message: `\"${name}\" has spacing ${spacing}px not on ${gridBase}pt grid`,\n suggestion: `Round to nearest ${gridBase}pt multiple (${nearest}px)`,\n});\n\n// ── no-auto-layout ───────────────────────────────────────────────────────────\n\nexport const noAutoLayoutMsg = {\n overlapping: (name: string): ViolationMsg => ({\n message: `\"${name}\" has overlapping children without Auto Layout`,\n suggestion: `Apply auto-layout to separate overlapping children`,\n guide: `If this is an intentional overlay (e.g., badge on avatar), this can be ignored`,\n }),\n nested: (name: string): ViolationMsg => ({\n message: `\"${name}\" has nested containers without layout hints`,\n suggestion: `Apply auto-layout to organize nested containers`,\n guide: `Icon wrappers containing only vectors are automatically excluded`,\n }),\n basic: (name: string, arrangement: string, directionHint: string): ViolationMsg => ({\n message: `Frame \"${name}\" has no auto-layout${arrangement}`,\n suggestion: directionHint ? `Apply ${directionHint} auto-layout` : `Apply auto-layout`,\n guide: `Single-child wrappers and icon containers are automatically excluded`,\n }),\n};\n\n// ── absolute-position-in-auto-layout ─────────────────────────────────────────\n\nexport const absolutePositionMsg = (name: string, parentName: string): ViolationMsg => ({\n message: `\"${name}\" uses absolute positioning inside Auto Layout parent \"${parentName}\"`,\n suggestion: `Remove absolute positioning or restructure outside the auto-layout parent`,\n guide: `If this is a badge or overlay, name it with \"badge\", \"overlay\", or \"icon\" to auto-exclude`,\n});\n\n// ── fixed-size-in-auto-layout ────────────────────────────────────────────────\n\nexport const fixedSizeMsg = {\n bothAxes: (name: string, width: number, height: number): ViolationMsg => ({\n message: `Container \"${name}\" (${width}×${height}) uses fixed size on both axes inside auto-layout`,\n suggestion: `Set at least one axis to HUG or FILL`,\n }),\n horizontal: (name: string, width: number): ViolationMsg => ({\n message: `\"${name}\" has fixed width (${width}px) inside auto-layout`,\n suggestion: `Set horizontal sizing to FILL`,\n }),\n};\n\n// ── missing-size-constraint ──────────────────────────────────────────────────\n\nexport type MissingSizeConstraintSubType = \"max-width\" | \"min-width\" | \"wrap\" | \"grid\";\n\nexport const missingSizeConstraintMsg = {\n maxWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without max-width`,\n suggestion: `Add maxWidth to prevent stretching on large screens`,\n }),\n minWidth: (name: string, currentWidth: string): ViolationMsg => ({\n message: `\"${name}\" uses FILL width (currently ${currentWidth}) without min-width`,\n suggestion: `Add minWidth to prevent collapsing on small screens`,\n }),\n wrap: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a wrap container without min-width`,\n suggestion: `Add minWidth to control when wrapping occurs`,\n }),\n grid: (name: string): ViolationMsg => ({\n message: `\"${name}\" is in a grid layout without size constraints`,\n suggestion: `Add min/max-width for proper column sizing`,\n }),\n};\n\n// ── non-layout-container (was group-usage) ───────────────────────────────────\n\nexport type NonLayoutContainerSubType = \"group\" | \"section\";\n\nexport const nonLayoutContainerMsg = {\n group: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Group`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n section: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Section used as layout container`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n};\n\n// ── deep-nesting ─────────────────────────────────────────────────────────────\n\nexport const deepNestingMsg = (name: string, depth: number, maxDepth: number): ViolationMsg => ({\n message: `\"${name}\" is nested ${depth} levels deep within its component (max: ${maxDepth})`,\n suggestion: `Extract into a sub-component to reduce depth`,\n});\n\n// ── missing-component ────────────────────────────────────────────────────────\n\nexport const missingComponentMsg = {\n unusedComponent: (componentName: string, count: number): ViolationMsg => ({\n message: `Component \"${componentName}\" exists but ${count} repeated frames found instead of instances`,\n suggestion: `Replace frames with component instances`,\n }),\n nameRepetition: (name: string, count: number): ViolationMsg => ({\n message: `\"${name}\" appears ${count} times`,\n suggestion: `Extract as a reusable component`,\n }),\n structureRepetition: (name: string, siblingCount: number): ViolationMsg => ({\n message: `\"${name}\" and ${siblingCount} sibling frame(s) share the same internal structure`,\n suggestion: `Extract a shared component from the repeated structure`,\n }),\n styleOverride: (componentName: string, overrides: string[]): ViolationMsg => ({\n message: `\"${componentName}\" instance has style overrides (${overrides.join(\", \")})`,\n suggestion: `Create a new variant for this style combination`,\n }),\n};\n\n// ── detached-instance ────────────────────────────────────────────────────────\n\nexport const detachedInstanceMsg = (name: string, componentName: string): ViolationMsg => ({\n message: `\"${name}\" may be a detached instance of component \"${componentName}\"`,\n suggestion: `Restore as an instance of \"${componentName}\" or create a new variant`,\n});\n\n// ── variant-structure-mismatch ───────────────────────────────────────────────\n\nexport const variantStructureMismatchMsg = (name: string, mismatchCount: number, totalVariants: number): ViolationMsg => ({\n message: `\"${name}\" has ${mismatchCount}/${totalVariants} variants with different child structures`,\n suggestion: `Unify variant structures using visibility toggles for optional elements`,\n});\n\n// ── non-standard-naming ──────────────────────────────────────────────────────\n\nexport type NonStandardNamingSubType = \"state-name\";\n\nexport const nonStandardNamingMsg = {\n stateName: (name: string, nonStandard: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" has non-standard state name \"${nonStandard}\"`,\n suggestion: `Use \"${suggested}\" for dev-friendly naming`,\n }),\n};\n\n// ── non-semantic-name (merged: default-name + non-semantic-name) ─────────────\n\nexport type NonSemanticNameSubType = \"frame\" | \"group\" | \"vector\" | \"shape\" | \"text\" | \"image\" | \"component\" | \"instance\" | \"shape-name\";\n\nconst DEFAULT_NAME_SUBTYPE_MAP: Record<string, NonSemanticNameSubType> = {\n FRAME: \"frame\",\n GROUP: \"group\",\n RECTANGLE: \"shape\",\n ELLIPSE: \"shape\",\n VECTOR: \"vector\",\n LINE: \"vector\",\n STAR: \"shape\",\n REGULAR_POLYGON: \"shape\",\n TEXT: \"text\",\n IMAGE: \"image\",\n COMPONENT: \"component\",\n COMPONENT_SET: \"component\",\n INSTANCE: \"instance\",\n};\n\nexport function getDefaultNameSubType(nodeType: string): NonSemanticNameSubType {\n return DEFAULT_NAME_SUBTYPE_MAP[nodeType] ?? \"frame\";\n}\n\nconst NON_SEMANTIC_EXAMPLES: Record<string, string> = {\n FRAME: '\"Header\", \"ProductCard\", \"Sidebar\"',\n GROUP: '\"NavItems\", \"ButtonGroup\", \"CardContent\"',\n VECTOR: '\"ArrowIcon\", \"CheckMark\", \"LogoSymbol\"',\n LINE: '\"Divider\", \"Separator\", \"Underline\"',\n RECTANGLE: '\"Background\", \"Divider\", \"Overlay\"',\n ELLIPSE: '\"AvatarShape\", \"StatusDot\", \"Badge\"',\n STAR: '\"RatingIcon\", \"FavoriteIcon\", \"StarBadge\"',\n REGULAR_POLYGON: '\"PlayIcon\", \"WarningIcon\", \"ShapeDecor\"',\n TEXT: '\"PageTitle\", \"Description\", \"Price\"',\n IMAGE: '\"Avatar\", \"ProductPhoto\", \"Banner\"',\n COMPONENT: '\"PrimaryButton\", \"InputField\", \"CardTemplate\"',\n COMPONENT_SET: '\"Button\", \"Input\", \"Card\"',\n INSTANCE: '\"CloseButton\", \"UserAvatar\", \"StarIcon\"',\n};\n\nexport const nonSemanticNameMsg = (type: string, name: string): ViolationMsg => {\n const examples = NON_SEMANTIC_EXAMPLES[type] ?? '\"Header\", \"ProductCard\", \"Icon\"';\n return {\n message: `${type} \"${name}\" is a non-semantic name`,\n suggestion: `Rename to describe its role (e.g., ${examples})`,\n };\n};\n\n// ── missing-interaction-state ─────────────────────────────────────────────────\n\nexport type MissingInteractionStateSubType = \"hover\" | \"disabled\" | \"active\" | \"focus\";\n\nexport const missingInteractionStateMsg = {\n hover: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Hover state variant`,\n suggestion: `Add a State=Hover variant`,\n }),\n disabled: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Disabled state variant`,\n suggestion: `Add a State=Disabled variant`,\n }),\n active: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Active state variant`,\n suggestion: `Add a State=Active variant`,\n }),\n focus: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Focus state variant`,\n suggestion: `Add a State=Focus variant`,\n }),\n};\n\n// ── missing-prototype ─────────────────────────────────────────────────────────\n\nexport type MissingPrototypeSubType = \"button\" | \"navigation\" | \"tab\" | \"overlay\" | \"carousel\" | \"input\" | \"toggle\";\n\nexport const missingPrototypeMsg = {\n button: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a button but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the click behavior`,\n }),\n navigation: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a navigation link but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the destination`,\n }),\n tab: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a tab but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define tab switching behavior`,\n }),\n overlay: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an overlay trigger but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define open/close behavior`,\n }),\n carousel: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a carousel but has no interaction prototype`,\n suggestion: `Add an ON_CLICK or ON_DRAG interaction to define slide navigation`,\n }),\n input: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an input but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define focus/interaction behavior`,\n }),\n toggle: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a toggle but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define on/off behavior`,\n }),\n};\n\n// ── inconsistent-naming-convention ───────────────────────────────────────────\n\nexport const inconsistentNamingMsg = (name: string, nodeConvention: string, dominantConvention: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n suggestion: `Rename to \"${suggested}\"`,\n guide: `This checks sibling layers at the same level — you don't have to follow the exact suggestion, just keep naming consistent across siblings`,\n});\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isAutoLayoutExempt, isAbsolutePositionExempt, isSizeConstraintExempt, isFixedSizeExempt } from \"../rule-exceptions.js\";\nimport { noAutoLayoutMsg, absolutePositionMsg, fixedSizeMsg, missingSizeConstraintMsg, nonLayoutContainerMsg, deepNestingMsg } from \"../rule-messages.js\";\nimport { isContainerNode, hasAutoLayout, hasTextContent, hasOverlappingBounds } from \"../node-semantics.js\";\n\n// ============================================\n// no-auto-layout (merged: absorbs ambiguous-structure + missing-layout-hint)\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"pixel-critical\",\n why: \"Without Auto Layout, AI must guess positioning from absolute coordinates instead of reading explicit layout rules\",\n impact: \"Generated code uses hardcoded positions that break on any content or screen size change\",\n fix: \"Apply Auto Layout to create clear, explicit structure — enables AI to generate flexbox/grid instead of absolute positioning\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n if (isAutoLayoutExempt(node)) return null;\n\n // Priority 1: Check for overlapping visible children (ambiguous-structure)\n if (node.children.length >= 2) {\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n if (!childA || !childB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"overlapping\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.overlapping(node.name),\n };\n }\n }\n }\n }\n }\n\n // Priority 2: Check for nested containers without layout hints (missing-layout-hint)\n if (node.children.length >= 2) {\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n if (withoutLayout.length >= 2) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"nested\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.nested(node.name),\n };\n }\n }\n }\n\n // Priority 3: Basic no-auto-layout check (FRAME only)\n if (node.type !== \"FRAME\") return null;\n\n const childCount = node.children?.length ?? 0;\n let directionHint = \"\";\n if (node.children && node.children.length >= 2) {\n const boxes = node.children.filter(c => c.absoluteBoundingBox).map(c => c.absoluteBoundingBox!);\n if (boxes.length >= 2) {\n const yRange = Math.max(...boxes.map(b => b.y)) - Math.min(...boxes.map(b => b.y));\n const xRange = Math.max(...boxes.map(b => b.x)) - Math.min(...boxes.map(b => b.x));\n directionHint = yRange > xRange ? \"VERTICAL\" : \"HORIZONTAL\";\n }\n }\n\n const arrangement = directionHint\n ? ` (${childCount} children arranged ${directionHint.toLowerCase()}ly)`\n : childCount > 0 ? ` (${childCount} children)` : \"\";\n\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"basic\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.basic(node.name, arrangement, directionHint),\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"pixel-critical\",\n why: \"Absolute positioning inside Auto Layout contradicts the parent's layout rules — AI sees conflicting instructions\",\n impact: \"AI must decide whether to follow the parent's flexbox or the child's absolute position — often gets it wrong\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n if (isAbsolutePositionExempt(node)) return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...absolutePositionMsg(node.name, context.parent.name),\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout (merged: absorbs fixed-width-in-responsive-context)\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"responsive-critical\",\n why: \"Fixed sizing inside Auto Layout contradicts the flexible layout intent\",\n impact: \"AI generates a rigid element inside a flex container — the layout won't respond to content changes\",\n fix: \"Use 'Hug' or 'Fill' for at least one axis. Both-axes FIXED → layout completely rigid; horizontal-only FIXED → width won't adapt to parent resize\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n if (isFixedSizeExempt(node)) return null;\n\n const { width, height } = node.absoluteBoundingBox;\n\n // Check both axes FIXED (stronger case)\n const hFixed =\n node.layoutSizingHorizontal === \"FIXED\" || node.layoutSizingHorizontal === undefined;\n const vFixed =\n node.layoutSizingVertical === \"FIXED\" || node.layoutSizingVertical === undefined;\n\n if (hFixed && vFixed) {\n // Skip if it has its own auto-layout\n if (node.layoutMode && node.layoutMode !== \"NONE\") return null;\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"both-axes\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.bothAxes(node.name, width, height),\n };\n }\n\n // Check horizontal-only FIXED (lighter case, from fixed-width-in-responsive-context)\n if (hFixed && !vFixed) {\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"horizontal\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.horizontal(node.name, width),\n };\n }\n\n return null;\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-size-constraint (merged: missing-min-width + missing-max-width)\n// ============================================\n\nconst missingSizeConstraintDef: RuleDefinition = {\n id: \"missing-size-constraint\",\n name: \"Missing Size Constraint\",\n category: \"responsive-critical\",\n why: \"Without min/max-width, AI has no bounds — generated code may collapse or stretch indefinitely\",\n impact: \"Content becomes unreadable or invisible at extreme screen sizes\",\n fix: \"Set min-width and/or max-width so AI can generate proper size constraints\",\n};\n\nconst missingSizeConstraintCheck: RuleCheckFn = (node, context) => {\n // Only check containers and text-containing nodes\n if (!isContainerNode(node) && !hasTextContent(node)) return null;\n // Skip if not in Auto Layout context\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n const nodePath = context.path.join(\" > \");\n\n // Check 1: wrap parent → FILL children need min-width\n if (context.parent.layoutWrap === \"WRAP\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"wrap\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.wrap(node.name),\n };\n }\n\n // Check 2: grid parent → FILL children need size constraints\n if (context.parent.layoutMode === \"GRID\" && node.layoutSizingHorizontal === \"FILL\" && node.minWidth === undefined && node.maxWidth === undefined) {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"grid\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.grid(node.name),\n };\n }\n\n // Check 3: FILL containers need max-width\n if (node.layoutSizingHorizontal === \"FILL\") {\n if (isSizeConstraintExempt(node, context)) return null;\n\n const currentWidth = node.absoluteBoundingBox ? `${node.absoluteBoundingBox.width}px` : \"unknown\";\n return {\n ruleId: missingSizeConstraintDef.id,\n subType: \"max-width\" as const,\n nodeId: node.id,\n nodePath,\n ...missingSizeConstraintMsg.maxWidth(node.name, currentWidth),\n };\n }\n\n return null;\n};\n\nexport const missingSizeConstraint = defineRule({\n definition: missingSizeConstraintDef,\n check: missingSizeConstraintCheck,\n});\n\n// ============================================\n// non-layout-container (was group-usage — now also catches Section)\n// ============================================\n\nconst nonLayoutContainerDef: RuleDefinition = {\n id: \"non-layout-container\",\n name: \"Non-Layout Container\",\n category: \"pixel-critical\",\n why: \"Groups and Sections lack proper layout rules — AI sees children with absolute coordinates but no container logic\",\n impact: \"AI wraps elements in a plain div with no spacing/alignment, producing fragile layouts\",\n fix: \"Convert to Frame with Auto Layout so AI can generate proper flex/grid containers\",\n};\n\nconst nonLayoutContainerCheck: RuleCheckFn = (node, context) => {\n if (node.type === \"GROUP\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"group\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.group(node.name),\n };\n }\n\n if (node.type === \"SECTION\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"section\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.section(node.name),\n };\n }\n\n return null;\n};\n\nexport const nonLayoutContainer = defineRule({\n definition: nonLayoutContainerDef,\n check: nonLayoutContainerCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"code-quality\",\n why: \"Deep nesting consumes AI context exponentially — each level adds indentation and structural overhead\",\n impact: \"AI may lose track of parent-child relationships in deeply nested trees, producing wrong layout hierarchy\",\n fix: \"Flatten the structure by extracting deeply nested groups into sub-components\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.componentDepth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...deepNestingMsg(node.name, context.componentDepth, maxDepth),\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { rawValueMsg, irregularSpacingMsg } from \"../rule-messages.js\";\nimport { hasStyleReference, hasBoundVariable } from \"../node-semantics.js\";\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-value (merged: raw-color + raw-font + raw-shadow + raw-opacity + raw-spacing)\n// ============================================\n\nconst rawValueDef: RuleDefinition = {\n id: \"raw-value\",\n name: \"Raw Value\",\n category: \"token-management\",\n why: \"Values without design tokens or variables must be reproduced exactly per node — one typo means a visible difference\",\n impact: \"AI cannot reference a shared token, so each raw value is an independent source of error across large pages\",\n fix: \"Use design tokens or variables (color styles, text styles, effect styles, opacity/spacing variables) so values are referenceable\",\n};\n\nconst rawValueCheck: RuleCheckFn = (node, context) => {\n const nodePath = context.path.join(\" > \");\n\n // Check 1: Raw fill color\n if (node.fills && Array.isArray(node.fills) && node.fills.length > 0) {\n if (!hasStyleReference(node, \"fill\") && !hasBoundVariable(node, \"fills\")) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n const c = fillObj[\"color\"] as Record<string, number>;\n const hex = `#${Math.round((c[\"r\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"g\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"b\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}`.toUpperCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"color\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.color(node.name, hex),\n };\n }\n }\n }\n }\n\n // Check 2: Raw font (TEXT nodes without text style)\n if (node.type === \"TEXT\") {\n if (\n !hasStyleReference(node, \"text\") &&\n (!hasBoundVariable(node, \"fontFamily\") || !hasBoundVariable(node, \"fontSize\"))\n ) {\n const fontParts: string[] = [];\n const s = node.style;\n if (s) {\n if (s[\"fontFamily\"]) fontParts.push(String(s[\"fontFamily\"]));\n if (s[\"fontSize\"]) fontParts.push(`${s[\"fontSize\"]}px`);\n if (s[\"fontWeight\"]) fontParts.push(String(s[\"fontWeight\"]));\n }\n const fontDesc = fontParts.length > 0 ? ` (${fontParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"font\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.font(node.name, fontDesc),\n };\n }\n }\n\n // Check 3: Raw shadow (effects without effect style)\n if (node.effects && Array.isArray(node.effects) && node.effects.length > 0) {\n if (!hasStyleReference(node, \"effect\")) {\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (effectObj[\"type\"] === \"DROP_SHADOW\" || effectObj[\"type\"] === \"INNER_SHADOW\") {\n const shadowType = effectObj[\"type\"] === \"DROP_SHADOW\" ? \"drop shadow\" : \"inner shadow\";\n const offset = effectObj[\"offset\"] as Record<string, number> | undefined;\n const radius = effectObj[\"radius\"] as number | undefined;\n const detailParts: string[] = [];\n if (offset) detailParts.push(`offset ${Math.round(offset[\"x\"] ?? 0)},${Math.round(offset[\"y\"] ?? 0)}`);\n if (radius !== undefined) detailParts.push(`blur ${Math.round(radius)}`);\n const details = detailParts.length > 0 ? ` (${detailParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"shadow\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.shadow(node.name, shadowType, details),\n };\n }\n }\n }\n }\n\n // Check 4: Raw opacity (non-default opacity without variable)\n if (node.opacity !== undefined && node.opacity < 1 && !hasBoundVariable(node, \"opacity\")) {\n return {\n ruleId: rawValueDef.id,\n subType: \"opacity\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.opacity(node.name, Math.round(node.opacity * 100)),\n };\n }\n\n // Check 5: Raw spacing (padding/gap without variable binding)\n const spacingKeys = [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\", \"itemSpacing\"] as const;\n for (const key of spacingKeys) {\n const value = node[key];\n if (value !== undefined && value > 0 && !hasBoundVariable(node, key)) {\n const label = key === \"itemSpacing\" ? \"gap\" : key.replace(\"padding\", \"padding-\").toLowerCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"spacing\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.spacing(node.name, label, value),\n };\n }\n }\n\n return null;\n};\n\nexport const rawValue = defineRule({\n definition: rawValueDef,\n check: rawValueCheck,\n});\n\n// ============================================\n// irregular-spacing (merged: inconsistent-spacing + magic-number-spacing)\n// ============================================\n\nconst irregularSpacingDef: RuleDefinition = {\n id: \"irregular-spacing\",\n name: \"Irregular Spacing\",\n category: \"token-management\",\n why: \"Off-grid or arbitrary spacing values force AI to handle many unique values instead of a predictable pattern\",\n impact: \"Higher chance of pixel-level differences when AI substitutes nearby round values\",\n fix: \"Align spacing to the design system grid (e.g., 4pt/8pt increments) for predictable implementation\",\n};\n\nconst irregularSpacingCheck: RuleCheckFn = (node, context, options) => {\n const configuredGridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"irregular-spacing\", \"gridBase\", 4);\n const gridBase = Number.isFinite(configuredGridBase) && configuredGridBase > 0 ? configuredGridBase : 4;\n\n const spacingEntries: Array<{ value: number; subType: \"padding\" | \"gap\" }> = [];\n for (const key of [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\"] as const) {\n const v = node[key];\n if (v !== undefined && v > 0) spacingEntries.push({ value: v, subType: \"padding\" });\n }\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n spacingEntries.push({ value: node.itemSpacing, subType: \"gap\" });\n }\n\n // Allow small intentional values\n const commonValues = [1, 2];\n\n for (const entry of spacingEntries) {\n if (commonValues.includes(entry.value)) continue;\n if (!isOnGrid(entry.value, gridBase)) {\n return {\n ruleId: irregularSpacingDef.id,\n subType: entry.subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...irregularSpacingMsg(node.name, entry.value, gridBase, Math.round(entry.value / gridBase) * gridBase),\n };\n }\n }\n\n return null;\n};\n\nexport const irregularSpacing = defineRule({\n definition: irregularSpacingDef,\n check: irregularSpacingCheck,\n});\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { missingComponentMsg, detachedInstanceMsg, variantStructureMismatchMsg } from \"../rule-messages.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\n\n/** Style properties to compare between master and instance. */\nconst STYLE_COMPARE_KEYS = [\"fills\", \"strokes\", \"effects\", \"cornerRadius\", \"strokeWeight\", \"individualStrokeWeights\"] as const;\n\n/**\n * Detect style overrides between a component master and an instance.\n * Returns list of property names that differ.\n */\nfunction detectStyleOverrides(master: AnalysisNode, instance: AnalysisNode): string[] {\n const overrides: string[] = [];\n for (const key of STYLE_COMPARE_KEYS) {\n const masterVal = master[key];\n const instanceVal = instance[key];\n // Both undefined/null → no override\n if (masterVal == null && instanceVal == null) continue;\n // One exists, other doesn't → override\n if (masterVal == null || instanceVal == null) {\n overrides.push(key);\n continue;\n }\n // Deep compare via JSON\n if (JSON.stringify(masterVal) !== JSON.stringify(instanceVal)) {\n overrides.push(key);\n }\n }\n return overrides;\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n/**\n * Build a structural fingerprint for a node.\n * The fingerprint encodes type, layoutMode, and child types recursively up to maxDepth.\n */\nfunction buildFingerprint(node: AnalysisNode, depth: number): string {\n if (depth <= 0 || !node.children || node.children.length === 0) {\n return `${node.type}:${node.layoutMode ?? \"NONE\"}`;\n }\n\n const childFingerprints = node.children\n .map((child) => buildFingerprint(child, depth - 1))\n .join(\",\");\n\n return `${node.type}:${node.layoutMode ?? \"NONE\"}:[${childFingerprints}]`;\n}\n\n/**\n * Check if the node is inside an INSTANCE subtree.\n * Walks the full ancestor type chain to detect INSTANCE at any level.\n */\nfunction isInsideInstance(context: {\n ancestorTypes: string[];\n}): boolean {\n return context.ancestorTypes.includes(\"INSTANCE\");\n}\n\n\n\n// ============================================\n// missing-component (unified 4-stage rule)\n// ============================================\n\n/** State keys for per-analysis deduplication via RuleContext.analysisState */\nconst SEEN_STAGE1_KEY = \"missing-component:seenStage1ComponentNames\";\nconst SEEN_STAGE4_KEY = \"missing-component:seenStage4ComponentIds\";\n\nfunction getSeenStage1(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE1_KEY, () => new Set<string>());\n}\n\nfunction getSeenStage4(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE4_KEY, () => new Set<string>());\n}\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"code-quality\",\n why: \"Repeated structures, unused components, and divergent instance overrides indicate missing or underutilized components. This inflates AI token consumption and forces manual maintenance.\",\n impact: \"AI code generators reproduce each repeated frame independently instead of emitting a reusable component. Divergent instance overrides produce inconsistent implementations.\",\n fix: \"Create components from repeated structures, use instances instead of duplicated frames, and create variants for instances with significantly different overrides.\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // ========================================\n // FRAME stages (1, 2, 3) — ordered by priority\n // ========================================\n if (node.type === \"FRAME\") {\n // Stage 1: Component exists but not used — FRAME name matches a component in metadata AND frame is repeated\n const components = context.file.components;\n const matchingComponent = Object.values(components).find(\n (c) => c.name.toLowerCase() === node.name.toLowerCase()\n );\n\n // Collect frame names once for Stage 1 and Stage 2\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n const firstFrame = sameNameFrames?.[0];\n\n if (matchingComponent) {\n const seenStage1 = getSeenStage1(context);\n if (\n sameNameFrames &&\n firstFrame !== undefined &&\n sameNameFrames.length >= 2 &&\n !seenStage1.has(node.name.toLowerCase()) &&\n firstFrame === node.id\n ) {\n seenStage1.add(node.name.toLowerCase());\n return {\n ruleId: missingComponentDef.id,\n subType: \"unused-component\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.unusedComponent(matchingComponent.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 2: Name-based repetition (existing logic)\n const minRepetitions =\n (options?.[\"minRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n if (sameNameFrames && firstFrame !== undefined && sameNameFrames.length >= minRepetitions) {\n if (firstFrame === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"name-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.nameRepetition(node.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 3: Structure-based repetition (absorbed from repeated-frame-structure)\n // Skip if node is inside an INSTANCE subtree\n if (isInsideInstance(context)) return null;\n\n // Skip if parent is COMPONENT_SET\n if (context.parent?.type === \"COMPONENT_SET\") return null;\n\n // Skip if node has no children\n if (!node.children || node.children.length === 0) return null;\n\n const structureMinRepetitions =\n (options?.[\"structureMinRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"structureMinRepetitions\", 2);\n\n const maxFingerprintDepth =\n (options?.[\"maxFingerprintDepth\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"maxFingerprintDepth\", 3);\n\n // Compute fingerprint for this node\n const fingerprint = buildFingerprint(node, maxFingerprintDepth);\n\n // Access siblings (may be undefined)\n const siblings = context.siblings ?? [];\n\n // Filter siblings to qualifying frames (type === FRAME, not inside INSTANCE, has children)\n const qualifyingSiblings = siblings.filter(\n (s) =>\n s.type === \"FRAME\" &&\n s.children !== undefined &&\n s.children.length > 0\n );\n\n // Count siblings (including self) sharing the same fingerprint\n const matchingNodes = qualifyingSiblings.filter(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // Ensure self is counted (it should be in siblings, but add a guard)\n const selfIsInSiblings = qualifyingSiblings.some((s) => s.id === node.id);\n const count = selfIsInSiblings\n ? matchingNodes.length\n : matchingNodes.length + 1;\n\n if (count >= structureMinRepetitions) {\n // Only emit for the first sibling (by array order) with this fingerprint\n const firstMatch = qualifyingSiblings.find(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // If self is not in siblings list, treat self as first match when no earlier match exists\n const firstMatchId = firstMatch?.id ?? node.id;\n if (firstMatchId === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"structure-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.structureRepetition(node.name, count - 1),\n };\n }\n }\n\n return null;\n }\n\n // ========================================\n // Stage 4: Instance style override detection\n // Compares instance styles against component master.\n // Any style override (fills, strokes, effects, cornerRadius) means\n // the designer should use a variant instead.\n // ========================================\n if (node.type === \"INSTANCE\" && node.componentId) {\n const seenStage4 = getSeenStage4(context);\n if (seenStage4.has(node.componentId)) return null;\n\n const componentDefs = context.file.componentDefinitions;\n if (!componentDefs) return null;\n\n const master = componentDefs[node.componentId];\n if (!master) return null;\n\n // Compare style properties between master and instance\n const overrides = detectStyleOverrides(master, node);\n if (overrides.length > 0) {\n // Only mark as seen when we actually flag — allows other instances to be checked\n seenStage4.add(node.componentId);\n const componentMeta = context.file.components[node.componentId];\n const componentName = componentMeta?.name ?? node.name;\n\n return {\n ruleId: missingComponentDef.id,\n subType: \"style-override\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.styleOverride(componentName, overrides),\n };\n }\n return null;\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"code-quality\",\n why: \"Detached instances lose component relationship — AI sees a one-off frame instead of a reusable component reference\",\n impact: \"AI generates duplicate code instead of reusing the component, inflating output and causing inconsistencies\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a matching name (word boundary)\n const components = context.file.components;\n\n for (const [, component] of Object.entries(components)) {\n const pattern = new RegExp(`\\\\b${component.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`);\n if (pattern.test(node.name)) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...detachedInstanceMsg(node.name, component.name),\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// variant-structure-mismatch\n// ============================================\n\nconst variantStructureMismatchDef: RuleDefinition = {\n id: \"variant-structure-mismatch\",\n name: \"Variant Structure Mismatch\",\n category: \"code-quality\",\n why: \"Variants with different child structures prevent AI from creating a unified component template\",\n impact: \"AI must generate separate implementations for each variant instead of a single parameterized component\",\n fix: \"Ensure all variants share the same child structure, using visibility toggles for optional elements\",\n};\n\nconst variantStructureMismatchCheck: RuleCheckFn = (node, context) => {\n // Only COMPONENT_SET\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.children?.length || node.children.length < 2) return null;\n\n // Build fingerprint for each variant child\n const fingerprints = node.children\n .filter(child => child.type === \"COMPONENT\")\n .map(child => buildFingerprint(child, 2));\n\n if (fingerprints.length < 2) return null;\n\n // Compare all fingerprints to the first one\n const base = fingerprints[0];\n const mismatched = fingerprints.filter(fp => fp !== base);\n\n if (mismatched.length === 0) return null;\n\n const mismatchCount = mismatched.length;\n const totalVariants = fingerprints.length;\n\n return {\n ruleId: variantStructureMismatchDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...variantStructureMismatchMsg(node.name, mismatchCount, totalVariants),\n };\n};\n\nexport const variantStructureMismatch = defineRule({\n definition: variantStructureMismatchDef,\n check: variantStructureMismatchCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getDefaultNameSubType, nonSemanticNameMsg, inconsistentNamingMsg, nonStandardNamingMsg } from \"../rule-messages.js\";\nimport { isExcludedName, isDefaultName, isNonSemanticName, STANDARD_STATE_NAMES, STATE_NAME_SUGGESTIONS, STATE_LIKE_PATTERN } from \"../node-semantics.js\";\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n/** Single capitalized word is compatible with both PascalCase and Title Case */\nfunction isCompatible(nodeConvention: string, dominantConvention: string, name: string): boolean {\n if (!/^[A-Z][a-z]+$/.test(name)) return false;\n const pair = new Set([nodeConvention, dominantConvention]);\n return pair.has(\"PascalCase\") && pair.has(\"Title Case\");\n}\n\n/** Split a name into words regardless of convention */\nfunction splitWords(name: string): string[] {\n // Title Case / space-separated\n if (/\\s/.test(name)) return name.split(/\\s+/);\n // SCREAMING_SNAKE_CASE or snake_case\n if (name.includes(\"_\")) return name.split(\"_\");\n // kebab-case\n if (name.includes(\"-\")) return name.split(\"-\");\n // camelCase / PascalCase — split on uppercase boundaries (including acronym runs)\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1\\0$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1\\0$2\")\n .split(\"\\0\");\n}\n\n/** Convert a name to the target convention */\nfunction convertName(name: string, target: string): string {\n const words = splitWords(name);\n switch (target) {\n case \"kebab-case\":\n return words.map(w => w.toLowerCase()).join(\"-\");\n case \"snake_case\":\n return words.map(w => w.toLowerCase()).join(\"_\");\n case \"camelCase\":\n return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"PascalCase\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"SCREAMING_SNAKE_CASE\":\n return words.map(w => w.toUpperCase()).join(\"_\");\n case \"Title Case\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\" \");\n default:\n return name;\n }\n}\n\n// ============================================\n// non-semantic-name (merged: default-name + non-semantic-name)\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"semantic\",\n why: \"Default or shape names give AI no semantic context — it cannot choose appropriate HTML tags or class names\",\n impact: \"AI generates generic <div> wrappers instead of semantic elements like <header>, <nav>, <article>\",\n fix: \"Rename with a descriptive, purpose-driven name (e.g., 'Header', 'ProductCard', 'Divider')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n\n // Check 1: Figma default names (Frame 1, Group 2, etc.)\n if (isDefaultName(node.name)) {\n return {\n ruleId: nonSemanticNameDef.id,\n subType: getDefaultNameSubType(node.type),\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n // Check 2: Shape-only names (rectangle, ellipse, vector, etc.)\n if (isNonSemanticName(node.name)) {\n // Allow shape names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n subType: \"shape-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n return null;\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"semantic\",\n why: \"Mixed naming conventions (camelCase + kebab-case + Title Case) at the same level confuse AI pattern recognition\",\n impact: \"AI generates inconsistent class/component names, making the codebase harder to maintain\",\n fix: \"Pick one convention for sibling elements (e.g., kebab-case: 'product-card', or PascalCase: 'ProductCard') — AI maps names to CSS classes and component names, so mixed conventions produce inconsistent code\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n let ambiguousPascalCount = 0;\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n if (convention === \"PascalCase\" && /^[A-Z][a-z]+$/.test(sibling.name)) {\n ambiguousPascalCount++;\n }\n }\n }\n\n // Single capitalized words (Header, Footer) are detected as PascalCase but are\n // equally valid as Title Case. When both conventions appear, discount these\n // ambiguous names so they don't bias the dominant convention toward PascalCase.\n if (conventions.has(\"PascalCase\") && conventions.has(\"Title Case\") && ambiguousPascalCount > 0) {\n const adjusted = (conventions.get(\"PascalCase\") ?? 0) - ambiguousPascalCount;\n if (adjusted <= 0) {\n conventions.delete(\"PascalCase\");\n } else {\n conventions.set(\"PascalCase\", adjusted);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n // Single capitalized word is compatible with both PascalCase and Title Case\n if (isCompatible(nodeConvention, dominantConvention, node.name)) return null;\n\n const suggested = convertName(node.name, dominantConvention);\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...inconsistentNamingMsg(node.name, nodeConvention, dominantConvention, suggested),\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// non-standard-naming\n// ============================================\n\nconst nonStandardNamingDef: RuleDefinition = {\n id: \"non-standard-naming\",\n name: \"Non-Standard Naming\",\n category: \"semantic\",\n why: \"Non-standard state names prevent interaction rules from detecting state variants — AI cannot generate correct :hover/:active/:disabled styles\",\n impact: \"Interaction state detection fails, resulting in static UI with no state transitions\",\n fix: \"Use platform-standard state names: default, hover, active, pressed, selected, highlighted, disabled, enabled, focus, focused, dragged\",\n};\n\nconst nonStandardNamingCheck: RuleCheckFn = (node, context) => {\n // Only check COMPONENT_SET (variant container)\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.componentPropertyDefinitions) return null;\n\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n\n for (const opt of options) {\n if (typeof opt !== \"string\") continue;\n const lower = opt.toLowerCase().trim();\n\n // Skip if it's a standard name\n if (STANDARD_STATE_NAMES.has(lower)) continue;\n\n // Check if it matches a known non-standard state name\n if (STATE_LIKE_PATTERN.test(opt)) {\n const suggestion = STATE_NAME_SUGGESTIONS[lower];\n if (suggestion) {\n return {\n ruleId: nonStandardNamingDef.id,\n subType: \"state-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonStandardNamingMsg.stateName(node.name, opt, suggestion),\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const nonStandardNaming = defineRule({\n definition: nonStandardNamingDef,\n check: nonStandardNamingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport type { MissingInteractionStateSubType, MissingPrototypeSubType } from \"../rule-messages.js\";\nimport { missingInteractionStateMsg, missingPrototypeMsg } from \"../rule-messages.js\";\nimport { getStatefulComponentType, isOverlayNode, isCarouselNode, type StatefulComponentType } from \"../node-semantics.js\";\n\n/** Expected state variants by interactive type */\nconst EXPECTED_STATES: Record<StatefulComponentType, MissingInteractionStateSubType[]> = {\n button: [\"hover\", \"active\", \"disabled\"],\n link: [\"hover\"],\n tab: [\"hover\", \"active\"],\n input: [\"focus\", \"disabled\"],\n toggle: [\"disabled\"],\n};\n\n/** State name patterns — web + mobile platform standard names */\nconst STATE_PATTERNS: Record<MissingInteractionStateSubType, RegExp> = {\n hover: /\\bhover\\b/i,\n disabled: /\\bdisabled\\b/i,\n active: /\\b(active|pressed|selected|highlighted)\\b/i,\n focus: /\\bfocus(ed)?\\b/i,\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/** Dedup key: emit at most one violation per componentId + subType */\nconst SEEN_KEY = \"missing-interaction-state:seen\";\n\nfunction getSeen(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_KEY, () => new Set<string>());\n}\n\n/**\n * Check if a state variant exists via componentPropertyDefinitions.\n * Looks for VARIANT type properties where variantOptions contain the state name.\n */\nfunction hasStateInVariantProps(node: AnalysisNode, statePattern: RegExp): boolean {\n if (!node.componentPropertyDefinitions) return false;\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n if (options.some((opt) => typeof opt === \"string\" && statePattern.test(opt))) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a state variant exists via component master's componentPropertyDefinitions.\n * Falls back to componentDefinitions (fetched masters) when the instance itself\n * doesn't carry the property definitions.\n */\nfunction hasStateInComponentMaster(\n node: AnalysisNode,\n context: RuleContext,\n statePattern: RegExp,\n): boolean {\n if (!node.componentId) return false;\n const defs = context.file.componentDefinitions;\n if (!defs) return false;\n const master = defs[node.componentId];\n if (!master) return false;\n return hasStateInVariantProps(master, statePattern);\n}\n\n// ============================================\n// missing-interaction-state\n// ============================================\n\nconst missingInteractionStateDef: RuleDefinition = {\n id: \"missing-interaction-state\",\n name: \"Missing Interaction State\",\n category: \"interaction\",\n why: \"Interactive components without state variants force AI to guess hover/focus/disabled appearances — or skip them entirely\",\n impact: \"Generated code has no :hover, :focus, or :disabled styles, making the UI feel static and unresponsive\",\n fix: \"Add state variants (Hover, Disabled, Focus, Active) to interactive components in Figma\",\n};\n\nconst missingInteractionStateCheck: RuleCheckFn = (node, context) => {\n // Only check component instances and components\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\") return null;\n\n const interactiveType = getStatefulComponentType(node);\n if (!interactiveType) return null;\n\n const expectedStates = EXPECTED_STATES[interactiveType];\n if (!expectedStates) return null;\n\n const seen = getSeen(context);\n const nodePath = context.path.join(\" > \");\n\n for (const state of expectedStates) {\n const dedupeKey = `${node.componentId ?? node.id}:${state}`;\n if (seen.has(dedupeKey)) continue;\n\n const pattern = STATE_PATTERNS[state];\n\n // Check variant properties on instance\n if (hasStateInVariantProps(node, pattern)) continue;\n\n // Check variant properties on component master (fetched definitions)\n if (hasStateInComponentMaster(node, context, pattern)) continue;\n\n // Missing state — report first missing one\n seen.add(dedupeKey);\n return {\n ruleId: missingInteractionStateDef.id,\n subType: state,\n nodeId: node.id,\n nodePath,\n ...missingInteractionStateMsg[state](node.name),\n };\n }\n\n return null;\n};\n\nexport const missingInteractionState = defineRule({\n definition: missingInteractionStateDef,\n check: missingInteractionStateCheck,\n});\n\n// ============================================\n// missing-prototype\n// ============================================\n\n/** Interactive types that need click prototype */\nconst PROTOTYPE_TYPES: Record<StatefulComponentType, MissingPrototypeSubType> = {\n button: \"button\",\n link: \"navigation\",\n tab: \"tab\",\n input: \"input\",\n toggle: \"toggle\",\n};\n\nfunction getPrototypeSubType(node: AnalysisNode): MissingPrototypeSubType | null {\n // Check overlay/carousel first — select/dropdown are classified as \"input\" in\n // STATEFUL_PATTERNS but need \"overlay\" subType for prototype checks\n if (isOverlayNode(node)) return \"overlay\";\n if (isCarouselNode(node)) return \"carousel\";\n const interactiveType = getStatefulComponentType(node);\n if (interactiveType) {\n const mapped = PROTOTYPE_TYPES[interactiveType];\n if (mapped) return mapped;\n }\n return null;\n}\n\nfunction hasInteractionTrigger(node: AnalysisNode, triggerType: string): boolean {\n if (!node.interactions || !Array.isArray(node.interactions)) return false;\n return node.interactions.some((interaction) => {\n const i = interaction as { trigger?: { type?: string } };\n return i.trigger?.type === triggerType;\n });\n}\n\n/** Check if node (or its component master) has any of the given trigger types */\nfunction hasAnyInteraction(node: AnalysisNode, context: RuleContext, triggers: string[]): boolean {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(node, trigger)) return true;\n }\n // INSTANCE nodes don't inherit interactions from master — check master fallback\n if (node.componentId && context.file.componentDefinitions) {\n const master = context.file.componentDefinitions[node.componentId];\n if (master) {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(master, trigger)) return true;\n }\n }\n }\n return false;\n}\n\n/** Trigger types to check per subType */\nconst PROTOTYPE_TRIGGERS: Record<string, string[]> = {\n carousel: [\"ON_CLICK\", \"ON_DRAG\"],\n};\n\nconst DEFAULT_TRIGGERS = [\"ON_CLICK\"];\n\nconst missingPrototypeDef: RuleDefinition = {\n id: \"missing-prototype\",\n name: \"Missing Prototype\",\n category: \"interaction\",\n why: \"Interactive elements without prototype interactions give AI no information about navigation or behavior\",\n impact: \"AI cannot generate interaction handlers, routing, or state changes — interactive elements become static\",\n fix: \"Add prototype interactions (ON_CLICK, ON_DRAG) to define navigation targets or state changes\",\n};\n\nconst SEEN_PROTO_KEY = \"missing-prototype:seen\";\n\nfunction getSeenProto(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_PROTO_KEY, () => new Set<string>());\n}\n\nconst missingPrototypeCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\" && node.type !== \"FRAME\") return null;\n\n const subType = getPrototypeSubType(node);\n if (!subType) return null;\n\n // Already has relevant interaction (click, or drag for carousel)\n const triggers = PROTOTYPE_TRIGGERS[subType] ?? DEFAULT_TRIGGERS;\n if (hasAnyInteraction(node, context, triggers)) return null;\n\n // Dedup per componentId + subType\n const seen = getSeenProto(context);\n const dedupeKey = `${node.componentId ?? node.id}:${subType}`;\n if (seen.has(dedupeKey)) return null;\n seen.add(dedupeKey);\n\n return {\n ruleId: missingPrototypeDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingPrototypeMsg[subType](node.name),\n };\n};\n\nexport const missingPrototype = defineRule({\n definition: missingPrototypeDef,\n check: missingPrototypeCheck,\n});\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile, isJsonFile, isFixtureDir } from \"../core/engine/loader.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/config-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\n\n// Load .env for FIGMA_TOKEN (quiet: suppress dotenv's stdout banner — MCP uses stdout for JSON-RPC)\nconfig({ quiet: true });\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst server = new McpServer({\n name: \"canicode\",\n version: pkg.version,\n});\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ input, token, preset, targetNodeId, configPath }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n // Fetch via REST API or load from fixture\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // Open report in browser\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores, { fileKey: file.fileKey }), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- design-tree: Generate DOM-like design tree from fixture for AI code generation\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"rules\", \"config\", \"visual-compare\", \"design-tree\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from CUSTOMIZATION.md)\n const inlineTopics: Record<string, string> = {\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -e FIGMA_TOKEN=figd_xxxxxxxxxxxxx -- npx -y -p canicode canicode-mcp\n\\`\\`\\`\n\nRequires FIGMA_TOKEN for live Figma URL analysis.`,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (inferred from Figma PNG ÷ scale) | Logical viewport width in CSS px |\n| --height <px> | (inferred from Figma PNG ÷ scale) | Logical viewport height in CSS px |\n| --figma-scale <n> | 2 | Figma export scale (matches @2x fixture PNGs) |\n\nViewport and device pixel ratio are auto-inferred from the Figma PNG dimensions and export scale. Override only when needed.\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (at export scale, default @2x)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n\n \"design-tree\": `# Design Tree\n\nGenerate a DOM-like design tree from a Figma fixture. Converts the node tree to a concise text format with inline CSS styles — 50-100x smaller than raw JSON.\n\n## Usage\n\\`\\`\\`bash\ncanicode design-tree ./fixtures/design\ncanicode design-tree ./fixtures/design --output tree.txt\ncanicode design-tree \"https://www.figma.com/design/ABC/File?node-id=1-234\"\n\\`\\`\\`\n\n## Output Format\nEach node = one line with name, type, dimensions, followed by CSS-ready styles:\n\\`\\`\\`\nHero Form (INSTANCE, 375x960)\n style: display: flex; flex-direction: column; gap: 32px; padding: 160px 24px; background: #F5F5F5\n Title (TEXT, 117x58)\n style: font-family: \"Inter\"; font-weight: 700; font-size: 48px; color: #2C2C2C; text: \"Title\"\n\\`\\`\\`\n\n## Use Cases\n- AI code generation — feed this to an LLM instead of raw 250KB fixture JSON\n- Calibration pipeline — Converter uses this for accurate code reproduction\n- Debugging — quickly see the design structure and styles`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to CUSTOMIZATION.md for config/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/CUSTOMIZATION.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/CUSTOMIZATION.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nLogical viewport and device pixel ratio are inferred from the Figma PNG export scale (default 2×) so code.png matches figma.png pixels.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n figmaExportScale: z.number().int().min(1).max(4).optional().describe(\"Figma export scale (default 2, matches @2x fixture PNGs)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir, figmaExportScale }) => {\n try {\n const { visualCompare } = await import(\"../core/comparison/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n ...(figmaExportScale !== undefined ? { figmaExportScale } : {}),\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}