Files
2025-11-02 12:16:10 -08:00

13 lines
13 KiB
JSON

{
"name": "ai-code-demo",
"registryDependencies": [
"ai-code"
],
"files": [
{
"name": "ai-code-demo.tsx",
"content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport {\n AICode,\n type CodeSuggestion,\n type Explanation,\n type SecurityIssue,\n} from \"@/registry/default/ui/ai-code\"\n\nexport default function AICodeDemo() {\n const [isGenerating, setIsGenerating] = React.useState(false)\n\n // Mock AI handlers for demonstration\n const handleGenerate = async (prompt: string): Promise<string> => {\n setIsGenerating(true)\n\n // Simulate API call delay\n await new Promise((resolve) => setTimeout(resolve, 2000))\n\n // Mock code generation based on prompt\n const codeTemplates: Record<string, string> = {\n \"react component\": `import React from 'react'\n\ninterface Props {\n title: string\n children: React.ReactNode\n}\n\nexport const Component: React.FC<Props> = ({ title, children }) => {\n return (\n <div className=\"component\">\n <h2>{title}</h2>\n <div>{children}</div>\n </div>\n )\n}`,\n \"api endpoint\": `export async function POST(request: Request) {\n try {\n const data = await request.json()\n\n // Process the data\n const result = await processData(data)\n\n return Response.json({ success: true, data: result })\n } catch (error) {\n return Response.json(\n { success: false, error: error.message },\n { status: 500 }\n )\n }\n}`,\n \"utility function\": `export function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): (...args: Parameters<T>) => void {\n let timeoutId: NodeJS.Timeout\n\n return (...args: Parameters<T>) => {\n clearTimeout(timeoutId)\n timeoutId = setTimeout(() => func(...args), delay)\n }\n}`,\n default: `// AI generated code based on: \"${prompt}\"\nfunction generatedFunction() {\n console.log(\"This is AI-generated code based on your prompt\")\n\n // TODO: Implement the specific functionality requested\n return \"AI Code Assistant is working!\"\n}`,\n }\n\n setIsGenerating(false)\n\n // Find matching template or use default\n const matchingKey = Object.keys(codeTemplates).find((key) =>\n prompt.toLowerCase().includes(key)\n )\n\n return codeTemplates[matchingKey || \"default\"]\n }\n\n const handleExplain = async (\n code: string,\n line?: number\n ): Promise<Explanation[]> => {\n // Mock explanation generation\n await new Promise((resolve) => setTimeout(resolve, 1000))\n\n const explanations: Explanation[] = []\n\n // Generate explanations for common patterns\n const lines = code.split(\"\\n\")\n lines.forEach((lineContent, index) => {\n const lineNumber = index + 1\n\n if (lineContent.includes(\"function\")) {\n explanations.push({\n id: `explain-${lineNumber}`,\n line: lineNumber,\n content: \"Function declaration - defines a reusable block of code\",\n type: \"explanation\",\n })\n }\n\n if (lineContent.includes(\"const\") || lineContent.includes(\"let\")) {\n explanations.push({\n id: `explain-${lineNumber}`,\n line: lineNumber,\n content: \"Variable declaration - stores a value for later use\",\n type: \"explanation\",\n })\n }\n\n if (lineContent.includes(\"export\")) {\n explanations.push({\n id: `explain-${lineNumber}`,\n line: lineNumber,\n content:\n \"Export statement - makes this function/variable available to other modules\",\n type: \"explanation\",\n })\n }\n\n if (lineContent.includes(\"// TODO\")) {\n explanations.push({\n id: `explain-${lineNumber}`,\n line: lineNumber,\n content:\n \"TODO comment - indicates functionality that needs to be implemented\",\n type: \"warning\",\n })\n }\n })\n\n return explanations\n }\n\n const handleRefactor = async (code: string): Promise<string> => {\n await new Promise((resolve) => setTimeout(resolve, 1500))\n\n // Mock refactoring - add some improvements\n let refactoredCode = code\n\n // Add proper TypeScript types if missing\n if (!code.includes(\"interface\") && code.includes(\"function\")) {\n refactoredCode = `interface RefactoredProps {\n // TODO: Define proper prop types\n}\n\n${refactoredCode}`\n }\n\n // Add error handling if missing\n if (!code.includes(\"try\") && !code.includes(\"catch\")) {\n refactoredCode = refactoredCode.replace(\n /function\\s+(\\w+)/g,\n (match, funcName) => {\n return `function ${funcName} /* Added error handling */`\n }\n )\n }\n\n // Add JSDoc comments\n refactoredCode = `/**\n * Refactored code with improvements:\n * - Added proper TypeScript types\n * - Improved error handling\n * - Added documentation\n */\n${refactoredCode}`\n\n return refactoredCode\n }\n\n const handleDebug = async (code: string): Promise<CodeSuggestion[]> => {\n await new Promise((resolve) => setTimeout(resolve, 1000))\n\n const suggestions: CodeSuggestion[] = []\n\n // Mock debugging suggestions\n if (code.includes(\"console.log\")) {\n suggestions.push({\n id: \"debug-1\",\n type: \"debug\",\n title: \"Remove Debug Logs\",\n description:\n \"Console.log statements found - consider using a proper logging library\",\n severity: \"warning\",\n code: code.replace(/console\\.log\\([^)]*\\);?\\n?/g, \"\"),\n })\n }\n\n if (!code.includes(\"error\") && !code.includes(\"try\")) {\n suggestions.push({\n id: \"debug-2\",\n type: \"debug\",\n title: \"Add Error Handling\",\n description:\n \"No error handling detected - consider adding try-catch blocks\",\n severity: \"warning\",\n })\n }\n\n if (code.includes(\"any\")) {\n suggestions.push({\n id: \"debug-3\",\n type: \"debug\",\n title: \"Fix TypeScript Types\",\n description: 'Using \"any\" type - consider using more specific types',\n severity: \"error\",\n })\n }\n\n return suggestions\n }\n\n const handleTest = async (code: string): Promise<string> => {\n await new Promise((resolve) => setTimeout(resolve, 1500))\n\n // Mock test generation\n const functionName =\n code.match(/function\\s+(\\w+)/)?.[1] || \"generatedFunction\"\n\n return `import { describe, it, expect } from '@jest/globals'\nimport { ${functionName} } from './module'\n\ndescribe('${functionName}', () => {\n it('should work correctly', () => {\n // Arrange\n const input = 'test input'\n\n // Act\n const result = ${functionName}(input)\n\n // Assert\n expect(result).toBeDefined()\n expect(typeof result).toBe('string')\n })\n\n it('should handle edge cases', () => {\n // Test edge cases\n expect(() => ${functionName}(null)).not.toThrow()\n expect(${functionName}('')).toBeTruthy()\n })\n\n it('should have proper error handling', () => {\n // Test error scenarios\n const invalidInput = undefined\n expect(() => ${functionName}(invalidInput)).not.toThrow()\n })\n})`\n }\n\n const handleDocument = async (code: string): Promise<string> => {\n await new Promise((resolve) => setTimeout(resolve, 1000))\n\n // Mock documentation generation\n const functionName = code.match(/function\\s+(\\w+)/)?.[1] || \"Function\"\n\n return `## ${functionName} Documentation\n\n### Overview\nThis function provides core functionality for the application.\n\n### Parameters\n- **input**: The input parameter (type: any)\n- **options**: Optional configuration object\n\n### Returns\nReturns the processed result based on the input.\n\n### Usage Example\n\\`\\`\\`typescript\nconst result = ${functionName}('example input')\nconsole.log(result)\n\\`\\`\\`\n\n### Notes\n- Ensure proper error handling when using this function\n- Consider TypeScript types for better type safety\n- Add input validation for production use\n\n### See Also\n- Related utility functions\n- Error handling best practices\n- TypeScript documentation`\n }\n\n const handleReview = async (code: string): Promise<CodeSuggestion[]> => {\n await new Promise((resolve) => setTimeout(resolve, 1200))\n\n const suggestions: CodeSuggestion[] = []\n\n // Mock code review suggestions\n suggestions.push({\n id: \"review-1\",\n type: \"review\",\n title: \"Code Quality\",\n description:\n \"Overall code structure looks good, but consider these improvements\",\n severity: \"info\",\n })\n\n if (!code.includes(\"export\")) {\n suggestions.push({\n id: \"review-2\",\n type: \"review\",\n title: \"Add Exports\",\n description:\n \"Consider adding export statements to make functions reusable\",\n severity: \"warning\",\n })\n }\n\n if (code.length > 1000) {\n suggestions.push({\n id: \"review-3\",\n type: \"review\",\n title: \"Function Length\",\n description:\n \"Function is quite long - consider breaking it into smaller functions\",\n severity: \"warning\",\n })\n }\n\n return suggestions\n }\n\n const handleSecurityScan = async (code: string): Promise<SecurityIssue[]> => {\n await new Promise((resolve) => setTimeout(resolve, 1500))\n\n const issues: SecurityIssue[] = []\n\n // Mock security scanning\n if (code.includes(\"eval(\")) {\n issues.push({\n id: \"security-1\",\n line: code.split(\"\\n\").findIndex((line) => line.includes(\"eval(\")) + 1,\n severity: \"critical\",\n message:\n \"Use of eval() function detected - potential code injection vulnerability\",\n fix: \"Replace eval() with safer alternatives like JSON.parse() or Function constructor\",\n })\n }\n\n if (code.includes(\"innerHTML\")) {\n issues.push({\n id: \"security-2\",\n line:\n code.split(\"\\n\").findIndex((line) => line.includes(\"innerHTML\")) + 1,\n severity: \"high\",\n message:\n \"Direct innerHTML manipulation detected - potential XSS vulnerability\",\n fix: \"Use textContent or sanitize HTML content before setting innerHTML\",\n })\n }\n\n if (code.includes(\"document.write\")) {\n issues.push({\n id: \"security-3\",\n line:\n code\n .split(\"\\n\")\n .findIndex((line) => line.includes(\"document.write\")) + 1,\n severity: \"medium\",\n message:\n \"Use of document.write() detected - can lead to XSS vulnerabilities\",\n fix: \"Use modern DOM manipulation methods instead of document.write()\",\n })\n }\n\n return issues\n }\n\n return (\n <div className=\"w-full max-w-6xl mx-auto p-4\">\n <div className=\"space-y-4\">\n <div>\n <h2 className=\"text-2xl font-bold mb-2\">AI Code Assistant Demo</h2>\n <p className=\"text-muted-foreground\">\n Try the AI-powered code assistant with features like code\n generation, explanation, refactoring, debugging, testing, and\n security scanning.\n </p>\n </div>\n\n <AICode\n defaultValue={`// Welcome to AI Code Assistant!\n// Try these commands:\n// - Type \"generate a react component\" in the chat\n// - Click \"Explain\" to get code explanations\n// - Use \"Refactor\" to improve code quality\n// - Try \"Debug\" for error detection\n// - Generate tests with \"Test\"\n// - Create documentation with \"Document\"\n// - Get code review with \"Review\"\n// - Scan for security issues with \"Security\"\n\nfunction welcome() {\n console.log(\"Start coding with AI assistance!\")\n return \"AI Code Assistant is ready to help!\"\n}`}\n language=\"typescript\"\n height=\"500px\"\n onGenerate={handleGenerate}\n onExplain={handleExplain}\n onRefactor={handleRefactor}\n onDebug={handleDebug}\n onTest={handleTest}\n onDocument={handleDocument}\n onReview={handleReview}\n onSecurityScan={handleSecurityScan}\n isGenerating={isGenerating}\n features={[\n \"generate\",\n \"explain\",\n \"refactor\",\n \"debug\",\n \"test\",\n \"document\",\n \"review\",\n ]}\n placeholder=\"Ask AI to generate code, explain functions, refactor for improvements, or help with debugging...\"\n showMinimap={false}\n showLineNumbers={true}\n />\n\n <div className=\"text-sm text-muted-foreground space-y-2\">\n <p>\n <strong>Try these prompts:</strong>\n </p>\n <ul className=\"list-disc list-inside space-y-1\">\n <li>\"Generate a React component with props\"</li>\n <li>\"Create an API endpoint for user authentication\"</li>\n <li>\"Write a utility function for debouncing\"</li>\n <li>\"Add error handling to this function\"</li>\n <li>\"Explain what this code does line by line\"</li>\n </ul>\n </div>\n </div>\n </div>\n )\n}\n"
}
],
"type": "components:example"
}