UNPKG

ctrlshiftleft

Version:

AI-powered toolkit for embedding QA and security testing into development workflows

345 lines (255 loc) 9.32 kB
# Using ctrl.shift.left with Next.js This guide provides detailed instructions for integrating the ctrl.shift.left toolkit with Next.js applications. ## Installation For Next.js projects, we recommend using our specialized setup script: ```bash # If you've installed ctrl.shift.left via npm npx ctrlshiftleft-setup --nextjs # Alternatively, you can run it directly without installation npx -p ctrlshiftleft ctrlshiftleft-setup --nextjs ``` This setup script will: 1. Install the necessary dependencies 2. Create npm scripts for QA operations 3. Configure the project for optimal compatibility 4. Set up tests and GitHub Actions workflows ## Project Structure ctrl.shift.left understands both Next.js App Router and Pages Router structures: ### App Router (Next.js 13+) ``` app/ ├── api/ <- API routes (tested with security analysis) ├── components/ <- Your React components (tested with generated tests) ├── lib/ <- Utility functions └── (routes)/ <- Route groups ``` ### Pages Router ``` pages/ ├── api/ <- API routes (tested with security analysis) ├── components/ <- Components specific to pages └── _app.js <- App wrapper components/ <- Shared components (tested with generated tests) ``` ## Recommended Scripts The setup script adds these to your `package.json`: ```json { "scripts": { "qa:gen": "npx ctrlshiftleft gen ./app/components", "qa:analyze": "npx ctrlshiftleft-ai analyze ./app", "qa:checklist": "npx ctrlshiftleft checklist ./app", "qa:watch": "npx ctrlshiftleft-watch-ai ./app", "qa": "npm run qa:gen && npm run qa:analyze && npm run qa:checklist" } } ``` ## Common Commands ```bash # Generate tests for a specific component npm run qa:gen -- ./app/components/YourComponent.tsx # Analyze security with AI enhancement (requires OPENAI_API_KEY) npm run qa:analyze -- ./app/api # Watch for changes and provide real-time feedback npm run qa:watch # Generate comprehensive QA checklist npm run qa:checklist ``` ## Integration with Next.js API Routes For API routes, we recommend adding the QA validation middleware: ```typescript // app/api/example/route.ts (App Router) import { NextResponse } from 'next/server'; import { validateInput } from '@/lib/qa'; export async function POST(req: Request) { const data = await req.json(); // Validate user input const validation = validateInput(data.userInput, 'text'); if (!validation.valid) { return NextResponse.json({ error: validation.message }, { status: 400 }); } // Process request... return NextResponse.json({ success: true }); } ``` ```typescript // pages/api/example.ts (Pages Router) import type { NextApiRequest, NextApiResponse } from 'next'; import { validateInput } from '../../lib/qa'; export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { // Validate user input const validation = validateInput(req.body.userInput, 'text'); if (!validation.valid) { return res.status(400).json({ error: validation.message }); } // Process request... return res.status(200).json({ success: true }); } res.status(405).end(); // Method Not Allowed } ``` ## In-Component QA Status You can add visual QA status indicators to your components: ```tsx // components/QAStatus.tsx import React from 'react'; import { useEffect, useState } from 'react'; interface QAStatusProps { component: string; showInProduction?: boolean; } export default function QAStatus({ component, showInProduction = false }: QAStatusProps) { const [status, setStatus] = useState<'verified' | 'pending' | 'issues' | null>(null); useEffect(() => { // Only show in development or if explicitly allowed in production if (process.env.NODE_ENV === 'production' && !showInProduction) { return; } // In a real implementation, this would fetch from your QA system const fetchStatus = async () => { try { // This is a mock - in production you would fetch real data const mockStatuses: Record<string, 'verified' | 'pending' | 'issues'> = { 'Header': 'verified', 'LoginForm': 'issues', 'ProductCard': 'pending', }; setStatus(mockStatuses[component] || 'pending'); } catch (error) { console.error('Failed to fetch QA status', error); } }; fetchStatus(); }, [component, showInProduction]); if (process.env.NODE_ENV === 'production' && !showInProduction) { return null; } if (!status) return null; const getStatusStyles = () => { const baseStyles = 'text-xs rounded px-2 py-1 font-mono'; switch (status) { case 'verified': return `${baseStyles} bg-green-100 text-green-800`; case 'issues': return `${baseStyles} bg-red-100 text-red-800`; case 'pending': default: return `${baseStyles} bg-yellow-100 text-yellow-800`; } }; return ( <div className="absolute top-0 right-0 z-50 m-1"> <span className={getStatusStyles()}> QA: {status.toUpperCase()} </span> </div> ); } ``` Usage in your components: ```tsx import QAStatus from '@/components/QAStatus'; export default function Header() { return ( <header className="relative"> <QAStatus component="Header" /> {/* Header content */} </header> ); } ``` ## Improved Path Handling (v1.3.1+) Version 1.3.1 includes significant improvements to path resolution and output handling specifically for Next.js projects: ### .ctrlshiftleft Directory The setup process now creates a `.ctrlshiftleft` directory in your project root containing: ``` .ctrlshiftleft/ ├── paths.js <- Module path configuration ├── scripts/ <- Framework-specific scripts └── validation.js <- Validation helpers ``` This structure ensures scripts can find the necessary dependencies regardless of whether ctrl.shift.left is installed locally or globally. ### Custom Output Paths You can now specify custom output paths for all operations: ```bash # Generate security report in a custom location npm run qa:analyze -- src/components/AuthForm.jsx --output=reports/security/auth-report.md # Generate tests in a custom directory npm run qa:gen -- app/components/Button.jsx --output=e2e/generated-tests ``` This is especially useful for CI/CD pipelines where you need predictable output locations. ## Troubleshooting ### Module Not Found Errors As of v1.3.1, most module resolution issues are automatically handled by the `.ctrlshiftleft` directory structure. If you still encounter "Cannot find module" errors: ```bash # Run the repair tool npx ctrlshiftleft-repair # Or reinstall with the Next.js setup npm remove ctrlshiftleft npm install --save-dev ctrlshiftleft npx ctrlshiftleft-setup-nextjs ``` ### Permission Issues For permission issues during global installation: ```bash # User-level global installation (no sudo needed) ctrlshiftleft-setup --user # Or manually configure npm install -g ctrlshiftleft --prefix ~/.npm-global export PATH=~/.npm-global/bin:$PATH # Add to your shell profile (~/.bashrc, ~/.zshrc) export PATH=~/.npm-global/bin:$PATH ``` ### Next.js App Router Specific Issues If using server components: ```bash # Generate tests for client components only npm run qa:gen -- --client-only ./app/components ``` ### Troubleshooting Framework Detection If the tool doesn't properly detect your Next.js project structure: ```bash # Run diagnostics with Next.js focus npx ctrlshiftleft-repair --nextjs # Force Next.js framework handling npx ctrlshiftleft gen ./app/components --framework=nextjs ``` The toolkit automatically detects both App Router and Pages Router structures, but you can be explicit if needed. ## GitHub Actions Integration The setup script creates a GitHub Actions workflow that runs ctrl.shift.left in your CI pipeline: ```yaml # .github/workflows/qa.yml name: Quality Assurance on: push: branches: [ main ] pull_request: branches: [ main ] jobs: quality-assurance: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: '18' cache: 'npm' - name: Install dependencies run: npm ci --legacy-peer-deps - name: Install ctrl.shift.left run: npm install -g ctrlshiftleft - name: Set up OpenAI API Key if: ${{ secrets.OPENAI_API_KEY != '' }} run: echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}" >> $GITHUB_ENV - name: Generate tests run: npx ctrlshiftleft gen ./app/components --output=__tests__/components - name: Run security analysis run: npx ctrlshiftleft-ai analyze ./app --output=security-reports ``` ## Need More Help? If you encounter any issues not covered here, please: 1. Run the diagnostic tool: `npx ctrlshiftleft-repair --scan` 2. Check our main troubleshooting guide: [TROUBLESHOOTING.md](../TROUBLESHOOTING.md) 3. Report issues on our GitHub: [github.com/johngaspar/ctrlshiftleft/issues](https://github.com/johngaspar/ctrlshiftleft/issues)