uilint 0.2.13 → 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-EYCSOCU4.js → chunk-FRNXXIEM.js} +1 -32
- package/dist/{chunk-EYCSOCU4.js.map → chunk-FRNXXIEM.js.map} +1 -1
- package/dist/{chunk-2RNDQVEK.js → chunk-PBEKMDUH.js} +68 -13
- package/dist/chunk-PBEKMDUH.js.map +1 -0
- package/dist/index.js +16 -7
- package/dist/index.js.map +1 -1
- package/dist/{install-ui-ITXPOUVQ.js → install-ui-73AINMZ5.js} +602 -243
- package/dist/install-ui-73AINMZ5.js.map +1 -0
- package/dist/{plan-PX7FFJ25.js → plan-VPDTICSY.js} +9 -8
- package/dist/plan-VPDTICSY.js.map +1 -0
- package/package.json +3 -3
- package/dist/chunk-2RNDQVEK.js.map +0 -1
- package/dist/install-ui-ITXPOUVQ.js.map +0 -1
- package/dist/plan-PX7FFJ25.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/install-ui.tsx","../src/commands/install/components/InstallApp.tsx","../src/commands/install/components/Spinner.tsx","../src/commands/install/components/ProjectSelector.tsx","../src/commands/install/components/MultiSelect.tsx","../src/commands/install/components/RuleSelector.tsx","../src/commands/install/installers/registry.ts","../src/commands/install/analyze.ts","../src/utils/vite-detect.ts","../src/utils/package-detect.ts","../src/utils/package-manager.ts","../src/utils/eslint-config-inject.ts","../src/commands/install/execute.ts","../src/utils/react-inject.ts","../src/utils/next-config-inject.ts","../src/utils/vite-config-inject.ts","../src/utils/next-routes.ts","../src/utils/prettier.ts","../src/commands/install/installers/genstyleguide.ts","../src/commands/install/installers/skill.ts","../src/commands/install/installers/eslint.ts","../src/commands/install/installers/next-overlay.ts","../src/commands/install/installers/vite-overlay.ts","../src/commands/install/installers/index.ts"],"sourcesContent":["/**\n * Install command with new Ink-based UI\n *\n * This is the new installer flow that shows:\n * 1. Project selection (which Next.js/Vite app to configure)\n * 2. Feature selection (what to install)\n * 3. ESLint rule configuration (if ESLint selected)\n * 4. Completion summary\n */\n\nimport React from \"react\";\nimport { render } from \"ink\";\nimport { InstallApp } from \"./install/components/InstallApp.js\";\nimport { analyze } from \"./install/analyze.js\";\nimport { execute } from \"./install/execute.js\";\nimport type {\n InstallOptions,\n ExecuteOptions,\n UserChoices,\n InstallItem,\n ProjectState,\n} from \"./install/types.js\";\nimport type {\n InstallerSelection,\n InstallTarget,\n} from \"./install/installers/types.js\";\nimport type { ConfiguredRule } from \"./install/components/RuleSelector.js\";\nimport { ruleRegistry } from \"uilint-eslint\";\nimport {\n detectExecutionPackageManager,\n detectPackageManager,\n type PackageManager,\n} from \"../utils/package-manager.js\";\nimport { printBox } from \"../utils/output.js\";\nimport { existsSync } from \"fs\";\nimport { join } from \"path\";\n\n// Import installers to trigger registration\nimport \"./install/installers/index.js\";\n\n/**\n * Convert installer selections and configured rules to UserChoices for the execute phase\n */\nfunction selectionsToUserChoices(\n selections: InstallerSelection[],\n project: ProjectState,\n eslintRules?: ConfiguredRule[]\n): UserChoices {\n const items: InstallItem[] = [];\n const choices: UserChoices = { items };\n\n for (const selection of selections) {\n if (!selection.selected || selection.targets.length === 0) continue;\n\n const { installer, targets } = selection;\n\n if (installer.id === \"genstyleguide\") {\n items.push(\"genstyleguide\");\n } else if (installer.id === \"skill\") {\n items.push(\"skill\");\n } else if (installer.id === \"eslint\") {\n items.push(\"eslint\");\n // Add ESLint choices with configured rules\n choices.eslint = {\n packagePaths: targets.map((t: InstallTarget) => t.path),\n // Use configured rules if provided, otherwise fall back to all rules\n selectedRules: eslintRules\n ? eslintRules.map((cr) => ({\n ...cr.rule,\n // Override severity with user's selection\n defaultSeverity: cr.severity,\n defaultOptions: cr.options,\n }))\n : ruleRegistry,\n };\n } else if (installer.id === \"next\") {\n items.push(\"next\");\n // Add Next.js choices\n const target = targets[0];\n const appInfo = project.nextApps.find(\n (app) => app.projectPath === target?.path\n );\n if (appInfo) {\n choices.next = {\n projectPath: appInfo.projectPath,\n detection: appInfo.detection,\n };\n }\n } else if (installer.id === \"vite\") {\n items.push(\"vite\");\n // Add Vite choices\n const target = targets[0];\n const appInfo = project.viteApps.find(\n (app) => app.projectPath === target?.path\n );\n if (appInfo) {\n choices.vite = {\n projectPath: appInfo.projectPath,\n detection: appInfo.detection,\n };\n }\n }\n }\n\n return choices;\n}\n\n/**\n * Check if terminal supports interactive mode\n */\nfunction isInteractiveTerminal(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\n/**\n * Get the recommended command for a package manager\n */\nfunction getRecommendedCommand(pm: PackageManager): string {\n switch (pm) {\n case \"pnpm\":\n return \"pnpm dlx uilint install\";\n case \"yarn\":\n return \"yarn dlx uilint install\";\n case \"bun\":\n return \"bunx uilint install\";\n case \"npm\":\n default:\n return \"npx uilint install\";\n }\n}\n\n/**\n * Warn the user if they're running with a different package manager than the project uses.\n * For example, running `npx uilint install` in a yarn project will create a package-lock.json.\n *\n * This handles several scenarios:\n * 1. Single project: check if running pm matches project's lockfile\n * 2. Monorepo with root package.json: check workspace root's package manager\n * 3. Multi-project repo without root package.json: check all discovered packages' package managers\n */\nasync function warnOnPackageManagerMismatch(\n projectPromise: Promise<ProjectState>\n): Promise<void> {\n const executionPm = detectExecutionPackageManager();\n\n // If we can't detect the execution package manager, skip the check\n if (!executionPm) return;\n\n const project = await projectPromise;\n\n // Collect all unique package managers used by discovered packages\n const packageManagers = new Set<PackageManager>();\n\n // Check if current directory has a package.json (standard case)\n const hasRootPackageJson = existsSync(join(project.projectPath, \"package.json\"));\n\n if (hasRootPackageJson) {\n // Standard case: use the detected package manager from projectPath\n packageManagers.add(project.packageManager);\n } else {\n // No package.json at root - check all discovered packages\n // This handles repos like: root/ -> frontend/ (yarn), backend/ (go)\n for (const pkg of project.packages) {\n const pm = detectPackageManager(pkg.path);\n packageManagers.add(pm);\n }\n }\n\n // Filter out npm since it's the default when no lockfile is found\n // We only want to warn if there's a specific package manager detected\n const specificPackageManagers = Array.from(packageManagers).filter(\n (pm) => pm !== \"npm\" || hasRootPackageJson\n );\n\n // If no specific package managers found, nothing to warn about\n if (specificPackageManagers.length === 0) return;\n\n // Check if execution pm matches any of the project's package managers\n if (specificPackageManagers.includes(executionPm)) return;\n\n // Show warning about the mismatch\n const primaryPm = specificPackageManagers[0];\n const recommendedCmd = getRecommendedCommand(primaryPm);\n\n const pmList =\n specificPackageManagers.length === 1\n ? specificPackageManagers[0]\n : specificPackageManagers.join(\", \");\n\n printBox(\n \"Package manager mismatch detected\",\n [\n `This project uses ${pmList}, but you ran this command with ${executionPm}.`,\n \"\",\n `Running with ${executionPm} may create unwanted lockfiles.`,\n \"\",\n \"Recommended:\",\n ` ${recommendedCmd}`,\n \"\",\n \"Continuing anyway...\",\n ],\n \"warning\"\n );\n}\n\n/**\n * Main install function with new UI\n *\n * @param options - CLI options\n * @param executeOptions - Options for the execute phase\n */\nexport async function installUI(\n options: InstallOptions = {},\n executeOptions: ExecuteOptions = {}\n): Promise<void> {\n const projectPath = process.cwd();\n\n // Check if terminal supports interactive mode\n if (!isInteractiveTerminal()) {\n console.error(\"\\n✗ Interactive mode requires a TTY terminal.\");\n console.error(\"Run uilint install in an interactive terminal.\\n\");\n process.exit(1);\n }\n\n // Start project analysis\n const projectPromise = analyze(projectPath);\n\n // Check for package manager mismatch and warn the user\n await warnOnPackageManagerMismatch(projectPromise);\n\n // Render the Ink app\n const { waitUntilExit } = render(\n <InstallApp\n projectPromise={projectPromise}\n onComplete={async (selections, eslintRules) => {\n // When user completes selection, proceed with installation\n const project = await projectPromise;\n const choices = selectionsToUserChoices(selections, project, eslintRules);\n\n if (choices.items.length === 0) {\n console.log(\"\\nNo items selected for installation\");\n process.exit(0);\n }\n\n // Generate plan using existing plan logic\n const { createPlan } = await import(\"./install/plan.js\");\n const plan = createPlan(project, choices, { force: options.force });\n\n // Execute the plan with projectPath for prettier formatting\n const result = await execute(plan, {\n ...executeOptions,\n projectPath: project.projectPath,\n });\n\n // Display results\n if (result.success) {\n console.log(\"\\n✓ Installation completed successfully!\");\n } else {\n console.log(\"\\n⚠ Installation completed with errors\");\n }\n\n process.exit(result.success ? 0 : 1);\n }}\n onError={(error) => {\n console.error(\"\\n✗ Error:\", error.message);\n process.exit(1);\n }}\n />\n );\n\n // Wait for the app to exit\n await waitUntilExit();\n}\n","/**\n * InstallApp - Main Ink React component for the installer UI\n *\n * Three-phase installation flow:\n * 1. Select a project (Next.js app, Vite app, etc.)\n * 2. Select features to install\n * 3. Configure ESLint rules (if ESLint selected)\n */\n\nimport React, { useState, useEffect } from \"react\";\nimport { Box, Text, useApp, useInput } from \"ink\";\nimport { Spinner } from \"./Spinner.js\";\nimport { ProjectSelector, getDetectedProjects, type DetectedProject } from \"./ProjectSelector.js\";\nimport { ConfigSelector, type ConfigItem } from \"./MultiSelect.js\";\nimport { RuleSelector, type ConfiguredRule } from \"./RuleSelector.js\";\nimport type { ProjectState } from \"../types.js\";\nimport type { InstallerSelection } from \"../installers/types.js\";\nimport { getAllInstallers } from \"../installers/registry.js\";\n\ntype AppPhase =\n | \"scanning\"\n | \"select-project\"\n | \"configure-features\"\n | \"configure-eslint\"\n | \"error\";\n\nexport interface InstallAppProps {\n /** Project scan promise (resolves to ProjectState) */\n projectPromise: Promise<ProjectState>;\n /** Callback when installation is complete */\n onComplete: (selections: InstallerSelection[], eslintRules?: ConfiguredRule[]) => void;\n /** Callback when error occurs */\n onError?: (error: Error) => void;\n}\n\n/**\n * Build config items for a specific project\n */\nfunction buildConfigItemsForProject(\n project: ProjectState,\n selectedProject: DetectedProject,\n selections: InstallerSelection[]\n): ConfigItem[] {\n const items: ConfigItem[] = [];\n\n for (const selection of selections) {\n const { installer, targets } = selection;\n\n // Filter targets to those relevant to the selected project\n const relevantTargets = targets.filter((target) => {\n // For overlay installers, match by path\n if (installer.id === \"next\" || installer.id === \"vite\") {\n return target.path === selectedProject.path;\n }\n // For ESLint, match by package path\n if (installer.id === \"eslint\") {\n return target.path === selectedProject.path;\n }\n // Global features (genstyleguide, skill) always included\n return true;\n });\n\n if (relevantTargets.length === 0) continue;\n\n // Map installer IDs to display info\n const displayInfo: Record<string, { category: string; icon: string }> = {\n next: { category: \"UI Analysis\", icon: \"🔍\" },\n vite: { category: \"UI Analysis\", icon: \"🔍\" },\n eslint: { category: \"ESLint Rules\", icon: \"📋\" },\n genstyleguide: { category: \"Cursor Integration\", icon: \"📝\" },\n skill: { category: \"Cursor Integration\", icon: \"⚡\" },\n };\n\n const info = displayInfo[installer.id] || { category: \"Other\", icon: \"•\" };\n\n for (const target of relevantTargets) {\n items.push({\n id: `${installer.id}:${target.id}`,\n label: installer.name,\n hint: target.hint,\n status: target.isInstalled ? \"installed\" : \"not_installed\",\n category: info.category,\n categoryIcon: info.icon,\n });\n }\n }\n\n return items;\n}\n\n/**\n * Build config items for global features only (no project-specific items)\n */\nfunction buildGlobalConfigItems(selections: InstallerSelection[]): ConfigItem[] {\n const items: ConfigItem[] = [];\n\n for (const selection of selections) {\n const { installer, targets } = selection;\n\n // Only include global installers\n if (installer.id !== \"genstyleguide\" && installer.id !== \"skill\") {\n continue;\n }\n\n const displayInfo: Record<string, { category: string; icon: string }> = {\n genstyleguide: { category: \"Cursor Integration\", icon: \"📝\" },\n skill: { category: \"Cursor Integration\", icon: \"⚡\" },\n };\n\n const info = displayInfo[installer.id] || { category: \"Other\", icon: \"•\" };\n\n for (const target of targets) {\n items.push({\n id: `${installer.id}:${target.id}`,\n label: installer.name,\n hint: target.hint,\n status: target.isInstalled ? \"installed\" : \"not_installed\",\n category: info.category,\n categoryIcon: info.icon,\n });\n }\n }\n\n return items;\n}\n\n/**\n * Header component with app branding\n */\nfunction Header({ subtitle }: { subtitle?: string }): React.ReactElement {\n return (\n <Box flexDirection=\"column\" marginBottom={1}>\n <Box>\n <Text bold color=\"cyan\">◆ UILint</Text>\n <Text dimColor> v0.5.0</Text>\n {subtitle && <Text dimColor> · {subtitle}</Text>}\n </Box>\n </Box>\n );\n}\n\n/**\n * Feature configuration with back support\n */\nfunction FeatureConfig({\n selectedProject,\n configItems,\n canGoBack,\n onSubmit,\n onBack,\n onCancel,\n}: {\n selectedProject: DetectedProject | null;\n configItems: ConfigItem[];\n canGoBack: boolean;\n onSubmit: (selectedIds: string[]) => void;\n onBack: () => void;\n onCancel: () => void;\n}): React.ReactElement {\n useInput((input, key) => {\n if ((input === \"b\" || key.leftArrow) && canGoBack) {\n onBack();\n }\n });\n\n return (\n <Box flexDirection=\"column\">\n {/* Show selected project context */}\n {selectedProject && (\n <Box marginBottom={1}>\n <Text dimColor>Project: </Text>\n <Text bold color=\"cyan\">{selectedProject.name}</Text>\n <Text dimColor> ({selectedProject.hint})</Text>\n </Box>\n )}\n\n <ConfigSelector\n items={configItems}\n onSubmit={onSubmit}\n onCancel={onCancel}\n />\n\n {/* Back hint if multiple projects */}\n {canGoBack && (\n <Box marginTop={1}>\n <Text dimColor>\n Press <Text color=\"cyan\">b</Text> or <Text color=\"cyan\">←</Text> to select a different project\n </Text>\n </Box>\n )}\n </Box>\n );\n}\n\nexport function InstallApp({\n projectPromise,\n onComplete,\n onError,\n}: InstallAppProps): React.ReactElement {\n const { exit } = useApp();\n const [phase, setPhase] = useState<AppPhase>(\"scanning\");\n const [project, setProject] = useState<ProjectState | null>(null);\n const [detectedProjects, setDetectedProjects] = useState<DetectedProject[]>([]);\n const [selectedProject, setSelectedProject] = useState<DetectedProject | null>(null);\n const [selections, setSelections] = useState<InstallerSelection[]>([]);\n const [configItems, setConfigItems] = useState<ConfigItem[]>([]);\n const [selectedFeatureIds, setSelectedFeatureIds] = useState<string[]>([]);\n const [error, setError] = useState<Error | null>(null);\n\n // Check if ESLint is selected\n const isEslintSelected = selectedFeatureIds.some((id) => id.startsWith(\"eslint:\"));\n\n // Phase 1: Scan project\n useEffect(() => {\n if (phase !== \"scanning\") return;\n\n projectPromise\n .then((proj) => {\n setProject(proj);\n\n // Get detected projects\n const projects = getDetectedProjects(proj);\n setDetectedProjects(projects);\n\n // Build installer selections\n const installers = getAllInstallers();\n const initialSelections: InstallerSelection[] = installers\n .filter((installer) => installer.isApplicable(proj))\n .map((installer) => {\n const targets = installer.getTargets(proj);\n const nonInstalledTargets = targets.filter((t) => !t.isInstalled);\n return {\n installer,\n targets,\n selected: nonInstalledTargets.length > 0,\n };\n });\n setSelections(initialSelections);\n\n // If only one project, skip project selection\n if (projects.length === 1) {\n const singleProject = projects[0]!;\n setSelectedProject(singleProject);\n const items = buildConfigItemsForProject(proj, singleProject, initialSelections);\n setConfigItems(items);\n setPhase(\"configure-features\");\n } else if (projects.length === 0) {\n // No projects detected - go straight to global features\n setPhase(\"configure-features\");\n const items = buildGlobalConfigItems(initialSelections);\n setConfigItems(items);\n } else {\n setPhase(\"select-project\");\n }\n })\n .catch((err) => {\n setError(err as Error);\n setPhase(\"error\");\n onError?.(err as Error);\n });\n }, [phase, projectPromise, onError]);\n\n // Handle project selection\n const handleProjectSelect = (selected: DetectedProject) => {\n setSelectedProject(selected);\n if (project) {\n const items = buildConfigItemsForProject(project, selected, selections);\n setConfigItems(items);\n }\n setPhase(\"configure-features\");\n };\n\n // Handle back to project selection\n const handleBackToProject = () => {\n if (detectedProjects.length > 1) {\n setSelectedProject(null);\n setPhase(\"select-project\");\n }\n };\n\n // Handle feature selection submission\n const handleFeatureSubmit = (selectedIds: string[]) => {\n setSelectedFeatureIds(selectedIds);\n\n // Check if ESLint is selected - if so, go to rule configuration\n const eslintSelected = selectedIds.some((id) => id.startsWith(\"eslint:\"));\n\n if (eslintSelected) {\n setPhase(\"configure-eslint\");\n } else {\n // No ESLint, complete with current selections\n finishInstallation(selectedIds, undefined);\n }\n };\n\n // Handle ESLint rule configuration submission\n const handleRuleSubmit = (configuredRules: ConfiguredRule[]) => {\n finishInstallation(selectedFeatureIds, configuredRules);\n };\n\n // Handle back from ESLint config to feature selection\n const handleBackToFeatures = () => {\n setPhase(\"configure-features\");\n };\n\n // Finalize installation with all selections\n const finishInstallation = (selectedIds: string[], eslintRules?: ConfiguredRule[]) => {\n const selectedSet = new Set(selectedIds);\n\n const updatedSelections = selections.map((sel) => {\n const selectedTargets = sel.targets.filter((t) =>\n selectedSet.has(`${sel.installer.id}:${t.id}`)\n );\n return {\n ...sel,\n targets: selectedTargets,\n selected: selectedTargets.length > 0,\n };\n });\n\n setSelections(updatedSelections);\n onComplete(updatedSelections, eslintRules);\n };\n\n const handleCancel = () => {\n exit();\n };\n\n // Render: Scanning\n if (phase === \"scanning\") {\n return (\n <Box flexDirection=\"column\">\n <Header subtitle=\"Install\" />\n <Box>\n <Spinner />\n <Text> Scanning project...</Text>\n </Box>\n </Box>\n );\n }\n\n // Render: Error\n if (phase === \"error\") {\n return (\n <Box flexDirection=\"column\">\n <Header />\n <Box>\n <Text color=\"red\">✗ </Text>\n <Text color=\"red\">{error?.message || \"An unknown error occurred\"}</Text>\n </Box>\n </Box>\n );\n }\n\n // Render: Project selection\n if (phase === \"select-project\") {\n return (\n <Box flexDirection=\"column\">\n <Header subtitle=\"Install\" />\n <ProjectSelector\n projects={detectedProjects}\n onSelect={handleProjectSelect}\n onCancel={handleCancel}\n />\n </Box>\n );\n }\n\n // Render: Feature configuration\n if (phase === \"configure-features\" && project && configItems.length > 0) {\n return (\n <Box flexDirection=\"column\">\n <Header subtitle=\"Features\" />\n <FeatureConfig\n selectedProject={selectedProject}\n configItems={configItems}\n canGoBack={detectedProjects.length > 1}\n onSubmit={handleFeatureSubmit}\n onBack={handleBackToProject}\n onCancel={handleCancel}\n />\n </Box>\n );\n }\n\n // Render: ESLint rule configuration\n if (phase === \"configure-eslint\") {\n return (\n <Box flexDirection=\"column\">\n <Header subtitle=\"ESLint Rules\" />\n {selectedProject && (\n <Box marginBottom={1}>\n <Text dimColor>Project: </Text>\n <Text bold color=\"cyan\">{selectedProject.name}</Text>\n </Box>\n )}\n <RuleSelector\n onSubmit={handleRuleSubmit}\n onBack={handleBackToFeatures}\n onCancel={handleCancel}\n />\n </Box>\n );\n }\n\n // Fallback\n return (\n <Box flexDirection=\"column\">\n <Header />\n <Text dimColor>Loading...</Text>\n </Box>\n );\n}\n","/**\n * Simple Spinner component using core ink\n */\n\nimport React, { useState, useEffect } from \"react\";\nimport { Text } from \"ink\";\n\nconst frames = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport function Spinner(): React.ReactElement {\n const [frame, setFrame] = useState(0);\n\n useEffect(() => {\n const timer = setInterval(() => {\n setFrame((prevFrame) => (prevFrame + 1) % frames.length);\n }, 80);\n\n return () => {\n clearInterval(timer);\n };\n }, []);\n\n return <Text color=\"cyan\">{frames[frame]}</Text>;\n}\n","/**\n * ProjectSelector - First step: select which project to configure\n *\n * Shows a simple list of detected projects (Next.js apps, Vite apps, etc.)\n * and lets the user select one to configure.\n */\n\nimport React, { useState } from \"react\";\nimport { Box, Text, useInput, useApp } from \"ink\";\nimport type { ProjectState } from \"../types.js\";\n\nexport interface DetectedProject {\n /** Unique ID */\n id: string;\n /** Project name/label */\n name: string;\n /** Project path (relative to workspace) */\n path: string;\n /** Framework type */\n type: \"nextjs\" | \"vite\" | \"other\";\n /** Framework badge/hint */\n hint: string;\n /** Whether UILint is already configured */\n isConfigured: boolean;\n}\n\nexport interface ProjectSelectorProps {\n projects: DetectedProject[];\n onSelect: (project: DetectedProject) => void;\n onCancel?: () => void;\n}\n\n/**\n * Extract detected projects from ProjectState\n */\nexport function getDetectedProjects(project: ProjectState): DetectedProject[] {\n const projects: DetectedProject[] = [];\n\n // Add Next.js apps\n for (const app of project.nextApps) {\n const relativePath = app.projectPath.replace(project.workspaceRoot + \"/\", \"\");\n projects.push({\n id: `next:${app.projectPath}`,\n name: relativePath || \".\",\n path: app.projectPath,\n type: \"nextjs\",\n hint: \"Next.js App Router\",\n isConfigured: false, // TODO: detect if overlay is installed\n });\n }\n\n // Add Vite apps\n for (const app of project.viteApps) {\n const relativePath = app.projectPath.replace(project.workspaceRoot + \"/\", \"\");\n projects.push({\n id: `vite:${app.projectPath}`,\n name: relativePath || \".\",\n path: app.projectPath,\n type: \"vite\",\n hint: \"Vite + React\",\n isConfigured: false,\n });\n }\n\n return projects;\n}\n\nfunction FrameworkBadge({ type }: { type: DetectedProject[\"type\"] }): React.ReactElement {\n switch (type) {\n case \"nextjs\":\n return <Text color=\"white\" backgroundColor=\"black\"> Next.js </Text>;\n case \"vite\":\n return <Text color=\"black\" backgroundColor=\"yellow\"> Vite </Text>;\n default:\n return <Text dimColor>Other</Text>;\n }\n}\n\nexport function ProjectSelector({\n projects,\n onSelect,\n onCancel,\n}: ProjectSelectorProps): React.ReactElement {\n const { exit } = useApp();\n const [cursor, setCursor] = useState(0);\n\n useInput((input, key) => {\n if (key.upArrow) {\n setCursor((prev) => (prev > 0 ? prev - 1 : projects.length - 1));\n } else if (key.downArrow) {\n setCursor((prev) => (prev < projects.length - 1 ? prev + 1 : 0));\n } else if (key.return) {\n const selected = projects[cursor];\n if (selected) {\n onSelect(selected);\n }\n } else if (input === \"q\" || key.escape) {\n onCancel?.();\n exit();\n }\n });\n\n if (projects.length === 0) {\n return (\n <Box flexDirection=\"column\">\n <Text color=\"yellow\">No projects detected.</Text>\n <Text dimColor>\n UILint works with Next.js (App Router) and Vite + React projects.\n </Text>\n </Box>\n );\n }\n\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold>Select a project to configure:</Text>\n </Box>\n\n {projects.map((project, index) => {\n const isCursor = index === cursor;\n return (\n <Box key={project.id} paddingLeft={1}>\n {/* Cursor */}\n <Text color={isCursor ? \"cyan\" : undefined}>\n {isCursor ? \"› \" : \" \"}\n </Text>\n\n {/* Framework badge */}\n <Box width={12}>\n <FrameworkBadge type={project.type} />\n </Box>\n\n {/* Project name */}\n <Box width={30}>\n <Text color={isCursor ? \"cyan\" : undefined} bold={isCursor}>\n {project.name}\n </Text>\n </Box>\n\n {/* Status */}\n {project.isConfigured && (\n <Text color=\"green\" dimColor>\n configured\n </Text>\n )}\n </Box>\n );\n })}\n\n {/* Footer */}\n <Box marginTop={1} borderStyle=\"single\" borderColor=\"gray\" paddingX={1}>\n <Text dimColor>\n <Text color=\"cyan\">↑↓</Text> navigate{\" \"}\n <Text color=\"cyan\">enter</Text> select{\" \"}\n <Text color=\"cyan\">q</Text> quit\n </Text>\n </Box>\n </Box>\n );\n}\n","/**\n * Configuration item for the installer dashboard\n */\n\nimport React, { useState, useCallback } from \"react\";\nimport { Box, Text, useInput, useApp } from \"ink\";\n\nexport type ItemStatus = \"installed\" | \"not_installed\" | \"selected\" | \"partial\";\n\nexport interface ConfigItem {\n /** Unique ID */\n id: string;\n /** Display label */\n label: string;\n /** Optional description/hint */\n hint?: string;\n /** Current installation status */\n status: ItemStatus;\n /** Category/group this item belongs to */\n category: string;\n /** Icon for the category */\n categoryIcon?: string;\n /** Whether this item can be toggled */\n disabled?: boolean;\n}\n\nexport interface ConfigSelectorProps {\n items: ConfigItem[];\n onSubmit: (selectedIds: string[]) => void;\n onCancel?: () => void;\n}\n\nfunction StatusIndicator({ status, isSelected }: { status: ItemStatus; isSelected: boolean }): React.ReactElement {\n if (status === \"installed\") {\n return <Text color=\"green\">✓</Text>;\n }\n if (isSelected || status === \"selected\") {\n return <Text color=\"cyan\">◉</Text>;\n }\n if (status === \"partial\") {\n return <Text color=\"yellow\">◐</Text>;\n }\n return <Text dimColor>○</Text>;\n}\n\nfunction StatusLabel({ status }: { status: ItemStatus }): React.ReactElement {\n if (status === \"installed\") {\n return <Text color=\"green\" dimColor>installed</Text>;\n }\n if (status === \"partial\") {\n return <Text color=\"yellow\" dimColor>partial</Text>;\n }\n return <Text dimColor>-</Text>;\n}\n\nexport function ConfigSelector({\n items,\n onSubmit,\n onCancel,\n}: ConfigSelectorProps): React.ReactElement {\n const { exit } = useApp();\n const [cursor, setCursor] = useState(0);\n const [selected, setSelected] = useState<Set<string>>(() => {\n // Pre-select items that aren't installed\n return new Set(\n items\n .filter((item) => item.status !== \"installed\" && !item.disabled)\n .map((item) => item.id)\n );\n });\n\n // Group items by category\n const categories = Array.from(new Set(items.map((item) => item.category)));\n const itemsByCategory = new Map<string, ConfigItem[]>();\n for (const cat of categories) {\n itemsByCategory.set(cat, items.filter((item) => item.category === cat));\n }\n\n // Flatten for navigation\n const flatItems = items;\n\n const handleToggle = useCallback(() => {\n const item = flatItems[cursor];\n if (!item || item.disabled || item.status === \"installed\") return;\n\n setSelected((prev) => {\n const next = new Set(prev);\n if (next.has(item.id)) {\n next.delete(item.id);\n } else {\n next.add(item.id);\n }\n return next;\n });\n }, [cursor, flatItems]);\n\n useInput((input, key) => {\n if (key.upArrow) {\n setCursor((prev) => (prev > 0 ? prev - 1 : flatItems.length - 1));\n } else if (key.downArrow) {\n setCursor((prev) => (prev < flatItems.length - 1 ? prev + 1 : 0));\n } else if (input === \" \") {\n handleToggle();\n } else if (key.return) {\n onSubmit(Array.from(selected));\n } else if (input === \"q\" || key.escape) {\n onCancel?.();\n exit();\n } else if (input === \"a\") {\n // Select all non-installed\n setSelected(\n new Set(\n items\n .filter((item) => item.status !== \"installed\" && !item.disabled)\n .map((item) => item.id)\n )\n );\n } else if (input === \"n\") {\n // Select none\n setSelected(new Set());\n }\n });\n\n let globalIndex = 0;\n\n return (\n <Box flexDirection=\"column\">\n {categories.map((category) => {\n const categoryItems = itemsByCategory.get(category) || [];\n const categoryIcon = categoryItems[0]?.categoryIcon || \"•\";\n\n return (\n <Box key={category} flexDirection=\"column\" marginBottom={1}>\n {/* Category header */}\n <Box>\n <Text bold color=\"white\">\n {categoryIcon} {category}\n </Text>\n </Box>\n\n {/* Category items */}\n {categoryItems.map((item) => {\n const itemIndex = globalIndex++;\n const isCursor = itemIndex === cursor;\n const isItemSelected = selected.has(item.id);\n const isDisabled = item.disabled || item.status === \"installed\";\n\n return (\n <Box key={item.id} paddingLeft={2}>\n {/* Cursor indicator */}\n <Text color={isCursor ? \"cyan\" : undefined}>\n {isCursor ? \"› \" : \" \"}\n </Text>\n\n {/* Status checkbox */}\n <Box width={2}>\n <StatusIndicator status={item.status} isSelected={isItemSelected} />\n </Box>\n\n {/* Label */}\n <Box width={28}>\n <Text\n color={isDisabled ? undefined : isCursor ? \"cyan\" : undefined}\n dimColor={isDisabled}\n >\n {item.label}\n </Text>\n </Box>\n\n {/* Hint */}\n <Box width={20}>\n <Text dimColor>{item.hint || \"\"}</Text>\n </Box>\n\n {/* Status */}\n <StatusLabel status={item.status} />\n </Box>\n );\n })}\n </Box>\n );\n })}\n\n {/* Footer with keyboard hints */}\n <Box marginTop={1} borderStyle=\"single\" borderColor=\"gray\" paddingX={1}>\n <Text dimColor>\n <Text color=\"cyan\">↑↓</Text> navigate{\" \"}\n <Text color=\"cyan\">space</Text> toggle{\" \"}\n <Text color=\"cyan\">a</Text> all{\" \"}\n <Text color=\"cyan\">n</Text> none{\" \"}\n <Text color=\"cyan\">enter</Text> apply{\" \"}\n <Text color=\"cyan\">q</Text> quit\n </Text>\n </Box>\n\n {/* Selection summary */}\n <Box marginTop={1}>\n <Text>\n <Text color=\"cyan\">{selected.size}</Text>\n <Text dimColor> item{selected.size !== 1 ? \"s\" : \"\"} selected</Text>\n </Text>\n </Box>\n </Box>\n );\n}\n","/**\n * RuleSelector - ESLint rule configuration UI\n *\n * Shows a list of available ESLint rules with:\n * - Toggle to enable/disable each rule\n * - Severity selection (error/warn)\n * - Rule documentation on hover/select\n */\n\nimport React, { useState, useMemo } from \"react\";\nimport { Box, Text, useInput, useApp } from \"ink\";\nimport { ruleRegistry, getRulesByCategory } from \"uilint-eslint\";\nimport type { RuleMeta } from \"uilint-eslint\";\n\nexport interface ConfiguredRule {\n rule: RuleMeta;\n severity: \"error\" | \"warn\" | \"off\";\n options?: unknown[];\n}\n\nexport interface RuleSelectorProps {\n onSubmit: (configuredRules: ConfiguredRule[]) => void;\n onBack?: () => void;\n onCancel?: () => void;\n}\n\ntype ViewMode = \"list\" | \"docs\";\n\nfunction SeverityBadge({ severity }: { severity: \"error\" | \"warn\" | \"off\" }): React.ReactElement {\n if (severity === \"error\") {\n return <Text color=\"red\">error</Text>;\n }\n if (severity === \"warn\") {\n return <Text color=\"yellow\">warn</Text>;\n }\n return <Text dimColor>off</Text>;\n}\n\nfunction CategoryHeader({ name, icon }: { name: string; icon: string }): React.ReactElement {\n return (\n <Box marginTop={1} marginBottom={0}>\n <Text bold color=\"white\">\n {icon} {name}\n </Text>\n </Box>\n );\n}\n\nexport function RuleSelector({\n onSubmit,\n onBack,\n onCancel,\n}: RuleSelectorProps): React.ReactElement {\n const { exit } = useApp();\n\n const staticRules = useMemo(() => getRulesByCategory(\"static\"), []);\n const semanticRules = useMemo(() => getRulesByCategory(\"semantic\"), []);\n const allRules = useMemo(() => [...staticRules, ...semanticRules], [staticRules, semanticRules]);\n\n const [cursor, setCursor] = useState(0);\n const [viewMode, setViewMode] = useState<ViewMode>(\"list\");\n\n // Track enabled state and severity for each rule\n const [ruleStates, setRuleStates] = useState<Map<string, { enabled: boolean; severity: \"error\" | \"warn\" }>>(\n () => {\n const map = new Map();\n // Default: all static rules enabled with their default severity\n for (const rule of staticRules) {\n map.set(rule.id, {\n enabled: true,\n severity: rule.defaultSeverity === \"off\" ? \"warn\" : rule.defaultSeverity\n });\n }\n // Semantic rules disabled by default (require Ollama)\n for (const rule of semanticRules) {\n map.set(rule.id, {\n enabled: false,\n severity: rule.defaultSeverity === \"off\" ? \"warn\" : rule.defaultSeverity\n });\n }\n return map;\n }\n );\n\n const currentRule = allRules[cursor];\n const currentState = currentRule ? ruleStates.get(currentRule.id) : undefined;\n\n const toggleRule = () => {\n if (!currentRule) return;\n setRuleStates((prev) => {\n const next = new Map(prev);\n const current = next.get(currentRule.id)!;\n next.set(currentRule.id, { ...current, enabled: !current.enabled });\n return next;\n });\n };\n\n const cycleSeverity = () => {\n if (!currentRule) return;\n setRuleStates((prev) => {\n const next = new Map(prev);\n const current = next.get(currentRule.id)!;\n const newSeverity = current.severity === \"error\" ? \"warn\" : \"error\";\n next.set(currentRule.id, { ...current, severity: newSeverity });\n return next;\n });\n };\n\n const handleSubmit = () => {\n const configuredRules: ConfiguredRule[] = [];\n for (const rule of allRules) {\n const state = ruleStates.get(rule.id);\n if (state?.enabled) {\n configuredRules.push({\n rule,\n severity: state.severity,\n options: rule.defaultOptions,\n });\n }\n }\n onSubmit(configuredRules);\n };\n\n useInput((input, key) => {\n if (viewMode === \"docs\") {\n // In docs view, any key returns to list\n if (key.escape || key.return || input === \"d\" || input === \"q\") {\n setViewMode(\"list\");\n }\n return;\n }\n\n // List view controls\n if (key.upArrow) {\n setCursor((prev) => (prev > 0 ? prev - 1 : allRules.length - 1));\n } else if (key.downArrow) {\n setCursor((prev) => (prev < allRules.length - 1 ? prev + 1 : 0));\n } else if (input === \" \") {\n toggleRule();\n } else if (input === \"s\") {\n cycleSeverity();\n } else if (input === \"d\") {\n setViewMode(\"docs\");\n } else if (key.return) {\n handleSubmit();\n } else if (key.escape || input === \"q\") {\n onCancel?.();\n exit();\n } else if ((input === \"b\" || key.leftArrow) && onBack) {\n onBack();\n } else if (input === \"a\") {\n // Enable all\n setRuleStates((prev) => {\n const next = new Map(prev);\n for (const rule of allRules) {\n const current = next.get(rule.id)!;\n next.set(rule.id, { ...current, enabled: true });\n }\n return next;\n });\n } else if (input === \"n\") {\n // Disable all\n setRuleStates((prev) => {\n const next = new Map(prev);\n for (const rule of allRules) {\n const current = next.get(rule.id)!;\n next.set(rule.id, { ...current, enabled: false });\n }\n return next;\n });\n }\n });\n\n // Show documentation view\n if (viewMode === \"docs\" && currentRule) {\n const docLines = currentRule.docs.trim().split(\"\\n\").slice(0, 20);\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold color=\"cyan\">{currentRule.name}</Text>\n <Text dimColor> - {currentRule.description}</Text>\n </Box>\n\n <Box flexDirection=\"column\" borderStyle=\"single\" borderColor=\"gray\" paddingX={1}>\n {docLines.map((line, i) => (\n <Text key={i} dimColor={line.startsWith(\"#\")}>\n {line}\n </Text>\n ))}\n {currentRule.docs.split(\"\\n\").length > 20 && (\n <Text dimColor>... (truncated)</Text>\n )}\n </Box>\n\n <Box marginTop={1}>\n <Text dimColor>\n Press any key to return to list\n </Text>\n </Box>\n </Box>\n );\n }\n\n // Count enabled rules\n const enabledCount = Array.from(ruleStates.values()).filter((s) => s.enabled).length;\n const errorCount = Array.from(ruleStates.entries()).filter(\n ([id, s]) => s.enabled && s.severity === \"error\"\n ).length;\n const warnCount = enabledCount - errorCount;\n\n // Build flat list with category markers\n let globalIndex = 0;\n\n return (\n <Box flexDirection=\"column\">\n <Box marginBottom={1}>\n <Text bold>Configure ESLint Rules</Text>\n </Box>\n\n {/* Static rules */}\n <CategoryHeader name=\"Static Rules\" icon=\"📋\" />\n <Text dimColor> Pattern-based, fast analysis</Text>\n\n {staticRules.map((rule) => {\n const itemIndex = globalIndex++;\n const isCursor = itemIndex === cursor;\n const state = ruleStates.get(rule.id)!;\n\n return (\n <Box key={rule.id} paddingLeft={2}>\n <Text color={isCursor ? \"cyan\" : undefined}>\n {isCursor ? \"› \" : \" \"}\n </Text>\n <Box width={3}>\n <Text color={state.enabled ? \"green\" : undefined} dimColor={!state.enabled}>\n {state.enabled ? \"✓\" : \"○\"}\n </Text>\n </Box>\n <Box width={30}>\n <Text\n color={isCursor ? \"cyan\" : undefined}\n dimColor={!state.enabled}\n bold={isCursor}\n >\n {rule.name}\n </Text>\n </Box>\n <Box width={8}>\n {state.enabled ? (\n <SeverityBadge severity={state.severity} />\n ) : (\n <Text dimColor>-</Text>\n )}\n </Box>\n </Box>\n );\n })}\n\n {/* Semantic rules */}\n <CategoryHeader name=\"Semantic Rules\" icon=\"🧠\" />\n <Text dimColor> LLM-powered analysis (requires Ollama)</Text>\n\n {semanticRules.map((rule) => {\n const itemIndex = globalIndex++;\n const isCursor = itemIndex === cursor;\n const state = ruleStates.get(rule.id)!;\n\n return (\n <Box key={rule.id} paddingLeft={2}>\n <Text color={isCursor ? \"cyan\" : undefined}>\n {isCursor ? \"› \" : \" \"}\n </Text>\n <Box width={3}>\n <Text color={state.enabled ? \"green\" : undefined} dimColor={!state.enabled}>\n {state.enabled ? \"✓\" : \"○\"}\n </Text>\n </Box>\n <Box width={30}>\n <Text\n color={isCursor ? \"cyan\" : undefined}\n dimColor={!state.enabled}\n bold={isCursor}\n >\n {rule.name}\n </Text>\n </Box>\n <Box width={8}>\n {state.enabled ? (\n <SeverityBadge severity={state.severity} />\n ) : (\n <Text dimColor>-</Text>\n )}\n </Box>\n </Box>\n );\n })}\n\n {/* Current rule description */}\n {currentRule && (\n <Box marginTop={1} paddingX={2}>\n <Text dimColor>{currentRule.description}</Text>\n </Box>\n )}\n\n {/* Footer with keyboard hints */}\n <Box marginTop={1} borderStyle=\"single\" borderColor=\"gray\" paddingX={1}>\n <Text dimColor>\n <Text color=\"cyan\">↑↓</Text> navigate{\" \"}\n <Text color=\"cyan\">space</Text> toggle{\" \"}\n <Text color=\"cyan\">s</Text> severity{\" \"}\n <Text color=\"cyan\">d</Text> docs{\" \"}\n <Text color=\"cyan\">a</Text> all{\" \"}\n <Text color=\"cyan\">n</Text> none{\" \"}\n <Text color=\"cyan\">enter</Text> confirm\n </Text>\n </Box>\n\n {/* Summary */}\n <Box marginTop={1}>\n <Text>\n <Text color=\"cyan\">{enabledCount}</Text>\n <Text dimColor> rules enabled (</Text>\n <Text color=\"red\">{errorCount}</Text>\n <Text dimColor> errors, </Text>\n <Text color=\"yellow\">{warnCount}</Text>\n <Text dimColor> warnings)</Text>\n </Text>\n </Box>\n </Box>\n );\n}\n","/**\n * Installer registry - central registration point for all installers\n *\n * Installers self-register here to be available in the install flow.\n */\n\nimport type { Installer } from \"./types.js\";\n\n/**\n * Global registry of all installers\n */\nconst installers: Installer[] = [];\n\n/**\n * Register an installer\n * @param installer - Installer to register\n */\nexport function registerInstaller(installer: Installer): void {\n // Prevent duplicate registrations\n if (installers.some((i) => i.id === installer.id)) {\n console.warn(`Installer \"${installer.id}\" is already registered`);\n return;\n }\n installers.push(installer);\n}\n\n/**\n * Get all registered installers\n * @returns Array of all installers\n */\nexport function getAllInstallers(): readonly Installer[] {\n return installers;\n}\n\n/**\n * Get installer by ID\n * @param id - Installer ID\n * @returns Installer or undefined if not found\n */\nexport function getInstallerById(id: string): Installer | undefined {\n return installers.find((i) => i.id === id);\n}\n\n/**\n * Clear all registered installers (for testing)\n */\nexport function clearInstallers(): void {\n installers.length = 0;\n}\n","/**\n * Analyze phase - scan project and return ProjectState\n *\n * This is a pure scanning function with no prompts or mutations.\n * It aggregates detection from existing utilities to build a complete\n * picture of the project state.\n */\n\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { findWorkspaceRoot } from \"uilint-core/node\";\nimport {\n detectNextAppRouter,\n findNextAppRouterProjects,\n} from \"../../utils/next-detect.js\";\nimport {\n detectViteReact,\n findViteReactProjects,\n} from \"../../utils/vite-detect.js\";\nimport { findPackages } from \"../../utils/package-detect.js\";\nimport { detectPackageManager } from \"../../utils/package-manager.js\";\nimport {\n findEslintConfigFile,\n getEslintConfigFilename,\n getUilintEslintConfigInfoFromSource,\n} from \"../../utils/eslint-config-inject.js\";\nimport type {\n ProjectState,\n EslintPackageInfo,\n NextAppInfo,\n ViteAppInfo,\n} from \"./types.js\";\n\n// NOTE: uilint rule detection must ignore commented-out keys and handle spreads.\n// We re-use the AST-backed detector from eslint-config-inject.\n\n/**\n * Safely parse JSON file, returning undefined on error\n */\nfunction safeParseJson<T>(filePath: string): T | undefined {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n return JSON.parse(content) as T;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Analyze a project and return its state\n *\n * @param projectPath - The project directory to analyze (defaults to cwd)\n * @returns ProjectState describing what exists in the project\n */\nexport async function analyze(\n projectPath: string = process.cwd()\n): Promise<ProjectState> {\n // Find workspace root (may differ from projectPath in monorepos)\n const workspaceRoot = findWorkspaceRoot(projectPath);\n\n // Detect package manager\n const packageManager = detectPackageManager(projectPath);\n\n // .cursor directory\n const cursorDir = join(projectPath, \".cursor\");\n const cursorDirExists = existsSync(cursorDir);\n\n // Styleguide\n const styleguidePath = join(projectPath, \".uilint\", \"styleguide.md\");\n const styleguideExists = existsSync(styleguidePath);\n\n // Cursor commands\n const commandsDir = join(cursorDir, \"commands\");\n const genstyleguideExists = existsSync(join(commandsDir, \"genstyleguide.md\"));\n\n // Detect Next.js App Router projects\n const nextApps: NextAppInfo[] = [];\n const directDetection = detectNextAppRouter(projectPath);\n if (directDetection) {\n nextApps.push({ projectPath, detection: directDetection });\n } else {\n // Search in workspace for Next.js apps\n const matches = findNextAppRouterProjects(workspaceRoot, { maxDepth: 5 });\n for (const match of matches) {\n nextApps.push({\n projectPath: match.projectPath,\n detection: match.detection,\n });\n }\n }\n\n // Detect Vite + React projects\n const viteApps: ViteAppInfo[] = [];\n const directVite = detectViteReact(projectPath);\n if (directVite) {\n viteApps.push({ projectPath, detection: directVite });\n } else {\n const matches = findViteReactProjects(workspaceRoot, { maxDepth: 5 });\n for (const match of matches) {\n viteApps.push({\n projectPath: match.projectPath,\n detection: match.detection,\n });\n }\n }\n\n // Find all packages and enrich with ESLint info\n const rawPackages = findPackages(workspaceRoot);\n const packages: EslintPackageInfo[] = rawPackages.map((pkg) => {\n const eslintConfigPath = findEslintConfigFile(pkg.path);\n let eslintConfigFilename: string | null = null;\n let hasRules = false;\n let configuredRuleIds: string[] = [];\n\n if (eslintConfigPath) {\n eslintConfigFilename = getEslintConfigFilename(eslintConfigPath);\n try {\n const source = readFileSync(eslintConfigPath, \"utf-8\");\n const info = getUilintEslintConfigInfoFromSource(source);\n hasRules = info.configuredRuleIds.size > 0;\n configuredRuleIds = Array.from(info.configuredRuleIds);\n } catch {\n // Ignore read errors\n }\n }\n\n return {\n ...pkg,\n eslintConfigPath,\n eslintConfigFilename,\n hasUilintRules: hasRules,\n configuredRuleIds,\n };\n });\n\n return {\n projectPath,\n workspaceRoot,\n packageManager,\n cursorDir: {\n exists: cursorDirExists,\n path: cursorDir,\n },\n styleguide: {\n exists: styleguideExists,\n path: styleguidePath,\n },\n commands: {\n genstyleguide: genstyleguideExists,\n },\n nextApps,\n viteApps,\n packages,\n };\n}\n","import { existsSync, readdirSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\n\nexport interface ViteReactDetection {\n /**\n * Relative path to the Vite config file (e.g. \"vite.config.ts\").\n */\n configFile: string;\n /**\n * Absolute path to the Vite config file.\n */\n configFileAbs: string;\n /**\n * Relative path to the source root (usually \"src\").\n */\n entryRoot: string;\n /**\n * Candidate entry files (relative paths) that are good injection targets.\n * For Vite+React this is usually `src/main.*`.\n */\n candidates: string[];\n}\n\nconst VITE_CONFIG_EXTS = [\".ts\", \".mjs\", \".js\", \".cjs\"];\n\nfunction findViteConfigFile(projectPath: string): string | null {\n for (const ext of VITE_CONFIG_EXTS) {\n const rel = `vite.config${ext}`;\n if (existsSync(join(projectPath, rel))) return rel;\n }\n return null;\n}\n\nfunction looksLikeReactPackage(projectPath: string): boolean {\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n return \"react\" in deps || \"react-dom\" in deps;\n } catch {\n return false;\n }\n}\n\nfunction fileExists(projectPath: string, relPath: string): boolean {\n return existsSync(join(projectPath, relPath));\n}\n\nexport function detectViteReact(projectPath: string): ViteReactDetection | null {\n const configFile = findViteConfigFile(projectPath);\n if (!configFile) return null;\n\n // Overlay integration currently targets React apps.\n if (!looksLikeReactPackage(projectPath)) return null;\n\n // Prefer Vite defaults: src/main.(tsx|jsx|ts|js)\n const entryRoot = \"src\";\n const candidates: string[] = [];\n const entryCandidates = [\n join(entryRoot, \"main.tsx\"),\n join(entryRoot, \"main.jsx\"),\n join(entryRoot, \"main.ts\"),\n join(entryRoot, \"main.js\"),\n ];\n\n for (const rel of entryCandidates) {\n if (fileExists(projectPath, rel)) candidates.push(rel);\n }\n\n // If no main.* exists, try common fallbacks (some templates render in App.tsx)\n const fallbackCandidates = [\n join(entryRoot, \"App.tsx\"),\n join(entryRoot, \"App.jsx\"),\n ];\n for (const rel of fallbackCandidates) {\n if (!candidates.includes(rel) && fileExists(projectPath, rel)) {\n candidates.push(rel);\n }\n }\n\n return {\n configFile,\n configFileAbs: join(projectPath, configFile),\n entryRoot,\n candidates,\n };\n}\n\nexport interface ViteReactProjectMatch {\n /**\n * Absolute path to the Vite project root (dir containing vite.config.*).\n */\n projectPath: string;\n detection: ViteReactDetection;\n}\n\nconst DEFAULT_IGNORE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \".next\",\n \"dist\",\n \"build\",\n \"out\",\n \".turbo\",\n \".vercel\",\n \".cursor\",\n \"coverage\",\n \".uilint\",\n]);\n\n/**\n * Best-effort monorepo discovery for Vite + React apps.\n *\n * Walks down from `rootDir` looking for directories that contain `vite.config.*`\n * and whose package.json looks like a React project.\n */\nexport function findViteReactProjects(\n rootDir: string,\n options?: { maxDepth?: number; ignoreDirs?: Set<string> }\n): ViteReactProjectMatch[] {\n const maxDepth = options?.maxDepth ?? 4;\n const ignoreDirs = options?.ignoreDirs ?? DEFAULT_IGNORE_DIRS;\n const results: ViteReactProjectMatch[] = [];\n const visited = new Set<string>();\n\n function walk(dir: string, depth: number) {\n if (depth > maxDepth) return;\n if (visited.has(dir)) return;\n visited.add(dir);\n\n const detection = detectViteReact(dir);\n if (detection) {\n results.push({ projectPath: dir, detection });\n return;\n }\n\n let entries: Array<{ name: string; isDirectory: boolean }> = [];\n try {\n entries = readdirSync(dir, { withFileTypes: true }).map((d) => ({\n name: d.name,\n isDirectory: d.isDirectory(),\n }));\n } catch {\n return;\n }\n\n for (const ent of entries) {\n if (!ent.isDirectory) continue;\n if (ignoreDirs.has(ent.name)) continue;\n if (ent.name.startsWith(\".\") && ent.name !== \".\") continue;\n walk(join(dir, ent.name), depth + 1);\n }\n }\n\n walk(rootDir, 0);\n return results;\n}\n","/**\n * Package.json detection utilities for monorepo discovery\n */\n\nimport { existsSync, readdirSync, readFileSync } from \"fs\";\nimport { join, relative } from \"path\";\n\nexport interface PackageInfo {\n /** Absolute path to the package directory */\n path: string;\n /** Display name (relative path from workspace root) */\n displayPath: string;\n /** Package name from package.json */\n name: string;\n /** Whether this package has ESLint config */\n hasEslintConfig: boolean;\n /** Whether this appears to be a frontend/UI package */\n isFrontend: boolean;\n /** Whether this is the workspace root */\n isRoot: boolean;\n /** Whether this package uses TypeScript */\n isTypeScript: boolean;\n}\n\nconst DEFAULT_IGNORE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \".next\",\n \"dist\",\n \"build\",\n \"out\",\n \".turbo\",\n \".vercel\",\n \".cursor\",\n \"coverage\",\n \".uilint\",\n \".pnpm\",\n]);\n\nconst ESLINT_CONFIG_FILES = [\n \"eslint.config.js\",\n \"eslint.config.ts\",\n \"eslint.config.mjs\",\n \"eslint.config.cjs\",\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \".eslintrc.json\",\n \".eslintrc.yml\",\n \".eslintrc.yaml\",\n \".eslintrc\",\n];\n\nconst FRONTEND_INDICATORS = [\n \"react\",\n \"react-dom\",\n \"next\",\n \"vue\",\n \"svelte\",\n \"@angular/core\",\n \"solid-js\",\n \"preact\",\n];\n\n/**\n * Check if a package.json indicates a frontend project\n */\nfunction isFrontendPackage(pkgJson: Record<string, unknown>): boolean {\n const deps = {\n ...(pkgJson.dependencies as Record<string, string> | undefined),\n ...(pkgJson.devDependencies as Record<string, string> | undefined),\n };\n\n return FRONTEND_INDICATORS.some((pkg) => pkg in deps);\n}\n\n/**\n * Check if a package uses TypeScript\n */\nfunction isTypeScriptPackage(dir: string, pkgJson: Record<string, unknown>): boolean {\n // Check for tsconfig.json\n if (existsSync(join(dir, \"tsconfig.json\"))) {\n return true;\n }\n\n // Check for typescript in dependencies\n const deps = {\n ...(pkgJson.dependencies as Record<string, string> | undefined),\n ...(pkgJson.devDependencies as Record<string, string> | undefined),\n };\n\n if (\"typescript\" in deps) {\n return true;\n }\n\n // Check ESLint config file extension (if .ts, it's TypeScript)\n for (const configFile of ESLINT_CONFIG_FILES) {\n if (configFile.endsWith(\".ts\") && existsSync(join(dir, configFile))) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Check if directory has ESLint config\n */\nfunction hasEslintConfig(dir: string): boolean {\n for (const file of ESLINT_CONFIG_FILES) {\n if (existsSync(join(dir, file))) {\n return true;\n }\n }\n\n // Also check package.json for eslintConfig field\n try {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n if (pkg.eslintConfig) return true;\n }\n } catch {\n // Ignore parse errors\n }\n\n return false;\n}\n\n/**\n * Find all packages in a workspace that could have ESLint installed\n */\nexport function findPackages(\n rootDir: string,\n options?: { maxDepth?: number; ignoreDirs?: Set<string> }\n): PackageInfo[] {\n const maxDepth = options?.maxDepth ?? 5;\n const ignoreDirs = options?.ignoreDirs ?? DEFAULT_IGNORE_DIRS;\n const results: PackageInfo[] = [];\n const visited = new Set<string>();\n\n function processPackage(dir: string, isRoot: boolean): PackageInfo | null {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n const name = pkg.name || relative(rootDir, dir) || \".\";\n\n return {\n path: dir,\n displayPath: relative(rootDir, dir) || \".\",\n name,\n hasEslintConfig: hasEslintConfig(dir),\n isFrontend: isFrontendPackage(pkg),\n isRoot,\n isTypeScript: isTypeScriptPackage(dir, pkg),\n };\n } catch {\n return null;\n }\n }\n\n function walk(dir: string, depth: number) {\n if (depth > maxDepth) return;\n if (visited.has(dir)) return;\n visited.add(dir);\n\n // Check for package.json in this dir\n const pkg = processPackage(dir, depth === 0);\n if (pkg) {\n results.push(pkg);\n }\n\n // Continue walking (even if we found a package - monorepos have nested packages)\n let entries: Array<{ name: string; isDirectory: boolean }> = [];\n try {\n entries = readdirSync(dir, { withFileTypes: true }).map((d) => ({\n name: d.name,\n isDirectory: d.isDirectory(),\n }));\n } catch {\n return;\n }\n\n for (const ent of entries) {\n if (!ent.isDirectory) continue;\n if (ignoreDirs.has(ent.name)) continue;\n if (ent.name.startsWith(\".\")) continue;\n walk(join(dir, ent.name), depth + 1);\n }\n }\n\n walk(rootDir, 0);\n\n // Sort: frontend packages first, then by path\n return results.sort((a, b) => {\n // Root package first\n if (a.isRoot && !b.isRoot) return -1;\n if (!a.isRoot && b.isRoot) return 1;\n // Frontend packages next\n if (a.isFrontend && !b.isFrontend) return -1;\n if (!a.isFrontend && b.isFrontend) return 1;\n // Then alphabetically by path\n return a.displayPath.localeCompare(b.displayPath);\n });\n}\n\n/**\n * Format package info for display in selection menu\n */\nexport function formatPackageOption(pkg: PackageInfo): {\n value: string;\n label: string;\n hint?: string;\n} {\n const hints: string[] = [];\n\n if (pkg.isRoot) hints.push(\"workspace root\");\n if (pkg.isFrontend) hints.push(\"frontend\");\n if (pkg.hasEslintConfig) hints.push(\"has ESLint config\");\n\n return {\n value: pkg.path,\n label:\n pkg.displayPath === \".\" ? pkg.name : `${pkg.name} (${pkg.displayPath})`,\n hint: hints.length > 0 ? hints.join(\", \") : undefined,\n };\n}\n","import { existsSync } from \"fs\";\nimport { spawn } from \"child_process\";\nimport { dirname, join } from \"path\";\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"npm\" | \"bun\";\n\n/**\n * Detect which package manager was used to execute the current command.\n * This helps identify when a user runs `npx uilint install` in a yarn/pnpm project.\n *\n * Detection uses npm_execpath env var which is set by npm/yarn/pnpm when running scripts.\n * When using npx, npm_config_user_agent is also available.\n */\nexport function detectExecutionPackageManager(): PackageManager | null {\n // npm_config_user_agent is set by npm/yarn/pnpm/bun\n // e.g., \"npm/10.2.0 node/v20.0.0 darwin arm64\"\n // e.g., \"yarn/1.22.0 npm/? node/v20.0.0 darwin arm64\"\n // e.g., \"pnpm/8.6.0 npm/? node/v20.0.0 darwin arm64\"\n const userAgent = process.env.npm_config_user_agent;\n if (userAgent) {\n if (userAgent.startsWith(\"pnpm/\")) return \"pnpm\";\n if (userAgent.startsWith(\"yarn/\")) return \"yarn\";\n if (userAgent.startsWith(\"bun/\")) return \"bun\";\n if (userAgent.startsWith(\"npm/\")) return \"npm\";\n }\n\n // Fallback: check npm_execpath which contains the path to npm/yarn/pnpm binary\n const execPath = process.env.npm_execpath;\n if (execPath) {\n if (execPath.includes(\"pnpm\")) return \"pnpm\";\n if (execPath.includes(\"yarn\")) return \"yarn\";\n if (execPath.includes(\"bun\")) return \"bun\";\n if (execPath.includes(\"npm\")) return \"npm\";\n }\n\n return null;\n}\n\nexport function detectPackageManager(projectPath: string): PackageManager {\n // Monorepo-friendly detection: walk up to find the lockfile/workspace marker.\n let dir = projectPath;\n for (;;) {\n // pnpm\n if (existsSync(join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (existsSync(join(dir, \"pnpm-workspace.yaml\"))) return \"pnpm\";\n\n // yarn\n if (existsSync(join(dir, \"yarn.lock\"))) return \"yarn\";\n\n // bun\n if (existsSync(join(dir, \"bun.lockb\"))) return \"bun\";\n if (existsSync(join(dir, \"bun.lock\"))) return \"bun\";\n\n // npm\n if (existsSync(join(dir, \"package-lock.json\"))) return \"npm\";\n\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n // Default: npm (best-effort)\n return \"npm\";\n}\n\nfunction spawnAsync(\n command: string,\n args: string[],\n cwd: string\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n stdio: \"inherit\",\n shell: process.platform === \"win32\",\n });\n\n child.on(\"error\", reject);\n child.on(\"close\", (code) => {\n if (code === 0) resolve();\n else\n reject(new Error(`${command} ${args.join(\" \")} exited with ${code}`));\n });\n });\n}\n\nexport async function installDependencies(\n pm: PackageManager,\n projectPath: string,\n packages: string[]\n): Promise<void> {\n if (!packages.length) return;\n\n switch (pm) {\n case \"pnpm\":\n await spawnAsync(\"pnpm\", [\"add\", ...packages], projectPath);\n return;\n case \"yarn\":\n await spawnAsync(\"yarn\", [\"add\", ...packages], projectPath);\n return;\n case \"bun\":\n await spawnAsync(\"bun\", [\"add\", ...packages], projectPath);\n return;\n case \"npm\":\n default:\n await spawnAsync(\"npm\", [\"install\", \"--save\", ...packages], projectPath);\n return;\n }\n}\n","/**\n * Inject uilint-eslint rules into ESLint config\n *\n * Modifies eslint.config.{ts,mjs,js,cjs} to add uilint import and selected rules\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { join, relative, dirname } from \"path\";\nimport type { RuleMetadata } from \"uilint-eslint\";\nimport { parseExpression, parseModule, generateCode } from \"magicast\";\nimport { findWorkspaceRoot } from \"uilint-core/node\";\n\nexport interface InstallEslintPluginOptions {\n projectPath: string;\n selectedRules: RuleMetadata[];\n force?: boolean;\n confirmAddMissingRules?: (\n relPath: string,\n missingRules: RuleMetadata[]\n ) => Promise<boolean>;\n}\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".mjs\", \".js\", \".cjs\"];\n\n/**\n * Find the eslint.config file in a project\n */\nexport function findEslintConfigFile(projectPath: string): string | null {\n for (const ext of CONFIG_EXTENSIONS) {\n const configPath = join(projectPath, `eslint.config${ext}`);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n return null;\n}\n\n/**\n * Get the relative config filename for display\n */\nexport function getEslintConfigFilename(configPath: string): string {\n const parts = configPath.split(\"/\");\n return parts[parts.length - 1] || \"eslint.config.mjs\";\n}\n\n/**\n * Check if the source already has uilint rules configured\n */\nfunction hasUilintRules(source: string): boolean {\n return source.includes('\"uilint/') || source.includes(\"'uilint/\");\n}\n\n/**\n * Check if the source already has uilint imported\n */\nfunction hasUilintImport(source: string): boolean {\n return (\n source.includes('from \"uilint-eslint\"') ||\n source.includes(\"from 'uilint-eslint'\") ||\n source.includes('require(\"uilint-eslint\")') ||\n source.includes(\"require('uilint-eslint')\")\n );\n}\n\ntype UilintEslintConfigInfo = {\n /** Set of configured `uilint/*` rule IDs (without the `uilint/` prefix). */\n configuredRuleIds: Set<string>;\n /** Whether config appears to configure uilint rules. */\n configured: boolean;\n};\n\nfunction walkAst(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== \"object\") return;\n visit(node);\n for (const key of Object.keys(node)) {\n const v = (node as any)[key];\n if (!v) continue;\n if (Array.isArray(v)) {\n for (const item of v) walkAst(item, visit);\n } else if (typeof v === \"object\" && v.type) {\n walkAst(v, visit);\n }\n }\n}\n\nfunction isIdentifier(node: any, name?: string): boolean {\n return (\n !!node &&\n node.type === \"Identifier\" &&\n (name ? node.name === name : typeof node.name === \"string\")\n );\n}\n\nfunction isStringLiteral(node: any): node is { type: string; value: string } {\n return (\n !!node &&\n (node.type === \"StringLiteral\" || node.type === \"Literal\") &&\n typeof node.value === \"string\"\n );\n}\n\nfunction getObjectPropertyValue(obj: any, keyName: string): any | null {\n if (!obj || obj.type !== \"ObjectExpression\") return null;\n for (const prop of obj.properties ?? []) {\n if (!prop) continue;\n if (prop.type === \"ObjectProperty\" || prop.type === \"Property\") {\n const key = prop.key;\n const keyMatch =\n (key?.type === \"Identifier\" && key.name === keyName) ||\n (isStringLiteral(key) && key.value === keyName);\n if (keyMatch) return prop.value;\n }\n }\n return null;\n}\n\nfunction hasSpreadProperties(obj: any): boolean {\n if (!obj || obj.type !== \"ObjectExpression\") return false;\n return (obj.properties ?? []).some(\n (p: any) => p && (p.type === \"SpreadElement\" || p.type === \"SpreadProperty\")\n );\n}\n\nconst IGNORED_AST_KEYS = new Set([\n \"loc\",\n \"start\",\n \"end\",\n \"extra\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n]);\n\nfunction normalizeAstForCompare(node: any): any {\n if (node === null) return null;\n if (node === undefined) return undefined;\n if (typeof node !== \"object\") return node;\n if (Array.isArray(node)) return node.map(normalizeAstForCompare);\n\n const out: Record<string, any> = {};\n const keys = Object.keys(node)\n .filter((k) => !IGNORED_AST_KEYS.has(k))\n .sort();\n for (const k of keys) {\n // Avoid proxy-ish or non-serializable fields if present.\n if (k.startsWith(\"$\")) continue;\n out[k] = normalizeAstForCompare(node[k]);\n }\n return out;\n}\n\nfunction astEquivalent(a: any, b: any): boolean {\n try {\n return (\n JSON.stringify(normalizeAstForCompare(a)) ===\n JSON.stringify(normalizeAstForCompare(b))\n );\n } catch {\n return false;\n }\n}\n\nfunction collectUilintRuleIdsFromRulesObject(rulesObj: any): Set<string> {\n const ids = new Set<string>();\n if (!rulesObj || rulesObj.type !== \"ObjectExpression\") return ids;\n for (const prop of rulesObj.properties ?? []) {\n if (!prop) continue;\n if (prop.type !== \"ObjectProperty\" && prop.type !== \"Property\") continue;\n const key = prop.key;\n if (!isStringLiteral(key)) continue;\n const val = key.value;\n if (typeof val !== \"string\") continue;\n if (val.startsWith(\"uilint/\")) {\n ids.add(val.slice(\"uilint/\".length));\n }\n }\n return ids;\n}\n\nfunction findExportedConfigArrayExpression(mod: any): {\n kind: \"esm\" | \"cjs\";\n arrayExpr: any;\n program: any;\n} | null {\n function unwrapExpression(expr: any): any {\n let e = expr;\n // Best-effort unwrap for TS/parenthesized wrappers. (These can appear if the\n // config is authored in TS/JS with type assertions or parentheses.)\n while (e) {\n if (e.type === \"TSAsExpression\" || e.type === \"TSNonNullExpression\") {\n e = e.expression;\n continue;\n }\n if (e.type === \"TSSatisfiesExpression\") {\n e = e.expression;\n continue;\n }\n if (e.type === \"ParenthesizedExpression\") {\n e = e.expression;\n continue;\n }\n break;\n }\n return e;\n }\n\n function resolveTopLevelIdentifierToArrayExpr(\n program: any,\n name: string\n ): any | null {\n if (!program || program.type !== \"Program\") return null;\n for (const stmt of program.body ?? []) {\n if (stmt?.type !== \"VariableDeclaration\") continue;\n for (const decl of stmt.declarations ?? []) {\n const id = decl?.id;\n if (!isIdentifier(id, name)) continue;\n const init = unwrapExpression(decl?.init);\n if (!init) return null;\n if (init.type === \"ArrayExpression\") return init;\n if (\n init.type === \"CallExpression\" &&\n isIdentifier(init.callee, \"defineConfig\") &&\n unwrapExpression(init.arguments?.[0])?.type === \"ArrayExpression\"\n ) {\n return unwrapExpression(init.arguments?.[0]);\n }\n return null;\n }\n }\n return null;\n }\n\n // Prefer reading directly from the program AST so we can handle:\n // - export default [ ... ]\n // - export default defineConfig([ ... ])\n // - export default eslintConfig; (where eslintConfig is a top-level array)\n const program = mod?.$ast;\n if (program && program.type === \"Program\") {\n for (const stmt of program.body ?? []) {\n if (!stmt || stmt.type !== \"ExportDefaultDeclaration\") continue;\n const decl = unwrapExpression(stmt.declaration);\n if (!decl) break;\n\n if (decl.type === \"ArrayExpression\") {\n return { kind: \"esm\", arrayExpr: decl, program };\n }\n if (\n decl.type === \"CallExpression\" &&\n isIdentifier(decl.callee, \"defineConfig\") &&\n unwrapExpression(decl.arguments?.[0])?.type === \"ArrayExpression\"\n ) {\n return {\n kind: \"esm\",\n arrayExpr: unwrapExpression(decl.arguments?.[0]),\n program,\n };\n }\n if (decl.type === \"Identifier\" && typeof decl.name === \"string\") {\n const resolved = resolveTopLevelIdentifierToArrayExpr(\n program,\n decl.name\n );\n if (resolved) return { kind: \"esm\", arrayExpr: resolved, program };\n }\n break;\n }\n }\n\n // CommonJS: module.exports = [ ... ] OR module.exports = defineConfig([ ... ])\n if (!program || program.type !== \"Program\") return null;\n\n for (const stmt of program.body ?? []) {\n if (!stmt || stmt.type !== \"ExpressionStatement\") continue;\n const expr = stmt.expression;\n if (!expr || expr.type !== \"AssignmentExpression\") continue;\n const left = expr.left;\n const right = expr.right;\n const isModuleExports =\n left?.type === \"MemberExpression\" &&\n isIdentifier(left.object, \"module\") &&\n isIdentifier(left.property, \"exports\");\n if (!isModuleExports) continue;\n\n if (right?.type === \"ArrayExpression\") {\n return { kind: \"cjs\", arrayExpr: right, program };\n }\n if (\n right?.type === \"CallExpression\" &&\n isIdentifier(right.callee, \"defineConfig\") &&\n right.arguments?.[0]?.type === \"ArrayExpression\"\n ) {\n return { kind: \"cjs\", arrayExpr: right.arguments[0], program };\n }\n if (right?.type === \"Identifier\" && typeof right.name === \"string\") {\n const resolved = resolveTopLevelIdentifierToArrayExpr(\n program,\n right.name\n );\n if (resolved) return { kind: \"cjs\", arrayExpr: resolved, program };\n }\n }\n\n return null;\n}\n\nfunction collectConfiguredUilintRuleIdsFromConfigArray(\n arrayExpr: any\n): Set<string> {\n const ids = new Set<string>();\n if (!arrayExpr || arrayExpr.type !== \"ArrayExpression\") return ids;\n for (const el of arrayExpr.elements ?? []) {\n if (!el || el.type !== \"ObjectExpression\") continue;\n const rules = getObjectPropertyValue(el, \"rules\");\n for (const id of collectUilintRuleIdsFromRulesObject(rules)) ids.add(id);\n }\n return ids;\n}\n\nfunction findExistingUilintRulesObject(arrayExpr: any): {\n configObj: any | null;\n rulesObj: any | null;\n safeToMutate: boolean;\n} {\n if (!arrayExpr || arrayExpr.type !== \"ArrayExpression\") {\n return { configObj: null, rulesObj: null, safeToMutate: false };\n }\n\n for (const el of arrayExpr.elements ?? []) {\n if (!el || el.type !== \"ObjectExpression\") continue;\n\n const plugins = getObjectPropertyValue(el, \"plugins\");\n const rules = getObjectPropertyValue(el, \"rules\");\n\n const hasUilintPlugin =\n plugins?.type === \"ObjectExpression\" &&\n getObjectPropertyValue(plugins, \"uilint\") !== null;\n\n const uilintIds = collectUilintRuleIdsFromRulesObject(rules);\n const hasUilintRules = uilintIds.size > 0;\n\n if (!hasUilintPlugin && !hasUilintRules) continue;\n\n const safe =\n rules?.type === \"ObjectExpression\" && !hasSpreadProperties(rules);\n return { configObj: el, rulesObj: rules, safeToMutate: safe };\n }\n\n return { configObj: null, rulesObj: null, safeToMutate: false };\n}\n\nfunction collectTopLevelBindings(program: any): Set<string> {\n const names = new Set<string>();\n if (!program || program.type !== \"Program\") return names;\n\n for (const stmt of program.body ?? []) {\n if (stmt?.type === \"VariableDeclaration\") {\n for (const decl of stmt.declarations ?? []) {\n const id = decl?.id;\n if (id?.type === \"Identifier\" && typeof id.name === \"string\") {\n names.add(id.name);\n }\n }\n } else if (stmt?.type === \"FunctionDeclaration\") {\n if (stmt.id?.type === \"Identifier\" && typeof stmt.id.name === \"string\") {\n names.add(stmt.id.name);\n }\n }\n }\n return names;\n}\n\nfunction chooseUniqueIdentifier(base: string, used: Set<string>): string {\n if (!used.has(base)) return base;\n let i = 2;\n while (used.has(`${base}${i}`)) i++;\n return `${base}${i}`;\n}\n\n/**\n * Add imports for local rules from .uilint/rules/\n */\nfunction addLocalRuleImportsAst(\n mod: any,\n selectedRules: RuleMetadata[],\n configPath: string,\n rulesRoot: string,\n fileExtension: string = \".js\"\n): { importNames: Map<string, string>; changed: boolean } {\n const importNames = new Map<string, string>();\n let changed = false;\n\n // Calculate relative path from config file to .uilint/rules/\n const configDir = dirname(configPath);\n const rulesDir = join(rulesRoot, \".uilint\", \"rules\");\n const relativeRulesPath = relative(configDir, rulesDir).replace(/\\\\/g, \"/\");\n\n // Ensure it starts with ./ or ../ (note: `.foo` is NOT a valid relative import)\n const normalizedRulesPath =\n relativeRulesPath.startsWith(\"./\") || relativeRulesPath.startsWith(\"../\")\n ? relativeRulesPath\n : `./${relativeRulesPath}`;\n\n const used = collectTopLevelBindings(mod.$ast);\n\n for (const rule of selectedRules) {\n // Generate a safe import name (e.g., noArbitraryTailwindRule)\n const importName = chooseUniqueIdentifier(\n `${rule.id\n .replace(/-([a-z])/g, (_: string, c: string) => c.toUpperCase())\n .replace(/^./, (c: string) => c.toUpperCase())}Rule`,\n used\n );\n importNames.set(rule.id, importName);\n used.add(importName);\n\n // Add import statement\n const rulePath = `${normalizedRulesPath}/${rule.id}${fileExtension}`;\n mod.imports.$add({\n imported: \"default\",\n local: importName,\n from: rulePath,\n });\n changed = true;\n }\n\n return { importNames, changed };\n}\n\n/**\n * Add require statements for local rules (CommonJS)\n */\nfunction addLocalRuleRequiresAst(\n program: any,\n selectedRules: RuleMetadata[],\n configPath: string,\n rulesRoot: string,\n fileExtension: string = \".js\"\n): { importNames: Map<string, string>; changed: boolean } {\n const importNames = new Map<string, string>();\n let changed = false;\n\n if (!program || program.type !== \"Program\") {\n return { importNames, changed };\n }\n\n // Calculate relative path from config file to .uilint/rules/\n const configDir = dirname(configPath);\n const rulesDir = join(rulesRoot, \".uilint\", \"rules\");\n const relativeRulesPath = relative(configDir, rulesDir).replace(/\\\\/g, \"/\");\n\n // Ensure it starts with ./ or ../ (note: `.foo` is NOT a valid relative require)\n const normalizedRulesPath =\n relativeRulesPath.startsWith(\"./\") || relativeRulesPath.startsWith(\"../\")\n ? relativeRulesPath\n : `./${relativeRulesPath}`;\n\n const used = collectTopLevelBindings(program);\n\n for (const rule of selectedRules) {\n // Generate a safe import name\n const importName = chooseUniqueIdentifier(\n `${rule.id\n .replace(/-([a-z])/g, (_: string, c: string) => c.toUpperCase())\n .replace(/^./, (c: string) => c.toUpperCase())}Rule`,\n used\n );\n importNames.set(rule.id, importName);\n used.add(importName);\n\n // Add require statement\n const rulePath = `${normalizedRulesPath}/${rule.id}${fileExtension}`;\n const stmtMod = parseModule(\n `const ${importName} = require(\"${rulePath}\");`\n );\n const stmt = (stmtMod.$ast as any).body?.[0];\n if (stmt) {\n // Place after a leading \"use strict\" if present.\n let insertAt = 0;\n const first = program.body?.[0];\n if (\n first?.type === \"ExpressionStatement\" &&\n first.expression?.type === \"StringLiteral\" &&\n first.expression.value === \"use strict\"\n ) {\n insertAt = 1;\n }\n program.body.splice(insertAt, 0, stmt);\n changed = true;\n }\n }\n\n return { importNames, changed };\n}\n\nfunction appendUilintConfigBlockToArray(\n arrayExpr: any,\n selectedRules: RuleMetadata[],\n ruleImportNames: Map<string, string>\n): void {\n // Build plugin object with local rule imports\n const pluginRulesCode = Array.from(ruleImportNames.entries())\n .map(([ruleId, importName]) => ` \"${ruleId}\": ${importName},`)\n .join(\"\\n\");\n\n const rulesPropsCode = selectedRules\n .map((r) => {\n const ruleKey = `uilint/${r.id}`;\n const valueCode =\n r.defaultOptions && r.defaultOptions.length > 0\n ? `[\"${r.defaultSeverity}\", ...${JSON.stringify(\n r.defaultOptions,\n null,\n 2\n )}]`\n : `\"${r.defaultSeverity}\"`;\n return ` \"${ruleKey}\": ${valueCode},`;\n })\n .join(\"\\n\");\n\n const blockCode = `{\n files: [\n \"src/**/*.{js,jsx,ts,tsx}\",\n \"app/**/*.{js,jsx,ts,tsx}\",\n \"pages/**/*.{js,jsx,ts,tsx}\",\n ],\n plugins: {\n uilint: {\n rules: {\n${pluginRulesCode}\n },\n },\n },\n rules: {\n${rulesPropsCode}\n },\n }`;\n\n const objExpr = (parseExpression(blockCode) as any).$ast;\n arrayExpr.elements.push(objExpr);\n}\n\nfunction getUilintEslintConfigInfoFromSourceAst(source: string):\n | {\n info: UilintEslintConfigInfo;\n mod: any;\n arrayExpr: any;\n kind: \"esm\" | \"cjs\";\n }\n | { error: string } {\n try {\n const mod = parseModule(source);\n const found = findExportedConfigArrayExpression(mod);\n if (!found) {\n return {\n error:\n \"Could not locate an exported ESLint flat config array (expected `export default [...]`, `export default defineConfig([...])`, `module.exports = [...]`, or `module.exports = defineConfig([...])`).\",\n };\n }\n\n const configuredRuleIds = collectConfiguredUilintRuleIdsFromConfigArray(\n found.arrayExpr\n );\n const existingUilint = findExistingUilintRulesObject(found.arrayExpr);\n const configured =\n configuredRuleIds.size > 0 || existingUilint.configObj !== null;\n\n return {\n info: { configuredRuleIds, configured },\n mod,\n arrayExpr: found.arrayExpr,\n kind: found.kind,\n };\n } catch {\n return {\n error:\n \"Unable to parse ESLint config as JavaScript. Please update it manually or simplify the config so it can be safely auto-modified.\",\n };\n }\n}\n\nexport function getUilintEslintConfigInfoFromSource(\n source: string\n): UilintEslintConfigInfo {\n const ast = getUilintEslintConfigInfoFromSourceAst(source);\n if (\"error\" in ast) {\n // Fallback (best-effort) to string heuristics for scan-only scenarios.\n const configuredRuleIds = extractConfiguredUilintRuleIds(source);\n return {\n configuredRuleIds,\n configured: configuredRuleIds.size > 0,\n };\n }\n return ast.info;\n}\n\nfunction findEsmExportedConfigArrayStartIndex(source: string): number | null {\n // Supported:\n // - export default [ ... ]\n // - export default defineConfig([ ... ])\n const patterns: RegExp[] = [\n /export\\s+default\\s+\\[/,\n /export\\s+default\\s+defineConfig\\s*\\(\\s*\\[/,\n ];\n\n for (const re of patterns) {\n const m = source.match(re);\n if (!m || m.index === undefined) continue;\n return m.index + m[0].length;\n }\n\n return null;\n}\n\nfunction findCommonJsExportedConfigArrayStartIndex(\n source: string\n): number | null {\n // Supported:\n // - module.exports = [ ... ]\n // - module.exports = defineConfig([ ... ]) (best-effort)\n const patterns: RegExp[] = [\n /module\\.exports\\s*=\\s*\\[/,\n /module\\.exports\\s*=\\s*defineConfig\\s*\\(\\s*\\[/,\n ];\n\n for (const re of patterns) {\n const m = source.match(re);\n if (!m || m.index === undefined) continue;\n return m.index + m[0].length;\n }\n\n return null;\n}\n\n/**\n * Extract configured uilint rule IDs from source.\n * Matches keys like: \"uilint/no-arbitrary-tailwind\": \"error\"\n */\nfunction extractConfiguredUilintRuleIds(source: string): Set<string> {\n const ids = new Set<string>();\n const re = /[\"']uilint\\/([^\"']+)[\"']\\s*:/g;\n for (const m of source.matchAll(re)) {\n if (m[1]) ids.add(m[1]);\n }\n return ids;\n}\n\nfunction getMissingSelectedRules(\n selectedRules: RuleMetadata[],\n configuredIds: Set<string>\n): RuleMetadata[] {\n return selectedRules.filter((r) => !configuredIds.has(r.id));\n}\n\n/**\n * Get rules that exist but need updating (different options or severity)\n */\nfunction buildDesiredRuleValueExpression(rule: RuleMetadata): string {\n if (rule.defaultOptions && rule.defaultOptions.length > 0) {\n // Match the shape we generate elsewhere: [\"severity\", ...[options...]]\n return `[\"${rule.defaultSeverity}\", ...${JSON.stringify(\n rule.defaultOptions,\n null,\n 2\n )}]`;\n }\n return `\"${rule.defaultSeverity}\"`;\n}\n\nfunction collectUilintRuleValueNodesFromConfigArray(\n arrayExpr: any\n): Map<string, any> {\n const out = new Map<string, any>();\n if (!arrayExpr || arrayExpr.type !== \"ArrayExpression\") return out;\n\n for (const el of arrayExpr.elements ?? []) {\n if (!el || el.type !== \"ObjectExpression\") continue;\n const rules = getObjectPropertyValue(el, \"rules\");\n if (!rules || rules.type !== \"ObjectExpression\") continue;\n\n for (const prop of rules.properties ?? []) {\n if (!prop) continue;\n if (prop.type !== \"ObjectProperty\" && prop.type !== \"Property\") continue;\n const key = prop.key;\n if (!isStringLiteral(key)) continue;\n const k = key.value;\n if (typeof k !== \"string\" || !k.startsWith(\"uilint/\")) continue;\n const id = k.slice(\"uilint/\".length);\n // First occurrence wins; that's enough for detecting up-to-date configs.\n if (!out.has(id)) out.set(id, prop.value);\n }\n }\n\n return out;\n}\n\nfunction getRulesNeedingUpdate(\n selectedRules: RuleMetadata[],\n configuredIds: Set<string>,\n arrayExpr: any\n): RuleMetadata[] {\n // Only consider rules that are already configured, and only update if the\n // existing severity/options differ from what we would generate.\n const existingVals = collectUilintRuleValueNodesFromConfigArray(arrayExpr);\n\n return selectedRules.filter((r) => {\n if (!configuredIds.has(r.id)) return false;\n const existing = existingVals.get(r.id);\n if (!existing) return true;\n\n const desiredExpr = buildDesiredRuleValueExpression(r);\n const desiredAst = (parseExpression(desiredExpr) as any).$ast;\n return !astEquivalent(existing, desiredAst);\n });\n}\n\n/**\n * Generate a single rule config string\n */\nfunction generateSingleRuleConfig(rule: RuleMetadata): string {\n const ruleKey = `\"uilint/${rule.id}\"`;\n\n if (rule.defaultOptions && rule.defaultOptions.length > 0) {\n // Rule with options\n const optionsStr = JSON.stringify(rule.defaultOptions, null, 6)\n .split(\"\\n\")\n .join(\"\\n \");\n return ` ${ruleKey}: [\"${rule.defaultSeverity}\", ...${optionsStr}],`;\n } else {\n // Simple rule\n return ` ${ruleKey}: \"${rule.defaultSeverity}\",`;\n }\n}\n\n/**\n * Add the uilint import to the source if not present\n */\nfunction ensureUilintImport(source: string, isCommonJS: boolean): string {\n if (hasUilintImport(source)) {\n return source;\n }\n\n const importLine = isCommonJS\n ? `const uilint = require(\"uilint-eslint\");\\n`\n : `import uilint from \"uilint-eslint\";\\n`;\n\n // Find the last import/require statement and insert after it\n const header = source.slice(0, Math.min(source.length, 5000));\n const importRegex = isCommonJS\n ? /^(?:const|var|let)\\s+.*?=\\s*require\\([^)]+\\);?\\s*$/gm\n : /^import[\\s\\S]*?;\\s*$/gm;\n\n let lastImportEnd = -1;\n for (const m of header.matchAll(importRegex)) {\n lastImportEnd = (m.index ?? 0) + m[0].length;\n }\n\n if (lastImportEnd !== -1) {\n return (\n source.slice(0, lastImportEnd) +\n \"\\n\" +\n importLine +\n source.slice(lastImportEnd)\n );\n }\n\n // No imports found, add at the beginning\n return importLine + source;\n}\n\n/**\n * Generate the rules config object from selected rules\n */\nfunction generateRulesConfig(selectedRules: RuleMetadata[]): string {\n const lines: string[] = [];\n\n for (const rule of selectedRules) {\n const ruleKey = `\"uilint/${rule.id}\"`;\n\n if (rule.defaultOptions && rule.defaultOptions.length > 0) {\n // Rule with options\n const optionsStr = JSON.stringify(rule.defaultOptions, null, 6)\n .split(\"\\n\")\n .join(\"\\n \");\n lines.push(\n ` ${ruleKey}: [\"${rule.defaultSeverity}\", ...${optionsStr}],`\n );\n } else {\n // Simple rule\n lines.push(` ${ruleKey}: \"${rule.defaultSeverity}\",`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction detectIndent(source: string, index: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", index);\n const start = lineStart === -1 ? 0 : lineStart + 1;\n const line = source.slice(start, index);\n const m = line.match(/^\\s*/);\n return m?.[0] ?? \"\";\n}\n\n/**\n * Insert missing uilint rule keys into an existing `rules: { ... }` object\n * that already contains at least one \"uilint/\" key.\n *\n * This is intentionally a best-effort string transform (no JS AST dependency).\n */\nfunction insertMissingRulesIntoExistingRulesObject(\n source: string,\n missingRules: RuleMetadata[]\n): string {\n if (missingRules.length === 0) return source;\n\n // Anchor on an existing uilint rule key, then look backwards for the\n // nearest `rules:` preceding it.\n const uilintKeyMatch = source.match(/[\"']uilint\\/[^\"']+[\"']\\s*:/);\n if (!uilintKeyMatch || uilintKeyMatch.index === undefined) return source;\n\n const uilintKeyIndex = uilintKeyMatch.index;\n const searchStart = Math.max(0, uilintKeyIndex - 4000);\n const before = source.slice(searchStart, uilintKeyIndex);\n const rulesKwIndexRel = before.lastIndexOf(\"rules\");\n if (rulesKwIndexRel === -1) return source;\n\n const rulesKwIndex = searchStart + rulesKwIndexRel;\n const braceOpenIndex = source.indexOf(\"{\", rulesKwIndex);\n if (braceOpenIndex === -1 || braceOpenIndex > uilintKeyIndex) return source;\n\n // Find the matching closing brace for the rules object.\n let depth = 0;\n let braceCloseIndex = -1;\n for (let i = braceOpenIndex; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\") {\n depth--;\n if (depth === 0) {\n braceCloseIndex = i;\n break;\n }\n }\n }\n if (braceCloseIndex === -1) return source;\n\n const rulesIndent = detectIndent(source, braceOpenIndex);\n const entryIndent = rulesIndent + \" \";\n const entryTextRaw = generateRulesConfig(missingRules);\n const entryText = entryTextRaw\n .split(\"\\n\")\n .map((l) => (l.trim().length === 0 ? l : entryIndent + l.trimStart()))\n .join(\"\\n\");\n\n const insertion =\n (source.slice(braceOpenIndex + 1, braceCloseIndex).trim().length === 0\n ? \"\\n\"\n : \"\\n\") +\n entryText +\n \"\\n\" +\n rulesIndent;\n\n return (\n source.slice(0, braceCloseIndex) + insertion + source.slice(braceCloseIndex)\n );\n}\n\n/**\n * Find the end of a rule value in the source code\n * Handles: \"error\", [\"error\"], [\"error\", {...}], [\"error\", ...[{...}]]\n */\nfunction findRuleValueEnd(source: string, startIndex: number): number {\n let pos = startIndex;\n let depth = 0;\n let inString = false;\n let stringChar = \"\";\n let foundArray = false;\n\n while (pos < source.length) {\n const ch = source[pos];\n const prevCh = pos > 0 ? source[pos - 1] : \"\";\n\n // Handle string literals\n if (!inString && (ch === '\"' || ch === \"'\")) {\n inString = true;\n stringChar = ch;\n } else if (inString && ch === stringChar && prevCh !== \"\\\\\") {\n inString = false;\n } else if (!inString) {\n // Track brackets/braces\n if (ch === \"[\") {\n depth++;\n foundArray = true;\n } else if (ch === \"]\") {\n depth--;\n if (depth === 0 && foundArray) {\n // Found the end of the array\n pos++;\n // Skip whitespace and include trailing comma if present\n while (pos < source.length && /\\s/.test(source[pos])) {\n pos++;\n }\n if (pos < source.length && source[pos] === \",\") {\n pos++;\n }\n return pos;\n }\n } else if (ch === \"{\" || ch === \"(\") {\n depth++;\n } else if (ch === \"}\" || ch === \")\") {\n depth--;\n } else if (!foundArray && depth === 0) {\n // Simple string value - ends at comma or closing brace\n if (ch === \",\" || ch === \"}\") {\n return pos + (ch === \",\" ? 1 : 0);\n }\n }\n }\n\n pos++;\n }\n\n return pos;\n}\n\n/**\n * Update existing uilint rule configurations with new options/severity\n *\n * This finds existing rule entries and replaces them with updated configurations.\n * Uses a more robust approach to handle multi-line rules with spread syntax.\n */\nfunction updateExistingRulesWithNewOptions(\n source: string,\n rulesToUpdate: RuleMetadata[]\n): string {\n if (rulesToUpdate.length === 0) return source;\n\n let updated = source;\n\n // Process rules in reverse order to avoid index shifting issues\n for (let i = rulesToUpdate.length - 1; i >= 0; i--) {\n const rule = rulesToUpdate[i]!;\n const ruleKeyPattern = new RegExp(\n `[\"']uilint/${rule.id.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']\\\\s*:`,\n \"g\"\n );\n\n // Find all occurrences (should only be one, but be safe)\n const matches: Array<{ index: number; length: number }> = [];\n let match;\n while ((match = ruleKeyPattern.exec(updated)) !== null) {\n if (match.index !== undefined) {\n matches.push({ index: match.index, length: match[0].length });\n }\n }\n\n // Process matches in reverse order\n for (let j = matches.length - 1; j >= 0; j--) {\n const keyMatch = matches[j]!;\n const keyStart = keyMatch.index;\n const keyEnd = keyStart + keyMatch.length;\n\n // Find the value start (after colon and whitespace)\n let valueStart = keyEnd;\n while (valueStart < updated.length && /\\s/.test(updated[valueStart])) {\n valueStart++;\n }\n\n // Find the value end\n const valueEnd = findRuleValueEnd(updated, valueStart);\n\n // Generate new rule config\n const newRuleConfig = generateSingleRuleConfig(rule);\n\n // Find the indentation of the rule key line\n const indent = detectIndent(updated, keyStart);\n\n // Replace the old rule with the new one\n const before = updated.slice(0, keyStart);\n const after = updated.slice(valueEnd);\n\n updated = before + newRuleConfig + \"\\n\" + indent + after;\n }\n }\n\n return updated;\n}\n\n/**\n * Inject uilint rules into the export default array\n */\nfunction injectUilintRules(\n source: string,\n selectedRules: RuleMetadata[]\n): { source: string; injected: boolean } {\n if (hasUilintRules(source)) {\n // Already has uilint rules - don't inject again\n return { source, injected: false };\n }\n\n const rulesConfig = generateRulesConfig(selectedRules);\n\n const configBlock = ` {\n files: [\n \"src/**/*.{js,jsx,ts,tsx}\",\n \"app/**/*.{js,jsx,ts,tsx}\",\n \"pages/**/*.{js,jsx,ts,tsx}\",\n ],\n plugins: { uilint: uilint },\n rules: {\n${rulesConfig}\n },\n },`;\n\n const arrayStart = findEsmExportedConfigArrayStartIndex(source);\n if (arrayStart === null) {\n return { source, injected: false };\n }\n\n const afterExport = source.slice(arrayStart);\n\n // Insert at the beginning of the array (after opening bracket)\n // Add a newline if the array doesn't start on a new line\n const needsNewline = !afterExport.trimStart().startsWith(\"\\n\");\n const insertion = needsNewline\n ? \"\\n\" + configBlock + \"\\n\"\n : configBlock + \"\\n\";\n\n return {\n source: source.slice(0, arrayStart) + insertion + source.slice(arrayStart),\n injected: true,\n };\n}\n\n/**\n * Inject uilint rules into the CommonJS export\n */\nfunction injectUilintRulesCommonJS(\n source: string,\n selectedRules: RuleMetadata[]\n): { source: string; injected: boolean } {\n if (hasUilintRules(source)) {\n return { source, injected: false };\n }\n\n const rulesConfig = generateRulesConfig(selectedRules);\n\n const configBlock = ` {\n files: [\n \"src/**/*.{js,jsx,ts,tsx}\",\n \"app/**/*.{js,jsx,ts,tsx}\",\n \"pages/**/*.{js,jsx,ts,tsx}\",\n ],\n plugins: { uilint: uilint },\n rules: {\n${rulesConfig}\n },\n },`;\n\n const arrayStart = findCommonJsExportedConfigArrayStartIndex(source);\n if (arrayStart === null) {\n return { source, injected: false };\n }\n\n const afterExport = source.slice(arrayStart);\n const needsNewline = !afterExport.trimStart().startsWith(\"\\n\");\n const insertion = needsNewline\n ? \"\\n\" + configBlock + \"\\n\"\n : configBlock + \"\\n\";\n\n return {\n source: source.slice(0, arrayStart) + insertion + source.slice(arrayStart),\n injected: true,\n };\n}\n\n/**\n * Install uilint-eslint into eslint config\n */\nexport async function installEslintPlugin(\n opts: InstallEslintPluginOptions\n): Promise<{\n configFile: string | null;\n modified: boolean;\n missingRuleIds: string[];\n configured: boolean;\n error?: string;\n}> {\n const configPath = findEslintConfigFile(opts.projectPath);\n\n if (!configPath) {\n return {\n configFile: null,\n modified: false,\n missingRuleIds: [],\n configured: false,\n };\n }\n\n const configFilename = getEslintConfigFilename(configPath);\n const original = readFileSync(configPath, \"utf-8\");\n const isCommonJS = configPath.endsWith(\".cjs\");\n\n const ast = getUilintEslintConfigInfoFromSourceAst(original);\n if (\"error\" in ast) {\n return {\n configFile: configFilename,\n modified: false,\n missingRuleIds: [],\n configured: false,\n error: ast.error,\n };\n }\n\n const { info, mod, arrayExpr, kind } = ast;\n const configuredIds = info.configuredRuleIds;\n\n const missingRules = getMissingSelectedRules(\n opts.selectedRules,\n configuredIds\n );\n const rulesToUpdate = getRulesNeedingUpdate(\n opts.selectedRules,\n configuredIds,\n arrayExpr\n );\n\n // Decide what rules to apply, respecting prompts.\n let rulesToApply: RuleMetadata[] = [];\n if (!info.configured) {\n rulesToApply = opts.selectedRules;\n } else {\n // When already configured, we only apply updates + missing rules.\n rulesToApply = [...missingRules, ...rulesToUpdate];\n if (missingRules.length > 0 && !opts.force) {\n const ok = await opts.confirmAddMissingRules?.(\n configFilename,\n missingRules\n );\n if (!ok) {\n return {\n configFile: configFilename,\n modified: false,\n missingRuleIds: missingRules.map((r) => r.id),\n configured: true,\n };\n }\n }\n }\n\n if (rulesToApply.length === 0) {\n return {\n configFile: configFilename,\n modified: false,\n missingRuleIds: missingRules.map((r) => r.id),\n configured: info.configured,\n };\n }\n\n let modifiedAst = false;\n\n // Check if .uilint/rules/ directory exists alongside this target package/app.\n // (Also allow a fallback to workspace root for backwards compatibility.)\n const localRulesDir = join(opts.projectPath, \".uilint\", \"rules\");\n const workspaceRoot = findWorkspaceRoot(opts.projectPath);\n const workspaceRulesDir = join(workspaceRoot, \".uilint\", \"rules\");\n\n const rulesRoot = existsSync(localRulesDir)\n ? opts.projectPath\n : workspaceRoot;\n\n // Always use local rules (they should have been copied by the plan phase)\n // For TypeScript configs, omit the extension (TypeScript will resolve .ts files)\n // For JavaScript configs, use .js extension\n // Note: We don't use .ts extension directly because it requires allowImportingTsExtensions\n const isTypeScriptConfig = configPath.endsWith(\".ts\");\n let fileExtension = isTypeScriptConfig ? \"\" : \".js\";\n\n let ruleImportNames: Map<string, string> | undefined;\n\n // Add imports for local rules\n if (kind === \"esm\") {\n const result = addLocalRuleImportsAst(\n mod,\n rulesToApply,\n configPath,\n rulesRoot,\n fileExtension\n );\n ruleImportNames = result.importNames;\n if (result.changed) modifiedAst = true;\n } else {\n const result = addLocalRuleRequiresAst(\n mod.$ast,\n rulesToApply,\n configPath,\n rulesRoot,\n fileExtension\n );\n ruleImportNames = result.importNames;\n if (result.changed) modifiedAst = true;\n }\n\n // Add config block with local rules\n if (ruleImportNames && ruleImportNames.size > 0) {\n appendUilintConfigBlockToArray(arrayExpr, rulesToApply, ruleImportNames);\n modifiedAst = true;\n }\n\n // Ensure uilint-eslint import for utilities (createRule, etc.)\n if (!info.configured) {\n if (kind === \"esm\") {\n // Import createRule utility from uilint-eslint\n mod.imports.$add({\n imported: \"createRule\",\n local: \"createRule\",\n from: \"uilint-eslint\",\n });\n modifiedAst = true;\n } else {\n // CommonJS: add require for createRule\n const stmtMod = parseModule(\n `const { createRule } = require(\"uilint-eslint\");`\n );\n const stmt = (stmtMod.$ast as any).body?.[0];\n if (stmt) {\n let insertAt = 0;\n const first = mod.$ast.body?.[0];\n if (\n first?.type === \"ExpressionStatement\" &&\n first.expression?.type === \"StringLiteral\" &&\n first.expression.value === \"use strict\"\n ) {\n insertAt = 1;\n }\n mod.$ast.body.splice(insertAt, 0, stmt);\n modifiedAst = true;\n }\n }\n }\n\n const updated = modifiedAst ? generateCode(mod).code : original;\n\n if (updated !== original) {\n writeFileSync(configPath, updated, \"utf-8\");\n return {\n configFile: configFilename,\n modified: true,\n missingRuleIds: missingRules.map((r) => r.id),\n configured: getUilintEslintConfigInfoFromSource(updated).configured,\n };\n }\n\n return {\n configFile: configFilename,\n modified: false,\n missingRuleIds: missingRules.map((r) => r.id),\n configured: getUilintEslintConfigInfoFromSource(updated).configured,\n };\n}\n","/**\n * Execute phase - perform side effects from InstallPlan\n *\n * This module takes an InstallPlan and performs all the actual file operations,\n * dependency installations, and config modifications.\n */\n\nimport {\n existsSync,\n mkdirSync,\n writeFileSync,\n readFileSync,\n unlinkSync,\n chmodSync,\n} from \"fs\";\nimport { dirname } from \"path\";\nimport type {\n InstallPlan,\n InstallAction,\n InstallResult,\n ActionResult,\n DependencyResult,\n InstallSummary,\n ExecuteOptions,\n InjectEslintAction,\n InjectReactAction,\n InjectNextConfigAction,\n InjectViteConfigAction,\n InstallNextRoutesAction,\n} from \"./types.js\";\nimport { installDependencies as defaultInstallDependencies } from \"../../utils/package-manager.js\";\nimport { installEslintPlugin } from \"../../utils/eslint-config-inject.js\";\nimport { installReactUILintOverlay } from \"../../utils/react-inject.js\";\nimport { installJsxLocPlugin } from \"../../utils/next-config-inject.js\";\nimport { installViteJsxLocPlugin } from \"../../utils/vite-config-inject.js\";\nimport { installNextUILintRoutes } from \"../../utils/next-routes.js\";\nimport { formatFilesWithPrettier } from \"../../utils/prettier.js\";\n\n/**\n * Execute a single action and return the result\n */\nasync function executeAction(\n action: InstallAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n try {\n switch (action.type) {\n case \"create_directory\": {\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Create directory: ${action.path}`,\n };\n }\n if (!existsSync(action.path)) {\n mkdirSync(action.path, { recursive: true });\n }\n return { action, success: true };\n }\n\n case \"create_file\": {\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Create file: ${action.path}${\n action.permissions\n ? ` (mode: ${action.permissions.toString(8)})`\n : \"\"\n }`,\n };\n }\n // Ensure parent directory exists\n const dir = dirname(action.path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n writeFileSync(action.path, action.content, \"utf-8\");\n if (action.permissions) {\n chmodSync(action.path, action.permissions);\n }\n return { action, success: true };\n }\n\n case \"merge_json\": {\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Merge JSON into: ${action.path}`,\n };\n }\n let existing: Record<string, unknown> = {};\n if (existsSync(action.path)) {\n try {\n existing = JSON.parse(readFileSync(action.path, \"utf-8\"));\n } catch {\n // Start fresh if parse fails\n }\n }\n const merged = deepMerge(existing, action.merge);\n // Ensure parent directory exists\n const dir = dirname(action.path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n writeFileSync(action.path, JSON.stringify(merged, null, 2), \"utf-8\");\n return { action, success: true };\n }\n\n case \"delete_file\": {\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Delete file: ${action.path}`,\n };\n }\n if (existsSync(action.path)) {\n unlinkSync(action.path);\n }\n return { action, success: true };\n }\n\n case \"append_to_file\": {\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Append to file: ${action.path}`,\n };\n }\n if (existsSync(action.path)) {\n const content = readFileSync(action.path, \"utf-8\");\n if (action.ifNotContains && content.includes(action.ifNotContains)) {\n // Already contains the content, skip\n return { action, success: true };\n }\n writeFileSync(action.path, content + action.content, \"utf-8\");\n }\n // If file doesn't exist, skip (don't create .gitignore from scratch)\n return { action, success: true };\n }\n\n case \"inject_eslint\": {\n return await executeInjectEslint(action, options);\n }\n\n case \"inject_react\": {\n return await executeInjectReact(action, options);\n }\n\n case \"inject_next_config\": {\n return await executeInjectNextConfig(action, options);\n }\n\n case \"inject_vite_config\": {\n return await executeInjectViteConfig(action, options);\n }\n\n case \"install_next_routes\": {\n return await executeInstallNextRoutes(action, options);\n }\n\n default: {\n // Exhaustiveness check\n const _exhaustive: never = action;\n return {\n action: _exhaustive,\n success: false,\n error: `Unknown action type`,\n };\n }\n }\n } catch (error) {\n return {\n action,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Execute ESLint injection\n */\nasync function executeInjectEslint(\n action: InjectEslintAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Inject ESLint rules into: ${action.configPath}`,\n };\n }\n\n // Use the existing installEslintPlugin function\n // It handles all the complexity of parsing and modifying the config\n const result = await installEslintPlugin({\n projectPath: action.packagePath,\n selectedRules: action.rules,\n force: !action.hasExistingRules, // Don't force if already has rules\n // Auto-confirm for execute phase (choices were made during planning)\n confirmAddMissingRules: async () => true,\n });\n\n return {\n action,\n success: result.configFile !== null && result.configured,\n error:\n result.configFile === null\n ? \"No ESLint config found\"\n : result.configured\n ? undefined\n : result.error ?? \"Failed to configure uilint in ESLint config\",\n };\n}\n\n/**\n * Execute React overlay injection\n */\nasync function executeInjectReact(\n action: InjectReactAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Inject <uilint-devtools /> into React app: ${action.projectPath}`,\n };\n }\n\n const result = await installReactUILintOverlay({\n projectPath: action.projectPath,\n appRoot: action.appRoot,\n mode: action.mode,\n force: false,\n // Auto-select first choice for execute phase\n confirmFileChoice: async (choices) => choices[0],\n });\n\n // Success if modified OR already configured (goal achieved either way)\n const success = result.modified || result.alreadyConfigured === true;\n\n return {\n action,\n success,\n error: success ? undefined : \"Failed to configure React overlay\",\n };\n}\n\n/**\n * Execute Vite config injection\n */\nasync function executeInjectViteConfig(\n action: InjectViteConfigAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Inject jsx-loc-plugin into vite.config: ${action.projectPath}`,\n };\n }\n\n const result = await installViteJsxLocPlugin({\n projectPath: action.projectPath,\n force: false,\n });\n\n return {\n action,\n success: result.modified || result.configFile !== null,\n error: result.configFile === null ? \"No vite.config found\" : undefined,\n };\n}\n\n/**\n * Execute Next.js config injection\n */\nasync function executeInjectNextConfig(\n action: InjectNextConfigAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Inject jsx-loc-plugin into next.config: ${action.projectPath}`,\n };\n }\n\n const result = await installJsxLocPlugin({\n projectPath: action.projectPath,\n force: false,\n });\n\n return {\n action,\n success: result.modified || result.configFile !== null,\n error: result.configFile === null ? \"No next.config found\" : undefined,\n };\n}\n\n/**\n * Execute Next.js routes installation\n */\nasync function executeInstallNextRoutes(\n action: InstallNextRoutesAction,\n options: ExecuteOptions\n): Promise<ActionResult> {\n const { dryRun = false } = options;\n\n if (dryRun) {\n return {\n action,\n success: true,\n wouldDo: `Install Next.js API routes: ${action.projectPath}`,\n };\n }\n\n await installNextUILintRoutes({\n projectPath: action.projectPath,\n appRoot: action.appRoot,\n force: false,\n });\n\n return { action, success: true };\n}\n\n/**\n * Deep merge two objects\n */\nfunction deepMerge(\n target: Record<string, unknown>,\n source: Record<string, unknown>\n): Record<string, unknown> {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (\n sourceVal &&\n typeof sourceVal === \"object\" &&\n !Array.isArray(sourceVal) &&\n targetVal &&\n typeof targetVal === \"object\" &&\n !Array.isArray(targetVal)\n ) {\n result[key] = deepMerge(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>\n );\n } else {\n result[key] = sourceVal;\n }\n }\n\n return result;\n}\n\n/**\n * Build the install summary from results\n */\nfunction buildSummary(\n actionsPerformed: ActionResult[],\n dependencyResults: DependencyResult[],\n items: string[]\n): InstallSummary {\n const filesCreated: string[] = [];\n const filesModified: string[] = [];\n const filesDeleted: string[] = [];\n const eslintTargets: { displayName: string; configFile: string }[] = [];\n let nextApp: { appRoot: string } | undefined;\n let viteApp: { entryRoot: string } | undefined;\n\n for (const result of actionsPerformed) {\n if (!result.success) continue;\n\n const { action } = result;\n switch (action.type) {\n case \"create_file\":\n filesCreated.push(action.path);\n break;\n case \"merge_json\":\n case \"append_to_file\":\n filesModified.push(action.path);\n break;\n case \"delete_file\":\n filesDeleted.push(action.path);\n break;\n case \"inject_eslint\":\n filesModified.push(action.configPath);\n eslintTargets.push({\n displayName: action.packagePath,\n configFile: action.configPath,\n });\n break;\n case \"inject_react\":\n if (action.mode === \"vite\") {\n viteApp = { entryRoot: action.appRoot };\n } else {\n nextApp = { appRoot: action.appRoot };\n }\n break;\n case \"install_next_routes\":\n nextApp = { appRoot: action.appRoot };\n break;\n }\n }\n\n const dependenciesInstalled: { packagePath: string; packages: string[] }[] =\n [];\n for (const result of dependencyResults) {\n if (result.success && !result.skipped) {\n dependenciesInstalled.push({\n packagePath: result.install.packagePath,\n packages: result.install.packages,\n });\n }\n }\n\n return {\n installedItems: items as InstallSummary[\"installedItems\"],\n filesCreated,\n filesModified,\n filesDeleted,\n dependenciesInstalled,\n eslintTargets,\n nextApp,\n viteApp,\n };\n}\n\n/**\n * Collect files that should be formatted with prettier\n * Includes source files (.ts, .tsx, .js, .jsx, .mjs, .cjs) but excludes markdown\n */\nfunction collectFormattableFiles(actionsPerformed: ActionResult[]): string[] {\n const formattableExtensions = new Set([\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".json\",\n ]);\n\n const files: string[] = [];\n\n for (const result of actionsPerformed) {\n if (!result.success) continue;\n const { action } = result;\n\n let filePath: string | undefined;\n\n switch (action.type) {\n case \"create_file\":\n filePath = action.path;\n break;\n case \"merge_json\":\n filePath = action.path;\n break;\n case \"append_to_file\":\n filePath = action.path;\n break;\n case \"inject_eslint\":\n filePath = action.configPath;\n break;\n case \"inject_next_config\":\n case \"inject_vite_config\":\n case \"inject_react\":\n // These modify files but we don't have the exact path here\n // The injection utilities handle their own files\n break;\n }\n\n if (filePath) {\n const ext = filePath.slice(filePath.lastIndexOf(\".\")).toLowerCase();\n if (formattableExtensions.has(ext)) {\n files.push(filePath);\n }\n }\n }\n\n return files;\n}\n\n/**\n * Extract project path from actions\n */\nfunction getProjectPathFromActions(\n actionsPerformed: ActionResult[]\n): string | undefined {\n for (const result of actionsPerformed) {\n if (!result.success) continue;\n const { action } = result;\n\n switch (action.type) {\n case \"inject_eslint\":\n return action.packagePath;\n case \"inject_react\":\n case \"inject_next_config\":\n case \"inject_vite_config\":\n case \"install_next_routes\":\n return action.projectPath;\n }\n }\n return undefined;\n}\n\n/**\n * Execute an install plan\n *\n * @param plan - The install plan to execute\n * @param options - Execution options\n * @returns InstallResult with details of what was done\n */\nexport async function execute(\n plan: InstallPlan,\n options: ExecuteOptions = {}\n): Promise<InstallResult> {\n const {\n dryRun = false,\n installDependencies = defaultInstallDependencies,\n projectPath,\n skipPrettier = false,\n } = options;\n\n const actionsPerformed: ActionResult[] = [];\n const dependencyResults: DependencyResult[] = [];\n\n // Execute all actions in order\n for (const action of plan.actions) {\n const result = await executeAction(action, options);\n actionsPerformed.push(result);\n }\n\n // Install dependencies\n for (const dep of plan.dependencies) {\n if (dryRun) {\n dependencyResults.push({\n install: dep,\n success: true,\n skipped: true,\n });\n continue;\n }\n\n try {\n await installDependencies(\n dep.packageManager,\n dep.packagePath,\n dep.packages\n );\n dependencyResults.push({\n install: dep,\n success: true,\n });\n } catch (error) {\n dependencyResults.push({\n install: dep,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Format modified files with prettier (if available)\n if (!dryRun && !skipPrettier) {\n const filesToFormat = collectFormattableFiles(actionsPerformed);\n if (filesToFormat.length > 0) {\n // Determine project path from options or from first dependency/action\n const formatProjectPath =\n projectPath ||\n plan.dependencies[0]?.packagePath ||\n getProjectPathFromActions(actionsPerformed);\n\n if (formatProjectPath) {\n // Run prettier silently - don't fail install if formatting fails\n await formatFilesWithPrettier(filesToFormat, formatProjectPath).catch(\n () => {\n // Ignore formatting errors\n }\n );\n }\n }\n }\n\n // Determine overall success\n const actionsFailed = actionsPerformed.filter((r) => !r.success);\n const depsFailed = dependencyResults.filter((r) => !r.success);\n const success = actionsFailed.length === 0 && depsFailed.length === 0;\n\n // Collect items from actions (reverse engineer what was installed)\n const items: string[] = [];\n for (const result of actionsPerformed) {\n if (!result.success) continue;\n const { action } = result;\n if (action.type === \"create_file\") {\n if (action.path.includes(\"genstyleguide.md\")) items.push(\"genstyleguide\");\n if (action.path.includes(\"/skills/\") && action.path.includes(\"SKILL.md\")) items.push(\"skill\");\n }\n if (action.type === \"inject_eslint\") items.push(\"eslint\");\n if (action.type === \"install_next_routes\") items.push(\"next\");\n if (action.type === \"inject_react\") {\n items.push(action.mode === \"vite\" ? \"vite\" : \"next\");\n }\n if (action.type === \"inject_vite_config\") items.push(\"vite\");\n }\n // Dedupe\n const uniqueItems = [...new Set(items)];\n\n const summary = buildSummary(\n actionsPerformed,\n dependencyResults,\n uniqueItems\n );\n\n return {\n success,\n actionsPerformed,\n dependencyResults,\n summary,\n };\n}\n","import { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { parseModule, generateCode } from \"magicast\";\n\nexport interface InstallReactOverlayOptions {\n projectPath: string;\n /**\n * Relative entry root:\n * - Next.js: \"app\" or \"src/app\"\n * - Vite: typically \"src\"\n */\n appRoot: string;\n /**\n * Injection mode:\n * - \"next\": wraps `{children}` (App Router layout/page)\n * - \"vite\": wraps the first `*.render(<...>)` argument\n */\n mode?: \"next\" | \"vite\";\n force?: boolean;\n /**\n * If multiple candidates are found, prompt user to choose.\n */\n confirmFileChoice?: (choices: string[]) => Promise<string>;\n}\n\n/**\n * Find top-level layout.* or page.* files in the app root.\n * Prefer layout.* over page.* (layouts are better for providers).\n */\nfunction getDefaultCandidates(projectPath: string, appRoot: string): string[] {\n // Vite entry files (prefer src/main.*)\n const viteMainCandidates = [\n join(appRoot, \"main.tsx\"),\n join(appRoot, \"main.jsx\"),\n join(appRoot, \"main.ts\"),\n join(appRoot, \"main.js\"),\n ];\n const existingViteMain = viteMainCandidates.filter((rel) =>\n existsSync(join(projectPath, rel))\n );\n if (existingViteMain.length > 0) return existingViteMain;\n\n // Vite fallback: src/App.* (some templates wire provider there)\n const viteAppCandidates = [join(appRoot, \"App.tsx\"), join(appRoot, \"App.jsx\")];\n const existingViteApp = viteAppCandidates.filter((rel) =>\n existsSync(join(projectPath, rel))\n );\n if (existingViteApp.length > 0) return existingViteApp;\n\n // Check layout files first (preferred)\n const layoutCandidates = [\n join(appRoot, \"layout.tsx\"),\n join(appRoot, \"layout.jsx\"),\n join(appRoot, \"layout.ts\"),\n join(appRoot, \"layout.js\"),\n ];\n\n const existingLayouts = layoutCandidates.filter((rel) =>\n existsSync(join(projectPath, rel))\n );\n\n if (existingLayouts.length > 0) {\n return existingLayouts;\n }\n\n // Fall back to page files if no layouts found\n const pageCandidates = [join(appRoot, \"page.tsx\"), join(appRoot, \"page.jsx\")];\n\n return pageCandidates.filter((rel) => existsSync(join(projectPath, rel)));\n}\n\nfunction isUseClientDirective(stmt: any): boolean {\n return (\n stmt?.type === \"ExpressionStatement\" &&\n stmt.expression?.type === \"StringLiteral\" &&\n stmt.expression.value === \"use client\"\n );\n}\n\nfunction findImportDeclaration(program: any, from: string): any | null {\n if (!program || program.type !== \"Program\") return null;\n for (const stmt of program.body ?? []) {\n if (stmt?.type !== \"ImportDeclaration\") continue;\n if (stmt.source?.value === from) return stmt;\n }\n return null;\n}\n\nfunction walkAst(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== \"object\") return;\n if (node.type) visit(node);\n for (const key of Object.keys(node)) {\n const v = (node as any)[key];\n if (!v) continue;\n if (Array.isArray(v)) {\n for (const item of v) walkAst(item, visit);\n } else if (typeof v === \"object\" && v.type) {\n walkAst(v, visit);\n }\n }\n}\n\nfunction ensureNamedImport(\n program: any,\n from: string,\n name: string\n): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n const existing = findImportDeclaration(program, from);\n if (existing) {\n const has = (existing.specifiers ?? []).some(\n (s: any) =>\n s?.type === \"ImportSpecifier\" &&\n (s.imported?.name === name || s.imported?.value === name)\n );\n if (has) return { changed: false };\n\n const spec = (parseModule(`import { ${name} } from \"${from}\";`).$ast as any)\n .body?.[0]?.specifiers?.[0];\n if (!spec) return { changed: false };\n\n existing.specifiers = [...(existing.specifiers ?? []), spec];\n return { changed: true };\n }\n\n // Insert a fresh import after directives, and after existing imports.\n const importDecl = (\n parseModule(`import { ${name} } from \"${from}\";`).$ast as any\n ).body?.[0];\n if (!importDecl) return { changed: false };\n\n const body = program.body ?? [];\n let insertAt = 0;\n while (insertAt < body.length && isUseClientDirective(body[insertAt])) {\n insertAt++;\n }\n // Skip over existing imports\n while (\n insertAt < body.length &&\n body[insertAt]?.type === \"ImportDeclaration\"\n ) {\n insertAt++;\n }\n program.body.splice(insertAt, 0, importDecl);\n return { changed: true };\n}\n\nfunction hasUILintDevtoolsJsx(program: any): boolean {\n let found = false;\n walkAst(program, (node) => {\n if (found) return;\n if (node.type !== \"JSXElement\") return;\n const name = node.openingElement?.name;\n // Check for both old UILintProvider and new uilint-devtools\n if (name?.type === \"JSXIdentifier\") {\n if (name.name === \"UILintProvider\" || name.name === \"uilint-devtools\") {\n found = true;\n }\n }\n });\n return found;\n}\n\n/**\n * Add <uilint-devtools /> element as a sibling to {children} in Next.js layouts.\n * This injects the devtools web component without wrapping the children.\n */\nfunction addDevtoolsElementNextJs(program: any): {\n changed: boolean;\n} {\n if (!program || program.type !== \"Program\") return { changed: false };\n if (hasUILintDevtoolsJsx(program)) return { changed: false };\n\n // Create the devtools JSX element: <uilint-devtools />\n const devtoolsMod = parseModule(\n 'const __uilint_devtools = (<uilint-devtools />);'\n );\n const devtoolsJsx =\n (devtoolsMod.$ast as any).body?.[0]?.declarations?.[0]?.init ?? null;\n if (!devtoolsJsx || devtoolsJsx.type !== \"JSXElement\")\n return { changed: false };\n\n // Find the return statement that contains {children} and add devtools as sibling\n let added = false;\n walkAst(program, (node) => {\n if (added) return;\n\n // Look for JSX elements that contain {children}\n if (node.type !== \"JSXElement\" && node.type !== \"JSXFragment\") return;\n\n const children = node.children ?? [];\n const childrenIndex = children.findIndex(\n (child: any) =>\n child?.type === \"JSXExpressionContainer\" &&\n child.expression?.type === \"Identifier\" &&\n child.expression.name === \"children\"\n );\n\n if (childrenIndex === -1) return;\n\n // Add devtools element after {children}\n children.splice(childrenIndex + 1, 0, devtoolsJsx);\n added = true;\n });\n\n if (!added) {\n throw new Error(\"Could not find `{children}` in target file to add devtools.\");\n }\n return { changed: true };\n}\n\n/**\n * Add <uilint-devtools /> element to Vite's render call.\n * Wraps the existing render argument in a fragment with the devtools element.\n */\nfunction addDevtoolsElementVite(program: any): {\n changed: boolean;\n} {\n if (!program || program.type !== \"Program\") return { changed: false };\n if (hasUILintDevtoolsJsx(program)) return { changed: false };\n\n // Create a fragment containing the original content + devtools:\n // <>...original...<uilint-devtools /></>\n let added = false;\n walkAst(program, (node) => {\n if (added) return;\n if (node.type !== \"CallExpression\") return;\n const callee = node.callee;\n // Match: something.render(<JSX />)\n if (callee?.type !== \"MemberExpression\") return;\n const prop = callee.property;\n const isRender =\n (prop?.type === \"Identifier\" && prop.name === \"render\") ||\n (prop?.type === \"StringLiteral\" && prop.value === \"render\") ||\n (prop?.type === \"Literal\" && prop.value === \"render\");\n if (!isRender) return;\n\n const arg0 = node.arguments?.[0];\n if (!arg0) return;\n if (arg0.type !== \"JSXElement\" && arg0.type !== \"JSXFragment\") return;\n\n // Create the devtools JSX element\n const devtoolsMod = parseModule(\n 'const __uilint_devtools = (<uilint-devtools />);'\n );\n const devtoolsJsx =\n (devtoolsMod.$ast as any).body?.[0]?.declarations?.[0]?.init ?? null;\n if (!devtoolsJsx) return;\n\n // Create a fragment wrapping original + devtools\n const fragmentMod = parseModule(\n 'const __fragment = (<></>);'\n );\n const fragmentJsx =\n (fragmentMod.$ast as any).body?.[0]?.declarations?.[0]?.init ?? null;\n if (!fragmentJsx) return;\n\n // Add original content and devtools as children of the fragment\n fragmentJsx.children = [arg0, devtoolsJsx];\n node.arguments[0] = fragmentJsx;\n added = true;\n });\n\n if (!added) {\n throw new Error(\n 'Could not find a `.render(<...>)` call to add devtools. Expected a React entry like `createRoot(...).render(<App />)`.'\n );\n }\n return { changed: true };\n}\n\n/**\n * Ensure a side-effect import exists in the program.\n * e.g., import \"uilint-react/devtools\";\n */\nfunction ensureSideEffectImport(\n program: any,\n from: string\n): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n // Check if import already exists\n const existing = findImportDeclaration(program, from);\n if (existing) return { changed: false };\n\n // Create a side-effect import\n const importDecl = (\n parseModule(`import \"${from}\";`).$ast as any\n ).body?.[0];\n if (!importDecl) return { changed: false };\n\n const body = program.body ?? [];\n let insertAt = 0;\n // Skip \"use client\" directive\n while (insertAt < body.length && isUseClientDirective(body[insertAt])) {\n insertAt++;\n }\n // Skip over existing imports\n while (\n insertAt < body.length &&\n body[insertAt]?.type === \"ImportDeclaration\"\n ) {\n insertAt++;\n }\n program.body.splice(insertAt, 0, importDecl);\n return { changed: true };\n}\n\nexport async function installReactUILintOverlay(\n opts: InstallReactOverlayOptions\n): Promise<{\n targetFile: string;\n modified: boolean;\n alreadyConfigured?: boolean;\n}> {\n const candidates = getDefaultCandidates(opts.projectPath, opts.appRoot);\n if (!candidates.length) {\n throw new Error(\n `No suitable entry files found under ${opts.appRoot} (expected Next.js layout/page or Vite main/App).`\n );\n }\n\n let chosen: string;\n\n // If there are multiple candidates, ask user to choose\n if (candidates.length > 1 && opts.confirmFileChoice) {\n chosen = await opts.confirmFileChoice(candidates);\n } else {\n // Single candidate - use it\n chosen = candidates[0]!;\n }\n\n const absTarget = join(opts.projectPath, chosen);\n const original = readFileSync(absTarget, \"utf-8\");\n\n let mod: any;\n try {\n mod = parseModule(original);\n } catch {\n throw new Error(\n `Unable to parse ${chosen} as JavaScript/TypeScript. Please update it manually.`\n );\n }\n\n const program = mod.$ast;\n\n // Check if already configured (either old UILintProvider or new devtools approach)\n const hasDevtoolsImport = !!findImportDeclaration(program, \"uilint-react/devtools\");\n const hasOldImport = !!findImportDeclaration(program, \"uilint-react\");\n const alreadyConfigured =\n (hasDevtoolsImport || hasOldImport) && hasUILintDevtoolsJsx(program);\n\n let changed = false;\n\n // Add side-effect import for the devtools web component\n const importRes = ensureSideEffectImport(program, \"uilint-react/devtools\");\n if (importRes.changed) changed = true;\n\n const mode = opts.mode ?? \"next\";\n const addRes =\n mode === \"vite\"\n ? addDevtoolsElementVite(program)\n : addDevtoolsElementNextJs(program);\n if (addRes.changed) changed = true;\n\n const updated = changed ? generateCode(mod).code : original;\n\n const modified = updated !== original;\n if (modified) {\n writeFileSync(absTarget, updated, \"utf-8\");\n }\n\n return {\n targetFile: chosen,\n modified,\n alreadyConfigured: alreadyConfigured && !modified,\n };\n}\n","/**\n * Inject jsx-loc-plugin into Next.js config\n *\n * Modifies next.config.{ts,js,mjs,cjs} to wrap the export with withJsxLoc()\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { parseModule, generateCode } from \"magicast\";\n\nexport interface InstallJsxLocPluginOptions {\n projectPath: string;\n force?: boolean;\n}\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".mjs\", \".js\", \".cjs\"];\n\n/**\n * Find the next.config file in a project\n */\nexport function findNextConfigFile(projectPath: string): string | null {\n for (const ext of CONFIG_EXTENSIONS) {\n const configPath = join(projectPath, `next.config${ext}`);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n return null;\n}\n\n/**\n * Get the relative config filename for display\n */\nexport function getNextConfigFilename(configPath: string): string {\n const parts = configPath.split(\"/\");\n return parts[parts.length - 1] || \"next.config.ts\";\n}\n\n/**\n * Check if the source already has withJsxLoc imported\n */\nfunction hasJsxLocImport(source: string): boolean {\n return (\n source.includes('from \"jsx-loc-plugin\"') ||\n source.includes(\"from 'jsx-loc-plugin'\")\n );\n}\n\n/**\n * Check if the source already uses withJsxLoc\n */\nfunction hasJsxLocWrapper(source: string): boolean {\n return source.includes(\"withJsxLoc(\");\n}\n\nfunction isIdentifier(node: any, name?: string): boolean {\n return (\n !!node &&\n node.type === \"Identifier\" &&\n (name ? node.name === name : typeof node.name === \"string\")\n );\n}\n\nfunction isStringLiteral(node: any): node is { type: string; value: string } {\n return (\n !!node &&\n (node.type === \"StringLiteral\" || node.type === \"Literal\") &&\n typeof node.value === \"string\"\n );\n}\n\nfunction ensureEsmWithJsxLocImport(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n // Find existing import from jsx-loc-plugin\n const existing = (program.body ?? []).find(\n (s: any) => s?.type === \"ImportDeclaration\" && s.source?.value === \"jsx-loc-plugin\"\n );\n\n if (existing) {\n const has = (existing.specifiers ?? []).some(\n (sp: any) =>\n sp?.type === \"ImportSpecifier\" &&\n (sp.imported?.name === \"withJsxLoc\" || sp.imported?.value === \"withJsxLoc\")\n );\n if (has) return { changed: false };\n\n const spec = (parseModule('import { withJsxLoc } from \"jsx-loc-plugin\";')\n .$ast as any).body?.[0]?.specifiers?.[0];\n if (!spec) return { changed: false };\n existing.specifiers = [...(existing.specifiers ?? []), spec];\n return { changed: true };\n }\n\n const importDecl = (parseModule('import { withJsxLoc } from \"jsx-loc-plugin\";')\n .$ast as any).body?.[0];\n if (!importDecl) return { changed: false };\n\n // Insert after last import\n const body = program.body ?? [];\n let insertAt = 0;\n while (insertAt < body.length && body[insertAt]?.type === \"ImportDeclaration\") {\n insertAt++;\n }\n program.body.splice(insertAt, 0, importDecl);\n return { changed: true };\n}\n\nfunction ensureCjsWithJsxLocRequire(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n // Detect an existing require(\"jsx-loc-plugin\") that binds withJsxLoc\n for (const stmt of program.body ?? []) {\n if (stmt?.type !== \"VariableDeclaration\") continue;\n for (const decl of stmt.declarations ?? []) {\n const init = decl?.init;\n if (\n init?.type === \"CallExpression\" &&\n isIdentifier(init.callee, \"require\") &&\n isStringLiteral(init.arguments?.[0]) &&\n init.arguments[0].value === \"jsx-loc-plugin\"\n ) {\n // If destructuring, ensure property exists\n if (decl.id?.type === \"ObjectPattern\") {\n const has = (decl.id.properties ?? []).some((p: any) => {\n if (p?.type !== \"ObjectProperty\" && p?.type !== \"Property\") return false;\n return isIdentifier(p.key, \"withJsxLoc\");\n });\n if (has) return { changed: false };\n const prop = (parseModule('const { withJsxLoc } = require(\"jsx-loc-plugin\");')\n .$ast as any).body?.[0]?.declarations?.[0]?.id?.properties?.[0];\n if (!prop) return { changed: false };\n decl.id.properties = [...(decl.id.properties ?? []), prop];\n return { changed: true };\n }\n\n // Already requiring the module in some other shape; don't try to rewrite.\n return { changed: false };\n }\n }\n }\n\n // Insert: const { withJsxLoc } = require(\"jsx-loc-plugin\");\n const reqDecl = (parseModule('const { withJsxLoc } = require(\"jsx-loc-plugin\");')\n .$ast as any).body?.[0];\n if (!reqDecl) return { changed: false };\n program.body.unshift(reqDecl);\n return { changed: true };\n}\n\nfunction wrapEsmExportDefault(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n const exportDecl = (program.body ?? []).find(\n (s: any) => s?.type === \"ExportDefaultDeclaration\"\n );\n if (!exportDecl) return { changed: false };\n\n const decl = exportDecl.declaration;\n if (\n decl?.type === \"CallExpression\" &&\n isIdentifier(decl.callee, \"withJsxLoc\")\n ) {\n return { changed: false };\n }\n\n exportDecl.declaration = {\n type: \"CallExpression\",\n callee: { type: \"Identifier\", name: \"withJsxLoc\" },\n arguments: [decl],\n };\n return { changed: true };\n}\n\nfunction wrapCjsModuleExports(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n for (const stmt of program.body ?? []) {\n if (!stmt || stmt.type !== \"ExpressionStatement\") continue;\n const expr = stmt.expression;\n if (!expr || expr.type !== \"AssignmentExpression\") continue;\n const left = expr.left;\n const right = expr.right;\n const isModuleExports =\n left?.type === \"MemberExpression\" &&\n isIdentifier(left.object, \"module\") &&\n isIdentifier(left.property, \"exports\");\n if (!isModuleExports) continue;\n\n if (\n right?.type === \"CallExpression\" &&\n isIdentifier(right.callee, \"withJsxLoc\")\n ) {\n return { changed: false };\n }\n\n expr.right = {\n type: \"CallExpression\",\n callee: { type: \"Identifier\", name: \"withJsxLoc\" },\n arguments: [right],\n };\n return { changed: true };\n }\n\n return { changed: false };\n}\n\n/**\n * Install jsx-loc-plugin into next.config\n */\nexport async function installJsxLocPlugin(\n opts: InstallJsxLocPluginOptions\n): Promise<{ configFile: string | null; modified: boolean }> {\n const configPath = findNextConfigFile(opts.projectPath);\n\n if (!configPath) {\n return { configFile: null, modified: false };\n }\n\n const configFilename = getNextConfigFilename(configPath);\n const original = readFileSync(configPath, \"utf-8\");\n\n let mod: any;\n try {\n mod = parseModule(original);\n } catch {\n return { configFile: configFilename, modified: false };\n }\n\n const program = mod.$ast;\n const isCjs = configPath.endsWith(\".cjs\");\n\n // No confirmOverwrite needed: injector is idempotent.\n\n let changed = false;\n if (isCjs) {\n const reqRes = ensureCjsWithJsxLocRequire(program);\n if (reqRes.changed) changed = true;\n const wrapRes = wrapCjsModuleExports(program);\n if (wrapRes.changed) changed = true;\n } else {\n const impRes = ensureEsmWithJsxLocImport(program);\n if (impRes.changed) changed = true;\n const wrapRes = wrapEsmExportDefault(program);\n if (wrapRes.changed) changed = true;\n }\n\n const updated = changed ? generateCode(mod).code : original;\n\n if (updated !== original) {\n writeFileSync(configPath, updated, \"utf-8\");\n return { configFile: configFilename, modified: true };\n }\n\n return { configFile: configFilename, modified: false };\n}\n","/**\n * Inject jsx-loc-plugin into Vite config\n *\n * Modifies vite.config.{ts,js,mjs,cjs} to add `jsxLoc()` to the `plugins` array.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { parseModule, generateCode } from \"magicast\";\n\nexport interface InstallViteJsxLocPluginOptions {\n projectPath: string;\n force?: boolean;\n}\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".mjs\", \".js\", \".cjs\"];\n\nexport function findViteConfigFile(projectPath: string): string | null {\n for (const ext of CONFIG_EXTENSIONS) {\n const configPath = join(projectPath, `vite.config${ext}`);\n if (existsSync(configPath)) return configPath;\n }\n return null;\n}\n\nexport function getViteConfigFilename(configPath: string): string {\n const parts = configPath.split(\"/\");\n return parts[parts.length - 1] || \"vite.config.ts\";\n}\n\nfunction isIdentifier(node: any, name?: string): boolean {\n return (\n !!node &&\n node.type === \"Identifier\" &&\n (name ? node.name === name : typeof node.name === \"string\")\n );\n}\n\nfunction isStringLiteral(node: any): node is { type: string; value: string } {\n return (\n !!node &&\n (node.type === \"StringLiteral\" || node.type === \"Literal\") &&\n typeof node.value === \"string\"\n );\n}\n\nfunction unwrapExpression(expr: any): any {\n let e = expr;\n while (e) {\n if (e.type === \"TSAsExpression\" || e.type === \"TSNonNullExpression\") {\n e = e.expression;\n continue;\n }\n if (e.type === \"TSSatisfiesExpression\") {\n e = e.expression;\n continue;\n }\n if (e.type === \"ParenthesizedExpression\") {\n e = e.expression;\n continue;\n }\n break;\n }\n return e;\n}\n\nfunction findExportedConfigObjectExpression(mod: any): {\n kind: \"esm\" | \"cjs\";\n objExpr: any;\n program: any;\n} | null {\n const program = mod?.$ast;\n if (!program || program.type !== \"Program\") return null;\n\n // ESM: export default { ... } OR export default defineConfig({ ... })\n for (const stmt of program.body ?? []) {\n if (!stmt || stmt.type !== \"ExportDefaultDeclaration\") continue;\n const decl = unwrapExpression(stmt.declaration);\n if (!decl) break;\n\n if (decl.type === \"ObjectExpression\") {\n return { kind: \"esm\", objExpr: decl, program };\n }\n if (\n decl.type === \"CallExpression\" &&\n isIdentifier(decl.callee, \"defineConfig\") &&\n unwrapExpression(decl.arguments?.[0])?.type === \"ObjectExpression\"\n ) {\n return {\n kind: \"esm\",\n objExpr: unwrapExpression(decl.arguments?.[0]),\n program,\n };\n }\n break;\n }\n\n // CJS: module.exports = { ... } OR module.exports = defineConfig({ ... })\n for (const stmt of program.body ?? []) {\n if (!stmt || stmt.type !== \"ExpressionStatement\") continue;\n const expr = stmt.expression;\n if (!expr || expr.type !== \"AssignmentExpression\") continue;\n const left = expr.left;\n const right = unwrapExpression(expr.right);\n const isModuleExports =\n left?.type === \"MemberExpression\" &&\n isIdentifier(left.object, \"module\") &&\n isIdentifier(left.property, \"exports\");\n if (!isModuleExports) continue;\n\n if (right?.type === \"ObjectExpression\") {\n return { kind: \"cjs\", objExpr: right, program };\n }\n if (\n right?.type === \"CallExpression\" &&\n isIdentifier(right.callee, \"defineConfig\") &&\n unwrapExpression(right.arguments?.[0])?.type === \"ObjectExpression\"\n ) {\n return {\n kind: \"cjs\",\n objExpr: unwrapExpression(right.arguments?.[0]),\n program,\n };\n }\n }\n\n return null;\n}\n\nfunction getObjectProperty(obj: any, keyName: string): any | null {\n if (!obj || obj.type !== \"ObjectExpression\") return null;\n for (const prop of obj.properties ?? []) {\n if (!prop) continue;\n if (prop.type !== \"ObjectProperty\" && prop.type !== \"Property\") continue;\n const key = prop.key;\n const keyMatch =\n (key?.type === \"Identifier\" && key.name === keyName) ||\n (isStringLiteral(key) && key.value === keyName);\n if (keyMatch) return prop;\n }\n return null;\n}\n\nfunction ensureEsmJsxLocImport(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n // Find existing import from jsx-loc-plugin/vite\n const existing = (program.body ?? []).find(\n (s: any) =>\n s?.type === \"ImportDeclaration\" && s.source?.value === \"jsx-loc-plugin/vite\"\n );\n if (existing) {\n const has = (existing.specifiers ?? []).some(\n (sp: any) =>\n sp?.type === \"ImportSpecifier\" &&\n (sp.imported?.name === \"jsxLoc\" || sp.imported?.value === \"jsxLoc\")\n );\n if (has) return { changed: false };\n const spec = (\n parseModule('import { jsxLoc } from \"jsx-loc-plugin/vite\";').$ast as any\n ).body?.[0]?.specifiers?.[0];\n if (!spec) return { changed: false };\n existing.specifiers = [...(existing.specifiers ?? []), spec];\n return { changed: true };\n }\n\n const importDecl = (\n parseModule('import { jsxLoc } from \"jsx-loc-plugin/vite\";').$ast as any\n ).body?.[0];\n if (!importDecl) return { changed: false };\n\n // Insert after last import\n const body = program.body ?? [];\n let insertAt = 0;\n while (insertAt < body.length && body[insertAt]?.type === \"ImportDeclaration\") {\n insertAt++;\n }\n program.body.splice(insertAt, 0, importDecl);\n return { changed: true };\n}\n\nfunction ensureCjsJsxLocRequire(program: any): { changed: boolean } {\n if (!program || program.type !== \"Program\") return { changed: false };\n\n // Detect an existing require(\"jsx-loc-plugin/vite\") that binds jsxLoc\n for (const stmt of program.body ?? []) {\n if (stmt?.type !== \"VariableDeclaration\") continue;\n for (const decl of stmt.declarations ?? []) {\n const init = decl?.init;\n if (\n init?.type === \"CallExpression\" &&\n isIdentifier(init.callee, \"require\") &&\n isStringLiteral(init.arguments?.[0]) &&\n init.arguments[0].value === \"jsx-loc-plugin/vite\"\n ) {\n // If destructuring, ensure property exists\n if (decl.id?.type === \"ObjectPattern\") {\n const has = (decl.id.properties ?? []).some((p: any) => {\n if (p?.type !== \"ObjectProperty\" && p?.type !== \"Property\") return false;\n return isIdentifier(p.key, \"jsxLoc\");\n });\n if (has) return { changed: false };\n const prop = (\n parseModule('const { jsxLoc } = require(\"jsx-loc-plugin/vite\");')\n .$ast as any\n ).body?.[0]?.declarations?.[0]?.id?.properties?.[0];\n if (!prop) return { changed: false };\n decl.id.properties = [...(decl.id.properties ?? []), prop];\n return { changed: true };\n }\n return { changed: false };\n }\n }\n }\n\n // Insert: const { jsxLoc } = require(\"jsx-loc-plugin/vite\");\n const reqDecl = (\n parseModule('const { jsxLoc } = require(\"jsx-loc-plugin/vite\");').$ast as any\n ).body?.[0];\n if (!reqDecl) return { changed: false };\n program.body.unshift(reqDecl);\n return { changed: true };\n}\n\nfunction pluginsHasJsxLoc(arr: any): boolean {\n if (!arr || arr.type !== \"ArrayExpression\") return false;\n for (const el of arr.elements ?? []) {\n const e = unwrapExpression(el);\n if (!e) continue;\n if (e.type === \"CallExpression\" && isIdentifier(e.callee, \"jsxLoc\")) return true;\n }\n return false;\n}\n\nfunction ensurePluginsContainsJsxLoc(configObj: any): { changed: boolean } {\n const pluginsProp = getObjectProperty(configObj, \"plugins\");\n\n // No plugins: create plugins: [jsxLoc()]\n if (!pluginsProp) {\n const prop = (parseModule(\"export default { plugins: [jsxLoc()] };\").$ast as any)\n .body?.find((s: any) => s.type === \"ExportDefaultDeclaration\")\n ?.declaration?.properties?.find((p: any) => {\n const k = p?.key;\n return (k?.type === \"Identifier\" && k.name === \"plugins\") ||\n (isStringLiteral(k) && k.value === \"plugins\");\n });\n if (!prop) return { changed: false };\n configObj.properties = [...(configObj.properties ?? []), prop];\n return { changed: true };\n }\n\n const value = unwrapExpression(pluginsProp.value);\n if (!value) return { changed: false };\n\n // plugins: [ ... ]\n if (value.type === \"ArrayExpression\") {\n if (pluginsHasJsxLoc(value)) return { changed: false };\n const jsxLocCall = (parseModule(\"const __x = jsxLoc();\").$ast as any).body?.[0]\n ?.declarations?.[0]?.init;\n if (!jsxLocCall) return { changed: false };\n value.elements.push(jsxLocCall);\n return { changed: true };\n }\n\n // Non-array plugins: best-effort wrap into array with spread.\n // plugins: something -> plugins: [...something, jsxLoc()]\n const jsxLocCall = (parseModule(\"const __x = jsxLoc();\").$ast as any).body?.[0]\n ?.declarations?.[0]?.init;\n if (!jsxLocCall) return { changed: false };\n const spread = { type: \"SpreadElement\", argument: value };\n pluginsProp.value = { type: \"ArrayExpression\", elements: [spread, jsxLocCall] };\n return { changed: true };\n}\n\nexport async function installViteJsxLocPlugin(\n opts: InstallViteJsxLocPluginOptions\n): Promise<{ configFile: string | null; modified: boolean }> {\n const configPath = findViteConfigFile(opts.projectPath);\n if (!configPath) return { configFile: null, modified: false };\n\n const configFilename = getViteConfigFilename(configPath);\n const original = readFileSync(configPath, \"utf-8\");\n const isCjs = configPath.endsWith(\".cjs\");\n\n let mod: any;\n try {\n mod = parseModule(original);\n } catch {\n return { configFile: configFilename, modified: false };\n }\n\n const found = findExportedConfigObjectExpression(mod);\n if (!found) return { configFile: configFilename, modified: false };\n\n let changed = false;\n\n // Ensure import/require first (so generated code has the symbol)\n if (isCjs) {\n const reqRes = ensureCjsJsxLocRequire(found.program);\n if (reqRes.changed) changed = true;\n } else {\n const impRes = ensureEsmJsxLocImport(found.program);\n if (impRes.changed) changed = true;\n }\n\n const pluginsRes = ensurePluginsContainsJsxLoc(found.objExpr);\n if (pluginsRes.changed) changed = true;\n\n const updated = changed ? generateCode(mod).code : original;\n if (updated !== original) {\n writeFileSync(configPath, updated, \"utf-8\");\n return { configFile: configFilename, modified: true };\n }\n\n return { configFile: configFilename, modified: false };\n}\n","import { existsSync } from \"fs\";\nimport { mkdir, readdir, writeFile } from \"fs/promises\";\nimport { join } from \"path\";\n\nexport interface InstallNextRoutesOptions {\n projectPath: string;\n /**\n * Relative app root: \"app\" or \"src/app\"\n */\n appRoot: string;\n force?: boolean;\n}\n\nconst DEV_SOURCE_ROUTE_TS = `/**\n * Dev-only API route for fetching source files\n *\n * This route allows the UILint overlay to fetch and display source code\n * for components rendered on the page.\n *\n * Security:\n * - Only available in development mode\n * - Validates file path is within project root\n * - Only allows specific file extensions\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { readFileSync, existsSync } from \"fs\";\nimport { resolve, relative, dirname, extname, sep } from \"path\";\nimport { fileURLToPath } from \"url\";\n\nexport const runtime = \"nodejs\";\n\n// Allowed file extensions\nconst ALLOWED_EXTENSIONS = new Set([\".tsx\", \".ts\", \".jsx\", \".js\", \".css\"]);\n\n/**\n * Best-effort: resolve the Next.js project root (the dir that owns .next/) even in monorepos.\n *\n * Why: In monorepos, process.cwd() might be the workspace root (it also has package.json),\n * which would incorrectly store/read files under the wrong directory.\n */\nfunction findNextProjectRoot(): string {\n // Prefer discovering via this route module's on-disk path.\n // In Next, route code is executed from within \".next/server/...\".\n try {\n const selfPath = fileURLToPath(import.meta.url);\n const marker = sep + \".next\" + sep;\n const idx = selfPath.lastIndexOf(marker);\n if (idx !== -1) {\n return selfPath.slice(0, idx);\n }\n } catch {\n // ignore\n }\n\n // Fallback: walk up from cwd looking for .next/\n let dir = process.cwd();\n for (let i = 0; i < 20; i++) {\n if (existsSync(resolve(dir, \".next\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n // Final fallback: cwd\n return process.cwd();\n}\n\n/**\n * Validate that a path is within the allowed directory\n */\nfunction isPathWithinRoot(filePath: string, root: string): boolean {\n const resolved = resolve(filePath);\n const resolvedRoot = resolve(root);\n return resolved.startsWith(resolvedRoot + \"/\") || resolved === resolvedRoot;\n}\n\n/**\n * Find workspace root by walking up looking for pnpm-workspace.yaml or .git\n */\nfunction findWorkspaceRoot(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 10; i++) {\n if (\n existsSync(resolve(dir, \"pnpm-workspace.yaml\")) ||\n existsSync(resolve(dir, \".git\"))\n ) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return startDir;\n}\n\nexport async function GET(request: NextRequest) {\n // Block in production\n if (process.env.NODE_ENV === \"production\") {\n return NextResponse.json(\n { error: \"Not available in production\" },\n { status: 404 }\n );\n }\n\n const { searchParams } = new URL(request.url);\n const filePath = searchParams.get(\"path\");\n\n if (!filePath) {\n return NextResponse.json(\n { error: \"Missing 'path' query parameter\" },\n { status: 400 }\n );\n }\n\n // Validate extension\n const ext = extname(filePath).toLowerCase();\n if (!ALLOWED_EXTENSIONS.has(ext)) {\n return NextResponse.json(\n { error: \\`File extension '\\${ext}' not allowed\\` },\n { status: 403 }\n );\n }\n\n // Find project root (prefer Next project root over workspace root)\n const projectRoot = findNextProjectRoot();\n\n // Resolve the file path\n const resolvedPath = resolve(filePath);\n\n // Security check: ensure path is within project root or workspace root\n const workspaceRoot = findWorkspaceRoot(projectRoot);\n const isWithinApp = isPathWithinRoot(resolvedPath, projectRoot);\n const isWithinWorkspace = isPathWithinRoot(resolvedPath, workspaceRoot);\n\n if (!isWithinApp && !isWithinWorkspace) {\n return NextResponse.json(\n { error: \"Path outside project directory\" },\n { status: 403 }\n );\n }\n\n // Check file exists\n if (!existsSync(resolvedPath)) {\n return NextResponse.json({ error: \"File not found\" }, { status: 404 });\n }\n\n try {\n const content = readFileSync(resolvedPath, \"utf-8\");\n const relativePath = relative(workspaceRoot, resolvedPath);\n\n return NextResponse.json({\n content,\n relativePath,\n projectRoot,\n workspaceRoot,\n });\n } catch (error) {\n console.error(\"[Dev Source API] Error reading file:\", error);\n return NextResponse.json({ error: \"Failed to read file\" }, { status: 500 });\n }\n}\n`;\n\nconst SCREENSHOT_ROUTE_TS = `/**\n * Dev-only API route for saving and retrieving vision analysis screenshots\n *\n * This route allows the UILint overlay to:\n * - POST: Save screenshots and element manifests for vision analysis\n * - GET: Retrieve screenshots or list available screenshots\n *\n * Security:\n * - Only available in development mode\n * - Saves to .uilint/screenshots/ directory within project\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from \"fs\";\nimport { resolve, join, dirname, basename, sep } from \"path\";\nimport { fileURLToPath } from \"url\";\n\nexport const runtime = \"nodejs\";\n\n// Maximum screenshot size (10MB)\nconst MAX_SCREENSHOT_SIZE = 10 * 1024 * 1024;\n\n/**\n * Best-effort: resolve the Next.js project root (the dir that owns .next/) even in monorepos.\n */\nfunction findNextProjectRoot(): string {\n try {\n const selfPath = fileURLToPath(import.meta.url);\n const marker = sep + \".next\" + sep;\n const idx = selfPath.lastIndexOf(marker);\n if (idx !== -1) {\n return selfPath.slice(0, idx);\n }\n } catch {\n // ignore\n }\n\n let dir = process.cwd();\n for (let i = 0; i < 20; i++) {\n if (existsSync(resolve(dir, \".next\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n return process.cwd();\n}\n\n/**\n * Get the screenshots directory path, creating it if needed\n */\nfunction getScreenshotsDir(projectRoot: string): string {\n const screenshotsDir = join(projectRoot, \".uilint\", \"screenshots\");\n if (!existsSync(screenshotsDir)) {\n mkdirSync(screenshotsDir, { recursive: true });\n }\n return screenshotsDir;\n}\n\n/**\n * Validate filename to prevent path traversal\n */\nfunction isValidFilename(filename: string): boolean {\n // Only allow alphanumeric, hyphens, underscores, and dots\n // Must end with .png, .jpeg, .jpg, or .json\n const validPattern = /^[a-zA-Z0-9_-]+\\\\.(png|jpeg|jpg|json)$/;\n return validPattern.test(filename) && !filename.includes(\"..\");\n}\n\n/**\n * POST: Save a screenshot and optionally its manifest\n */\nexport async function POST(request: NextRequest) {\n // Block in production\n if (process.env.NODE_ENV === \"production\") {\n return NextResponse.json(\n { error: \"Not available in production\" },\n { status: 404 }\n );\n }\n\n try {\n const body = await request.json();\n const { filename, imageData, manifest, analysisResult } = body;\n\n if (!filename) {\n return NextResponse.json({ error: \"Missing 'filename'\" }, { status: 400 });\n }\n\n // Validate filename\n if (!isValidFilename(filename)) {\n return NextResponse.json(\n { error: \"Invalid filename format\" },\n { status: 400 }\n );\n }\n\n // Allow \"sidecar-only\" updates (manifest/analysisResult) without re-sending image bytes.\n const hasImageData = typeof imageData === \"string\" && imageData.length > 0;\n const hasSidecar =\n typeof manifest !== \"undefined\" || typeof analysisResult !== \"undefined\";\n\n if (!hasImageData && !hasSidecar) {\n return NextResponse.json(\n { error: \"Nothing to save (provide imageData and/or manifest/analysisResult)\" },\n { status: 400 }\n );\n }\n\n // Check size (image only)\n if (hasImageData && imageData.length > MAX_SCREENSHOT_SIZE) {\n return NextResponse.json(\n { error: \"Screenshot too large (max 10MB)\" },\n { status: 413 }\n );\n }\n\n const projectRoot = findNextProjectRoot();\n const screenshotsDir = getScreenshotsDir(projectRoot);\n\n const imagePath = join(screenshotsDir, filename);\n\n // Save the image (base64 data URL) if provided\n if (hasImageData) {\n const base64Data = imageData.includes(\",\")\n ? imageData.split(\",\")[1]\n : imageData;\n writeFileSync(imagePath, Buffer.from(base64Data, \"base64\"));\n }\n\n // Save manifest and analysis result as JSON sidecar\n if (hasSidecar) {\n const jsonFilename = filename.replace(/\\\\.(png|jpeg|jpg)$/, \".json\");\n const jsonPath = join(screenshotsDir, jsonFilename);\n\n // If a sidecar already exists, merge updates (lets us POST analysisResult later without re-sending image).\n let existing: any = null;\n if (existsSync(jsonPath)) {\n try {\n existing = JSON.parse(readFileSync(jsonPath, \"utf-8\"));\n } catch {\n existing = null;\n }\n }\n\n const routeFromAnalysis =\n analysisResult && typeof analysisResult === \"object\"\n ? (analysisResult as any).route\n : undefined;\n const issuesFromAnalysis =\n analysisResult && typeof analysisResult === \"object\"\n ? (analysisResult as any).issues\n : undefined;\n\n const jsonData = {\n ...(existing && typeof existing === \"object\" ? existing : {}),\n timestamp: Date.now(),\n filename,\n screenshotFile: filename,\n route:\n typeof routeFromAnalysis === \"string\"\n ? routeFromAnalysis\n : (existing as any)?.route ?? null,\n issues:\n Array.isArray(issuesFromAnalysis)\n ? issuesFromAnalysis\n : (existing as any)?.issues ?? null,\n manifest: typeof manifest === \"undefined\" ? existing?.manifest ?? null : manifest,\n analysisResult:\n typeof analysisResult === \"undefined\"\n ? existing?.analysisResult ?? null\n : analysisResult,\n };\n writeFileSync(jsonPath, JSON.stringify(jsonData, null, 2));\n }\n\n return NextResponse.json({\n success: true,\n path: imagePath,\n projectRoot,\n screenshotsDir,\n });\n } catch (error) {\n console.error(\"[Screenshot API] Error saving screenshot:\", error);\n return NextResponse.json(\n { error: \"Failed to save screenshot\" },\n { status: 500 }\n );\n }\n}\n\n/**\n * GET: Retrieve a screenshot or list available screenshots\n */\nexport async function GET(request: NextRequest) {\n // Block in production\n if (process.env.NODE_ENV === \"production\") {\n return NextResponse.json(\n { error: \"Not available in production\" },\n { status: 404 }\n );\n }\n\n const { searchParams } = new URL(request.url);\n const filename = searchParams.get(\"filename\");\n const list = searchParams.get(\"list\");\n\n const projectRoot = findNextProjectRoot();\n const screenshotsDir = getScreenshotsDir(projectRoot);\n\n // List mode: return all screenshots\n if (list === \"true\") {\n try {\n const files = readdirSync(screenshotsDir);\n const screenshots = files\n .filter((f) => /\\\\.(png|jpeg|jpg)$/.test(f))\n .map((f) => {\n const jsonFile = f.replace(/\\\\.(png|jpeg|jpg)$/, \".json\");\n const jsonPath = join(screenshotsDir, jsonFile);\n let metadata = null;\n if (existsSync(jsonPath)) {\n try {\n metadata = JSON.parse(readFileSync(jsonPath, \"utf-8\"));\n } catch {\n // Ignore parse errors\n }\n }\n return {\n filename: f,\n metadata,\n };\n })\n .sort((a, b) => {\n // Sort by timestamp descending (newest first)\n const aTime = a.metadata?.timestamp || 0;\n const bTime = b.metadata?.timestamp || 0;\n return bTime - aTime;\n });\n\n return NextResponse.json({ screenshots, projectRoot, screenshotsDir });\n } catch (error) {\n console.error(\"[Screenshot API] Error listing screenshots:\", error);\n return NextResponse.json(\n { error: \"Failed to list screenshots\" },\n { status: 500 }\n );\n }\n }\n\n // Retrieve mode: get specific screenshot\n if (!filename) {\n return NextResponse.json(\n { error: \"Missing 'filename' parameter\" },\n { status: 400 }\n );\n }\n\n if (!isValidFilename(filename)) {\n return NextResponse.json(\n { error: \"Invalid filename format\" },\n { status: 400 }\n );\n }\n\n const filePath = join(screenshotsDir, filename);\n\n if (!existsSync(filePath)) {\n return NextResponse.json(\n { error: \"Screenshot not found\" },\n { status: 404 }\n );\n }\n\n try {\n const content = readFileSync(filePath);\n \n // Determine content type\n const ext = filename.split(\".\").pop()?.toLowerCase();\n const contentType =\n ext === \"json\"\n ? \"application/json\"\n : ext === \"png\"\n ? \"image/png\"\n : \"image/jpeg\";\n\n if (ext === \"json\") {\n return NextResponse.json(JSON.parse(content.toString()));\n }\n\n return new NextResponse(content, {\n headers: {\n \"Content-Type\": contentType,\n \"Cache-Control\": \"no-cache\",\n },\n });\n } catch (error) {\n console.error(\"[Screenshot API] Error reading screenshot:\", error);\n return NextResponse.json(\n { error: \"Failed to read screenshot\" },\n { status: 500 }\n );\n }\n}\n`;\n\nasync function writeRouteFile(\n absPath: string,\n relPath: string,\n content: string,\n opts: InstallNextRoutesOptions\n): Promise<void> {\n // This generator is deterministic; no confirmOverwrite prompts needed.\n // If a file exists and we're not forcing, just skip it.\n if (existsSync(absPath) && !opts.force) return;\n await writeFile(absPath, content, \"utf-8\");\n}\n\nexport async function installNextUILintRoutes(\n opts: InstallNextRoutesOptions\n): Promise<void> {\n const baseRel = join(opts.appRoot, \"api\", \".uilint\");\n const baseAbs = join(opts.projectPath, baseRel);\n\n // UILint API routes\n\n // Source file API (for source visualization in overlay)\n await mkdir(join(baseAbs, \"source\"), { recursive: true });\n\n await writeRouteFile(\n join(baseAbs, \"source\", \"route.ts\"),\n join(baseRel, \"source\", \"route.ts\"),\n DEV_SOURCE_ROUTE_TS,\n opts\n );\n\n // Screenshot API (for vision analysis screenshots)\n await mkdir(join(baseAbs, \"screenshots\"), { recursive: true });\n\n await writeRouteFile(\n join(baseAbs, \"screenshots\", \"route.ts\"),\n join(baseRel, \"screenshots\", \"route.ts\"),\n SCREENSHOT_ROUTE_TS,\n opts\n );\n}\n","/**\n * Prettier formatting utilities\n *\n * Formats files using the target project's prettier if available.\n * Falls back gracefully if prettier is not installed.\n */\n\nimport { existsSync } from \"fs\";\nimport { spawn } from \"child_process\";\nimport { join, dirname } from \"path\";\nimport { detectPackageManager, type PackageManager } from \"./package-manager.js\";\n\n/**\n * Check if prettier is available in the target project\n */\nexport function hasPrettier(projectPath: string): boolean {\n // Check for prettier in node_modules\n const prettierPath = join(projectPath, \"node_modules\", \".bin\", \"prettier\");\n if (existsSync(prettierPath)) return true;\n\n // Walk up to find prettier (monorepo support)\n let dir = projectPath;\n for (let i = 0; i < 10; i++) {\n const binPath = join(dir, \"node_modules\", \".bin\", \"prettier\");\n if (existsSync(binPath)) return true;\n\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n return false;\n}\n\n/**\n * Get the prettier executable path for the project\n */\nfunction getPrettierPath(projectPath: string): string | null {\n // Check local first\n const localPath = join(projectPath, \"node_modules\", \".bin\", \"prettier\");\n if (existsSync(localPath)) return localPath;\n\n // Walk up for monorepo\n let dir = projectPath;\n for (let i = 0; i < 10; i++) {\n const binPath = join(dir, \"node_modules\", \".bin\", \"prettier\");\n if (existsSync(binPath)) return binPath;\n\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n return null;\n}\n\n/**\n * Get the package manager runner command (npx, pnpm exec, yarn, bunx)\n */\nfunction getPmRunner(pm: PackageManager): { command: string; args: string[] } {\n switch (pm) {\n case \"pnpm\":\n return { command: \"pnpm\", args: [\"exec\"] };\n case \"yarn\":\n return { command: \"yarn\", args: [] };\n case \"bun\":\n return { command: \"bunx\", args: [] };\n case \"npm\":\n default:\n return { command: \"npx\", args: [] };\n }\n}\n\n/**\n * Format a file using prettier\n *\n * @param filePath - Absolute path to the file to format\n * @param projectPath - Project root (used to find prettier config)\n * @returns Promise that resolves when formatting is complete\n */\nexport async function formatWithPrettier(\n filePath: string,\n projectPath: string\n): Promise<{ formatted: boolean; error?: string }> {\n const prettierPath = getPrettierPath(projectPath);\n\n if (!prettierPath) {\n // Try using package manager runner as fallback\n const pm = detectPackageManager(projectPath);\n const runner = getPmRunner(pm);\n\n return new Promise((resolve) => {\n const args = [...runner.args, \"prettier\", \"--write\", filePath];\n const child = spawn(runner.command, args, {\n cwd: projectPath,\n stdio: \"pipe\",\n shell: process.platform === \"win32\",\n });\n\n let stderr = \"\";\n child.stderr?.on(\"data\", (data) => {\n stderr += data.toString();\n });\n\n child.on(\"error\", () => {\n // Prettier not available, that's OK\n resolve({ formatted: false, error: \"prettier not available\" });\n });\n\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolve({ formatted: true });\n } else {\n // Non-zero exit could mean prettier isn't installed\n resolve({ formatted: false, error: stderr || \"prettier failed\" });\n }\n });\n });\n }\n\n return new Promise((resolve) => {\n const child = spawn(prettierPath, [\"--write\", filePath], {\n cwd: projectPath,\n stdio: \"pipe\",\n shell: process.platform === \"win32\",\n });\n\n let stderr = \"\";\n child.stderr?.on(\"data\", (data) => {\n stderr += data.toString();\n });\n\n child.on(\"error\", (err) => {\n resolve({ formatted: false, error: err.message });\n });\n\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolve({ formatted: true });\n } else {\n resolve({ formatted: false, error: stderr || `exit code ${code}` });\n }\n });\n });\n}\n\n/**\n * Format multiple files using prettier\n *\n * @param filePaths - Array of absolute file paths to format\n * @param projectPath - Project root (used to find prettier config)\n * @returns Promise that resolves when all formatting is complete\n */\nexport async function formatFilesWithPrettier(\n filePaths: string[],\n projectPath: string\n): Promise<{ formatted: string[]; failed: string[] }> {\n if (filePaths.length === 0) {\n return { formatted: [], failed: [] };\n }\n\n const prettierPath = getPrettierPath(projectPath);\n const formatted: string[] = [];\n const failed: string[] = [];\n\n if (!prettierPath) {\n // Try using package manager runner\n const pm = detectPackageManager(projectPath);\n const runner = getPmRunner(pm);\n\n return new Promise((resolve) => {\n const args = [...runner.args, \"prettier\", \"--write\", ...filePaths];\n const child = spawn(runner.command, args, {\n cwd: projectPath,\n stdio: \"pipe\",\n shell: process.platform === \"win32\",\n });\n\n child.on(\"error\", () => {\n // Prettier not available\n resolve({ formatted: [], failed: filePaths });\n });\n\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolve({ formatted: filePaths, failed: [] });\n } else {\n resolve({ formatted: [], failed: filePaths });\n }\n });\n });\n }\n\n // Format all files in one prettier call for efficiency\n return new Promise((resolve) => {\n const child = spawn(prettierPath, [\"--write\", ...filePaths], {\n cwd: projectPath,\n stdio: \"pipe\",\n shell: process.platform === \"win32\",\n });\n\n child.on(\"error\", () => {\n resolve({ formatted: [], failed: filePaths });\n });\n\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolve({ formatted: filePaths, failed: [] });\n } else {\n // If batch fails, try individual files\n Promise.all(\n filePaths.map(async (fp) => {\n const result = await formatWithPrettier(fp, projectPath);\n if (result.formatted) {\n formatted.push(fp);\n } else {\n failed.push(fp);\n }\n })\n ).then(() => {\n resolve({ formatted, failed });\n });\n }\n });\n });\n}\n","/**\n * Genstyleguide installer - Cursor command for generating style guides\n */\n\nimport { join } from \"path\";\nimport type { Installer, InstallTarget, InstallerConfig, ProgressEvent } from \"./types.js\";\nimport type { ProjectState, InstallAction, DependencyInstall } from \"../types.js\";\nimport { GENSTYLEGUIDE_COMMAND_MD } from \"../constants.js\";\n\nexport const genstyleguideInstaller: Installer = {\n id: \"genstyleguide\",\n name: \"/genstyleguide command\",\n description: \"Cursor command to generate UI style guides\",\n icon: \"📝\",\n\n isApplicable(project: ProjectState): boolean {\n // Always applicable - works in any project\n return true;\n },\n\n getTargets(project: ProjectState): InstallTarget[] {\n const commandPath = join(project.cursorDir.path, \"commands\", \"genstyleguide.md\");\n const isInstalled = project.commands.genstyleguide;\n\n return [\n {\n id: \"genstyleguide-command\",\n label: \".cursor/commands/genstyleguide.md\",\n path: commandPath,\n isInstalled,\n },\n ];\n },\n\n plan(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): {\n actions: InstallAction[];\n dependencies: DependencyInstall[];\n } {\n const actions: InstallAction[] = [];\n\n // Ensure .cursor/commands directory exists\n const commandsDir = join(project.cursorDir.path, \"commands\");\n\n if (!project.cursorDir.exists) {\n actions.push({\n type: \"create_directory\",\n path: project.cursorDir.path,\n });\n }\n\n actions.push({\n type: \"create_directory\",\n path: commandsDir,\n });\n\n // Create the command file\n actions.push({\n type: \"create_file\",\n path: join(commandsDir, \"genstyleguide.md\"),\n content: GENSTYLEGUIDE_COMMAND_MD,\n });\n\n return {\n actions,\n dependencies: [],\n };\n },\n\n async *execute(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): AsyncGenerator<ProgressEvent> {\n yield {\n type: \"start\",\n message: \"Installing /genstyleguide command\",\n };\n\n yield {\n type: \"progress\",\n message: \"Creating .cursor/commands directory\",\n };\n\n yield {\n type: \"progress\",\n message: \"Writing command file\",\n detail: \"→ .cursor/commands/genstyleguide.md\",\n };\n\n yield {\n type: \"complete\",\n message: \"Installed /genstyleguide command\",\n };\n },\n};\n","/**\n * Skill installer - Claude Code Agent Skills for UI consistency\n */\n\nimport { existsSync } from \"fs\";\nimport { join } from \"path\";\nimport type { Installer, InstallTarget, InstallerConfig, ProgressEvent } from \"./types.js\";\nimport type { ProjectState, InstallAction, DependencyInstall } from \"../types.js\";\nimport { loadSkill } from \"../../../utils/skill-loader.js\";\n\nexport const skillInstaller: Installer = {\n id: \"skill\",\n name: \"UI Consistency Agent skill\",\n description: \"Claude Code skill for enforcing UI consistency\",\n icon: \"⚡\",\n\n isApplicable(project: ProjectState): boolean {\n // Always applicable - works in any project\n return true;\n },\n\n getTargets(project: ProjectState): InstallTarget[] {\n const skillsDir = join(project.cursorDir.path, \"skills\", \"ui-consistency-enforcer\");\n const skillMdPath = join(skillsDir, \"SKILL.md\");\n\n // Check if skill is already installed by checking for SKILL.md\n const isInstalled = existsSync(skillMdPath);\n\n return [\n {\n id: \"ui-consistency-skill\",\n label: \".cursor/skills/ui-consistency-enforcer\",\n path: skillsDir,\n isInstalled,\n hint: \"Agent skill for UI consistency checks\",\n },\n ];\n },\n\n plan(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): {\n actions: InstallAction[];\n dependencies: DependencyInstall[];\n } {\n const actions: InstallAction[] = [];\n\n // Ensure .cursor directory exists\n if (!project.cursorDir.exists) {\n actions.push({\n type: \"create_directory\",\n path: project.cursorDir.path,\n });\n }\n\n // Create skills directory\n const skillsDir = join(project.cursorDir.path, \"skills\");\n actions.push({\n type: \"create_directory\",\n path: skillsDir,\n });\n\n // Load and install the ui-consistency-enforcer skill\n try {\n const skill = loadSkill(\"ui-consistency-enforcer\");\n const skillDir = join(skillsDir, skill.name);\n\n // Create skill directory\n actions.push({\n type: \"create_directory\",\n path: skillDir,\n });\n\n // Create all skill files\n for (const file of skill.files) {\n const filePath = join(skillDir, file.relativePath);\n\n // Ensure subdirectories exist (e.g., references/)\n const fileDir = join(\n skillDir,\n file.relativePath.split(\"/\").slice(0, -1).join(\"/\")\n );\n if (fileDir !== skillDir && file.relativePath.includes(\"/\")) {\n actions.push({\n type: \"create_directory\",\n path: fileDir,\n });\n }\n\n actions.push({\n type: \"create_file\",\n path: filePath,\n content: file.content,\n });\n }\n } catch (error) {\n // Skill not found - this shouldn't happen in normal install\n console.warn(\"Failed to load ui-consistency-enforcer skill:\", error);\n }\n\n return {\n actions,\n dependencies: [],\n };\n },\n\n async *execute(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): AsyncGenerator<ProgressEvent> {\n yield {\n type: \"start\",\n message: \"Installing UI Consistency Agent skill\",\n };\n\n yield {\n type: \"progress\",\n message: \"Creating .cursor/skills directory\",\n };\n\n try {\n const skill = loadSkill(\"ui-consistency-enforcer\");\n\n for (const file of skill.files) {\n yield {\n type: \"progress\",\n message: \"Writing skill file\",\n detail: `→ ${file.relativePath}`,\n };\n }\n\n yield {\n type: \"complete\",\n message: \"Installed UI Consistency Agent skill\",\n };\n } catch (error) {\n yield {\n type: \"error\",\n message: \"Failed to install skill\",\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n};\n","/**\n * ESLint installer - UILint ESLint plugin configuration\n *\n * Provides interactive rule selection and severity configuration during install.\n */\n\nimport { join } from \"path\";\nimport { ruleRegistry, getRulesByCategory, getRuleDocs } from \"uilint-eslint\";\nimport type {\n Installer,\n InstallTarget,\n InstallerConfig,\n ProgressEvent,\n} from \"./types.js\";\nimport type {\n ProjectState,\n InstallAction,\n DependencyInstall,\n} from \"../types.js\";\nimport type { RuleMeta } from \"uilint-eslint\";\nimport * as prompts from \"../../../utils/prompts.js\";\n\nfunction toInstallSpecifier(pkgName: string): string {\n return pkgName;\n}\n\n/**\n * Configured rule with user-selected severity\n */\nexport interface ConfiguredRule {\n /** Rule metadata */\n rule: RuleMeta;\n /** User-selected severity */\n severity: \"error\" | \"warn\" | \"off\";\n /** Custom options (if user configured them) */\n options?: unknown[];\n}\n\nexport interface ESLintInstallerConfig extends InstallerConfig {\n /** Selected rules with their configurations */\n configuredRules: ConfiguredRule[];\n}\n\n/**\n * Format rule for display in multiselect\n */\nfunction formatRuleOption(rule: RuleMeta): {\n value: string;\n label: string;\n hint: string;\n} {\n const severityBadge =\n rule.defaultSeverity === \"error\"\n ? prompts.pc.red(\"error\")\n : prompts.pc.yellow(\"warn\");\n return {\n value: rule.id,\n label: `${rule.name}`,\n hint: `${rule.description} [${severityBadge}]`,\n };\n}\n\n/**\n * Display rule documentation in a nice format\n */\nfunction showRuleDoc(rule: RuleMeta): void {\n prompts.note(\n rule.docs.trim().slice(0, 500) + (rule.docs.length > 500 ? \"...\" : \"\"),\n `📖 ${rule.name}`\n );\n}\n\nexport const eslintInstaller: Installer = {\n id: \"eslint\",\n name: \"ESLint plugin\",\n description: \"Lint UI consistency with ESLint rules\",\n icon: \"🔍\",\n\n isApplicable(project: ProjectState): boolean {\n return project.packages.some((pkg) => pkg.eslintConfigPath !== null);\n },\n\n getTargets(project: ProjectState): InstallTarget[] {\n return project.packages\n .filter((pkg) => pkg.eslintConfigPath !== null)\n .map((pkg) => ({\n id: `eslint-${pkg.name}`,\n label: pkg.name,\n path: pkg.path,\n hint: pkg.eslintConfigFilename || \"ESLint config detected\",\n isInstalled: pkg.hasUilintRules,\n }));\n },\n\n async configure(\n targets: InstallTarget[],\n project: ProjectState\n ): Promise<ESLintInstallerConfig> {\n const staticRules = getRulesByCategory(\"static\");\n const semanticRules = getRulesByCategory(\"semantic\");\n\n // Step 1: Ask about installation mode\n const installMode = await prompts.select({\n message: \"How would you like to configure UILint ESLint rules?\",\n options: [\n {\n value: \"recommended\",\n label: \"Recommended (static rules only)\",\n hint: \"Best for most projects - fast and reliable\",\n },\n {\n value: \"strict\",\n label: \"Strict (all rules including semantic)\",\n hint: \"Includes LLM-powered analysis - requires Ollama\",\n },\n {\n value: \"custom\",\n label: \"Custom selection\",\n hint: \"Choose individual rules and configure severity\",\n },\n ],\n });\n\n let selectedRuleIds: string[];\n let configuredRules: ConfiguredRule[];\n\n if (installMode === \"recommended\") {\n // Use all static rules with default severity\n configuredRules = staticRules.map((rule) => ({\n rule,\n severity: rule.defaultSeverity as \"error\" | \"warn\",\n options: rule.defaultOptions,\n }));\n } else if (installMode === \"strict\") {\n // Use all rules with default severity\n configuredRules = ruleRegistry.map((rule) => ({\n rule,\n severity: rule.defaultSeverity as \"error\" | \"warn\",\n options: rule.defaultOptions,\n }));\n } else {\n // Custom selection flow\n prompts.log(prompts.pc.dim(\"\\n📋 Static rules (pattern-based, fast):\"));\n\n // Select static rules\n const selectedStaticIds = await prompts.multiselect({\n message: \"Select static rules to enable:\",\n options: staticRules.map(formatRuleOption),\n initialValues: staticRules.map((r) => r.id),\n });\n\n // Ask about semantic rules\n const includeSemanticRules = await prompts.confirm({\n message: `Include semantic rules? ${prompts.pc.dim(\n \"(requires Ollama for LLM analysis)\"\n )}`,\n initialValue: false,\n });\n\n let selectedSemanticIds: string[] = [];\n if (includeSemanticRules) {\n prompts.log(\n prompts.pc.dim(\"\\n🧠 Semantic rules (LLM-powered, slower):\")\n );\n selectedSemanticIds = await prompts.multiselect({\n message: \"Select semantic rules:\",\n options: semanticRules.map(formatRuleOption),\n initialValues: semanticRules.map((r) => r.id),\n });\n }\n\n selectedRuleIds = [...selectedStaticIds, ...selectedSemanticIds];\n\n // Step 2: Configure severity for each selected rule\n const configureSeverity = await prompts.confirm({\n message: \"Would you like to customize severity levels?\",\n initialValue: false,\n });\n\n configuredRules = [];\n\n for (const ruleId of selectedRuleIds) {\n const rule = ruleRegistry.find((r) => r.id === ruleId)!;\n\n if (configureSeverity) {\n const severity = await prompts.select({\n message: `${rule.name} - severity:`,\n options: [\n {\n value: rule.defaultSeverity,\n label: `${rule.defaultSeverity} (default)`,\n },\n ...(rule.defaultSeverity !== \"error\"\n ? [{ value: \"error\" as const, label: \"error\" }]\n : []),\n ...(rule.defaultSeverity !== \"warn\"\n ? [{ value: \"warn\" as const, label: \"warn\" }]\n : []),\n ],\n initialValue: rule.defaultSeverity,\n });\n\n configuredRules.push({\n rule,\n severity: severity as \"error\" | \"warn\",\n options: rule.defaultOptions,\n });\n } else {\n configuredRules.push({\n rule,\n severity: rule.defaultSeverity as \"error\" | \"warn\",\n options: rule.defaultOptions,\n });\n }\n }\n }\n\n // Summary\n const errorCount = configuredRules.filter(\n (r) => r.severity === \"error\"\n ).length;\n const warnCount = configuredRules.filter(\n (r) => r.severity === \"warn\"\n ).length;\n\n prompts.log(\"\");\n prompts.note(\n configuredRules\n .map(\n (cr) =>\n `${cr.severity === \"error\" ? \"🔴\" : \"🟡\"} ${cr.rule.name} (${\n cr.severity\n })`\n )\n .join(\"\\n\"),\n `Selected ${configuredRules.length} rules (${errorCount} errors, ${warnCount} warnings)`\n );\n\n return { configuredRules };\n },\n\n plan(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): {\n actions: InstallAction[];\n dependencies: DependencyInstall[];\n } {\n const actions: InstallAction[] = [];\n const dependencies: DependencyInstall[] = [];\n const eslintConfig = config as ESLintInstallerConfig;\n const { configuredRules } = eslintConfig;\n\n // Convert configuredRules to the format expected by inject_eslint\n const rulesWithSeverity = configuredRules.map((cr) => ({\n ...cr.rule,\n defaultSeverity: cr.severity,\n defaultOptions: cr.options,\n }));\n\n for (const target of targets) {\n const pkgInfo = project.packages.find((p) => p.path === target.path);\n if (!pkgInfo || !pkgInfo.eslintConfigPath) continue;\n\n // Create .uilint/rules directory\n const rulesDir = join(target.path, \".uilint\", \"rules\");\n actions.push({\n type: \"create_directory\",\n path: rulesDir,\n });\n\n // Install dependencies\n dependencies.push({\n packagePath: target.path,\n packageManager: project.packageManager,\n packages: [toInstallSpecifier(\"uilint-eslint\"), \"typescript-eslint\"],\n });\n\n // Inject ESLint rules\n actions.push({\n type: \"inject_eslint\",\n packagePath: target.path,\n configPath: pkgInfo.eslintConfigPath,\n rules: rulesWithSeverity,\n hasExistingRules: pkgInfo.hasUilintRules,\n });\n }\n\n // Add .uilint/.cache to .gitignore\n const gitignorePath = join(project.workspaceRoot, \".gitignore\");\n actions.push({\n type: \"append_to_file\",\n path: gitignorePath,\n content: \"\\n# UILint cache\\n.uilint/.cache\\n\",\n ifNotContains: \".uilint/.cache\",\n });\n\n return { actions, dependencies };\n },\n\n async *execute(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): AsyncGenerator<ProgressEvent> {\n const eslintConfig = config as ESLintInstallerConfig;\n\n yield {\n type: \"start\",\n message: \"Installing ESLint plugin\",\n };\n\n for (const target of targets) {\n yield {\n type: \"progress\",\n message: `Configuring ESLint in ${target.label}`,\n detail: \"→ Adding uilint-eslint to dependencies\",\n };\n\n yield {\n type: \"progress\",\n message: `Injecting ${eslintConfig.configuredRules.length} rules`,\n detail: `→ ${target.hint}`,\n };\n }\n\n yield {\n type: \"complete\",\n message: `ESLint plugin installed in ${targets.length} package(s)`,\n };\n },\n};\n","/**\n * Next.js overlay installer - UI devtools for Next.js App Router apps\n */\n\nimport type { Installer, InstallTarget, InstallerConfig, ProgressEvent } from \"./types.js\";\nimport type { ProjectState, InstallAction, DependencyInstall } from \"../types.js\";\n\nexport const nextOverlayInstaller: Installer = {\n id: \"next\",\n name: \"Next.js overlay\",\n description: \"Alt+Click UI inspector for Next.js App Router\",\n icon: \"🔷\",\n\n isApplicable(project: ProjectState): boolean {\n return project.nextApps.length > 0;\n },\n\n getTargets(project: ProjectState): InstallTarget[] {\n return project.nextApps.map((app) => ({\n id: `next-${app.projectPath}`,\n label: app.projectPath.split(\"/\").pop() || app.projectPath,\n path: app.projectPath,\n hint: \"App Router\",\n isInstalled: false, // TODO: Detect if already installed\n }));\n },\n\n plan(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): {\n actions: InstallAction[];\n dependencies: DependencyInstall[];\n } {\n const actions: InstallAction[] = [];\n const dependencies: DependencyInstall[] = [];\n\n // Only install for the first selected target\n if (targets.length === 0) return { actions, dependencies };\n\n const target = targets[0];\n const appInfo = project.nextApps.find((app) => app.projectPath === target.path);\n if (!appInfo) return { actions, dependencies };\n\n const { projectPath, detection } = appInfo;\n\n // Install Next.js routes\n actions.push({\n type: \"install_next_routes\",\n projectPath,\n appRoot: detection.appRoot,\n });\n\n // Install React overlay dependencies\n dependencies.push({\n packagePath: projectPath,\n packageManager: project.packageManager,\n packages: [\"uilint-react\", \"uilint-core\", \"jsx-loc-plugin\"],\n });\n\n // Inject <uilint-devtools /> web component into React\n actions.push({\n type: \"inject_react\",\n projectPath,\n appRoot: detection.appRoot,\n mode: \"next\",\n });\n\n // Inject jsx-loc-plugin into next.config\n actions.push({\n type: \"inject_next_config\",\n projectPath,\n });\n\n return { actions, dependencies };\n },\n\n async *execute(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): AsyncGenerator<ProgressEvent> {\n if (targets.length === 0) return;\n\n const target = targets[0];\n\n yield {\n type: \"start\",\n message: \"Installing Next.js overlay\",\n };\n\n yield {\n type: \"progress\",\n message: `Installing in ${target.label}`,\n detail: \"→ Adding API routes\",\n };\n\n yield {\n type: \"progress\",\n message: \"Installing dependencies\",\n detail: \"→ uilint-react, uilint-core, jsx-loc-plugin\",\n };\n\n yield {\n type: \"progress\",\n message: \"Injecting devtools component\",\n detail: \"→ <uilint-devtools /> in root layout\",\n };\n\n yield {\n type: \"progress\",\n message: \"Configuring jsx-loc-plugin\",\n detail: \"→ next.config.js\",\n };\n\n yield {\n type: \"complete\",\n message: \"Next.js overlay installed\",\n };\n },\n};\n","/**\n * Vite overlay installer - UI devtools for Vite + React apps\n */\n\nimport type { Installer, InstallTarget, InstallerConfig, ProgressEvent } from \"./types.js\";\nimport type { ProjectState, InstallAction, DependencyInstall } from \"../types.js\";\n\nexport const viteOverlayInstaller: Installer = {\n id: \"vite\",\n name: \"Vite overlay\",\n description: \"Alt+Click UI inspector for Vite + React apps\",\n icon: \"⚡\",\n\n isApplicable(project: ProjectState): boolean {\n return project.viteApps.length > 0;\n },\n\n getTargets(project: ProjectState): InstallTarget[] {\n return project.viteApps.map((app) => ({\n id: `vite-${app.projectPath}`,\n label: app.projectPath.split(\"/\").pop() || app.projectPath,\n path: app.projectPath,\n hint: \"React + Vite\",\n isInstalled: false, // TODO: Detect if already installed\n }));\n },\n\n plan(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): {\n actions: InstallAction[];\n dependencies: DependencyInstall[];\n } {\n const actions: InstallAction[] = [];\n const dependencies: DependencyInstall[] = [];\n\n // Only install for the first selected target\n if (targets.length === 0) return { actions, dependencies };\n\n const target = targets[0];\n const appInfo = project.viteApps.find((app) => app.projectPath === target.path);\n if (!appInfo) return { actions, dependencies };\n\n const { projectPath, detection } = appInfo;\n\n // Install React overlay dependencies\n dependencies.push({\n packagePath: projectPath,\n packageManager: project.packageManager,\n packages: [\"uilint-react\", \"uilint-core\", \"jsx-loc-plugin\"],\n });\n\n // Inject <uilint-devtools /> web component into React entry\n actions.push({\n type: \"inject_react\",\n projectPath,\n appRoot: detection.entryRoot,\n mode: \"vite\",\n });\n\n // Inject jsx-loc-plugin into vite.config\n actions.push({\n type: \"inject_vite_config\",\n projectPath,\n });\n\n return { actions, dependencies };\n },\n\n async *execute(\n targets: InstallTarget[],\n config: InstallerConfig,\n project: ProjectState\n ): AsyncGenerator<ProgressEvent> {\n if (targets.length === 0) return;\n\n const target = targets[0];\n\n yield {\n type: \"start\",\n message: \"Installing Vite overlay\",\n };\n\n yield {\n type: \"progress\",\n message: `Installing in ${target.label}`,\n detail: \"→ Adding dependencies\",\n };\n\n yield {\n type: \"progress\",\n message: \"Installing dependencies\",\n detail: \"→ uilint-react, uilint-core, jsx-loc-plugin\",\n };\n\n yield {\n type: \"progress\",\n message: \"Injecting devtools component\",\n detail: \"→ <uilint-devtools /> in entry file\",\n };\n\n yield {\n type: \"progress\",\n message: \"Configuring jsx-loc-plugin\",\n detail: \"→ vite.config.ts\",\n };\n\n yield {\n type: \"complete\",\n message: \"Vite overlay installed\",\n };\n },\n};\n","/**\n * Installer registry - auto-registration of all installers\n */\n\nimport { registerInstaller } from \"./registry.js\";\nimport { genstyleguideInstaller } from \"./genstyleguide.js\";\nimport { skillInstaller } from \"./skill.js\";\nimport { eslintInstaller } from \"./eslint.js\";\nimport { nextOverlayInstaller } from \"./next-overlay.js\";\nimport { viteOverlayInstaller } from \"./vite-overlay.js\";\n\n// Export types\nexport * from \"./types.js\";\nexport * from \"./registry.js\";\n\n// Export individual installers\nexport { genstyleguideInstaller } from \"./genstyleguide.js\";\nexport { skillInstaller } from \"./skill.js\";\nexport { eslintInstaller } from \"./eslint.js\";\nexport { nextOverlayInstaller } from \"./next-overlay.js\";\nexport { viteOverlayInstaller } from \"./vite-overlay.js\";\n\n// Auto-register all installers\nregisterInstaller(genstyleguideInstaller);\nregisterInstaller(skillInstaller);\nregisterInstaller(eslintInstaller);\nregisterInstaller(nextOverlayInstaller);\nregisterInstaller(viteOverlayInstaller);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWA,SAAS,cAAc;;;ACFvB,SAAgB,YAAAA,WAAU,aAAAC,kBAAiB;AAC3C,SAAS,OAAAC,MAAK,QAAAC,OAAM,UAAAC,SAAQ,YAAAC,iBAAgB;;;ACN5C,SAAgB,UAAU,iBAAiB;AAC3C,SAAS,YAAY;AAiBZ;AAfT,IAAM,SAAS,CAAC,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAG;AAEzD,SAAS,UAA8B;AAC5C,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,CAAC;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AAA,QACC;AAAA,QACA,YAAY,OAAO,YAAY,gBAAgB;AAE7C,gBAAM,UAAU,MAAM;AACtB,gBAAM,UAAU,wBAAwB,YAAY,SAAS,WAAW;AAExE,cAAI,QAAQ,MAAM,WAAW,GAAG;AAC9B,oBAAQ,IAAI,sCAAsC;AAClD,oBAAQ,KAAK,CAAC;AAAA,UAChB;AAGA,gBAAM,EAAE,WAAW,IAAI,MAAM,OAAO,oBAAmB;AACvD,gBAAM,OAAO,WAAW,SAAS,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AAGlE,gBAAM,SAAS,MAAM,QAAQ,MAAM;AAAA,YACjC,GAAG;AAAA,YACH,aAAa,QAAQ;AAAA,UACvB,CAAC;AAGD,cAAI,OAAO,SAAS;AAClB,oBAAQ,IAAI,+CAA0C;AAAA,UACxD,OAAO;AACL,oBAAQ,IAAI,6CAAwC;AAAA,UACtD;AAEA,kBAAQ,KAAK,OAAO,UAAU,IAAI,CAAC;AAAA,QACrC;AAAA,QACA,SAAS,CAAC,UAAU;AAClB,kBAAQ,MAAM,mBAAc,MAAM,OAAO;AACzC,kBAAQ,KAAK,CAAC;AAAA,QAChB;AAAA;AAAA,IACF;AAAA,EACF;AAGA,QAAM,cAAc;AACtB;","names":["useState","useEffect","Box","Text","useApp","useInput","useState","Text","jsx","useState","Box","Text","useInput","useApp","jsx","jsxs","useState","Box","Text","useInput","useApp","jsx","jsxs","jsx","jsxs","Box","Text","useInput","useApp","useState","useEffect","installers","existsSync","readFileSync","join","findWorkspaceRoot","existsSync","readdirSync","readFileSync","join","DEFAULT_IGNORE_DIRS","existsSync","join","existsSync","readFileSync","join","relative","dirname","unwrapExpression","program","dirname","join","relative","readFileSync","join","existsSync","findWorkspaceRoot","join","existsSync","readFileSync","existsSync","writeFileSync","readFileSync","dirname","existsSync","readFileSync","writeFileSync","join","parseModule","generateCode","parseModule","join","readFileSync","generateCode","writeFileSync","existsSync","readFileSync","writeFileSync","join","parseModule","generateCode","CONFIG_EXTENSIONS","isIdentifier","isStringLiteral","parseModule","readFileSync","generateCode","writeFileSync","existsSync","readFileSync","writeFileSync","join","parseModule","generateCode","CONFIG_EXTENSIONS","findViteConfigFile","isIdentifier","isStringLiteral","jsxLocCall","existsSync","join","existsSync","spawn","join","dirname","join","existsSync","dirname","spawn","existsSync","dirname","writeFileSync","readFileSync","installDependencies","ruleRegistry","existsSync","join","join","join","existsSync","join","join","existsSync","join","ruleRegistry","getRulesByCategory","getRulesByCategory","ruleRegistry","join","jsx","ruleRegistry","existsSync","join"]}
|