JSPM

  • Created
  • Published
  • Downloads 22
  • Score
    100M100P100Q73691F
  • License Apache-2.0

Prefl AI code review CLI that analyzes staged changes using Groq.

Package Exports

  • @preflight-ai/cli
  • @preflight-ai/cli/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@preflight-ai/cli) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Prefl AI - Your Dream Code Review Tool ✨

Professional AI-powered code review that catches bugs before they reach production

Website: prefl.run


🚀 Features

  • 🤖 AI-Powered Analysis - Deep semantic code review with Groq LLM (senior architect-level analysis)
  • 🐛 Production Bug Detection - Catches 16+ categories of bugs that pass code review & testing but crash in production
  • 🎭 E2E & UX Analysis - Detects forms without validation, missing error handling, broken navigation, poor user feedback
  • đŸŽ¯ Smart Context Tracking - Analyzes related code and imports to maintain full context
  • 🚨 Critical Issue Blocking - Prevents commits with critical problems
  • 🌍 Multi-Language Support - Works with any programming language (JavaScript, Python, Go, Java, C#, Ruby, PHP, Rust, etc.)
  • ⚡ Lightning Fast - AI analysis in 2-5 seconds
  • 🎨 Beautiful Output - Clear, categorized, emoji-rich reports with actionable fixes
  • 💾 Export Reports - Save detailed analysis to files
  • đŸĒ Git Integration - Auto-runs on pre-commit hooks
  • 🔧 Auto-Fix - AI-suggested patches for common issues
  • 🧮 Business Logic Validation - Checks all code paths, missing returns, edge cases
  • 🌍 Environment Validation - Detects missing environment variables and config issues
  • 🔌 API Integration Analysis - Validates API calls, external dependencies, deprecations
  • 💾 Resource Exhaustion Detection - Finds unbounded loops, memory issues, connection pooling problems
  • 🌐 Distributed System Analysis - Detects cross-service issues, transaction problems, cascading failures
  • 📝 Form Validation Check - Ensures proper input validation, required fields, error messages
  • 🧭 Navigation Analysis - Validates links, routes, 404 pages, auth-protected redirects

đŸ“Ļ Installation

npm i -g @preflight-ai/cli@latest

đŸ› ī¸ Setup

1. Initialize in your project

cd your-project
prefl init

This will:

  • ✅ Create prefl.json config file
  • ✅ Create .env and ask for your GROQ API key
  • ✅ Add .env to .gitignore
  • ✅ Install pre-commit hook automatically

2. Get your Groq API Key

  1. Visit console.groq.com
  2. Create a free account
  3. Generate an API key
  4. Paste it when prompted during prefl init

đŸŽ¯ Usage

Once initialized, Prefl automatically reviews your code before every commit:

git add .
git commit -m "feat: add new feature"
# ✨ Prefl analyzes your changes automatically!

Manual Analysis

# Analyze staged changes
prefl analyze

# Analyze entire repository
prefl analyze --all

# Save report to file
prefl analyze --output my-report.txt

# JSON output for CI/CD
prefl analyze --format json

Commands

prefl init                      # Setup Prefl in your project
prefl analyze                   # Analyze staged changes
prefl analyze --all             # Analyze entire repo
prefl analyze --output FILE     # Save results to file
prefl analyze --full            # Full project scan + detailed report
prefl fix                       # Generate AI-suggested patches
prefl fix --apply               # Auto-apply generated fixes
prefl install-hook              # Install pre-commit hook
prefl --version                 # Show version
prefl --help                    # Show help

📊 What Gets Analyzed?

Prefl's AI analyzes your code with 16 critical categories of production bugs that commonly pass code review and testing:

🚨 CRITICAL ISSUES (Blocks Commits)

  1. ⚡ Race Conditions & Async Bugs - Shared state without locking, read-modify-write without atomicity
  2. đŸŽ¯ Edge Cases & Boundary Conditions - Missing validation for null/empty/negative/NaN/Infinity
  3. 🔄 State Mutations & Side Effects - Unintended parameter mutations, missing immutability
  4. 🚰 Memory Leaks - Missing cleanup for intervals/listeners/subscriptions, closure leaks
  5. 🔌 Network & API Failures - Missing error handling, timeout, retries, unsafe JSON parsing
  6. 🔒 Authentication & Authorization - Unprotected endpoints, missing role/permission checks
  7. đŸ”ĸ Type Coercion & Conversions - String vs number comparisons, unsafe casting, missing validation
  8. 📅 Time & Date Bugs - Invalid dates, timezone issues, DST problems, date comparison failures
  9. 🧮 Business Logic Completeness - Functions with missing returns, uncovered branches, undefined results
  10. 🌍 Environment & Configuration - Missing env vars, unvalidated config, hardcoded values that should be dynamic
  11. 🔌 External Dependency Issues - Deprecated APIs, breaking changes, missing version checks, unsafe response assumptions
  12. 💾 Resource Exhaustion - Unbounded loops/recursion, loading entire datasets, no pagination/connection pooling
  13. 🌐 Distributed System Issues - Cross-service transactions, cascading failures, data consistency problems
  14. 🎭 User Experience & Runtime - Forms without validation, missing error handling, no loading states, blank screens on errors
  15. 📝 Form & Input Validation - Input fields without validation, required fields not enforced, unsafe user input
  16. 🧭 Navigation & Routing - Broken links, undefined routes, missing 404 pages, unprotected redirects
  • â™ŋ Accessibility - Missing alt text, ARIA labels, keyboard navigation
  • ⚡ Performance - N+1 queries, unnecessary re-renders, blocking main thread
  • đŸ›Ąī¸ Resilience - Missing error boundaries, fallback UI, poor error messages
  • 🌐 Browser Compatibility - Unsupported APIs in older browsers/platforms
  • 📊 Monitoring - Missing logging in critical paths

🎨 Example Output

🤖 Analyzing with AI (8 context files)...
✨ Analysis complete! Found 3 issue(s)

📊 Code Review Results

🚨 Critical: 3 | âš ī¸  Warnings: 0 | â„šī¸  Info: 0
────────────────────────────────────────────────────────

🚨 CRITICAL ISSUES (Must Fix)

1. ⚡
   File:     src/payment.ts:45
   Category: Race Condition
   Issue:    Race condition: shared state modified in async function without locking.
             Multiple concurrent requests will corrupt balance data, causing financial errors.
   Fix:      Use db.transaction() or mutex.lock() to ensure atomicity:
             await db.transaction(async (trx) => {
               const current = await trx.select('balance');
               await trx.update({ balance: current - amount });
             });

2. 🔒
   File:     src/api/user.ts:23
   Category: Security
   Issue:    Missing authentication middleware on /admin/users endpoint.
             Anyone can access admin-only data without authorization.
   Fix:      Add requireAuth and requireAdmin middleware before handler:
             app.get('/admin/users', requireAuth, requireAdmin, handler)

3. 🧮
   File:     src/utils.ts:89
   Category: Business Logic
   Issue:    Function returns undefined for non-premium users.
             Missing else branch causes caller code to break.
   Fix:      Add explicit return for all code paths:
             if (isPremium) return price * 0.9;
             return price; // Handle non-premium case

────────────────────────────────────────────────────────
🛑 Commit blocked due to critical issues. Please fix them first.

🎭 E2E & UX Analysis Examples

Prefl now analyzes user experience and runtime issues that cause poor UX:

Form Validation Issues

// ❌ BAD - Prefl detects:
function LoginForm() {
  const handleSubmit = async (e) => {
    await fetch('/api/login', {
      body: JSON.stringify({ email })
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} />
      <button>Login</button>
    </form>
  );
}

// Prefl reports:
🚨 CRITICAL: No error handling in handleSubmit
   Category: Ux Runtime
   Issue: Form submission has no error handling. Users will see blank screen if API fails.
   Fix: Add try-catch and show error message to user

🚨 CRITICAL: No loading state during API call
   Category: Form Validation
   Issue: Button stays clickable during API call. Users can submit multiple times.
   Fix: Add isLoading state and disable button: <button disabled={isLoading}>

🚨 CRITICAL: Form doesn't prevent default submission
   Category: Form Validation
   Issue: Form will cause page reload on submit, losing all state.
   Fix: Add e.preventDefault() at start of handleSubmit

📝 WARNING: No input validation
   Category: Form Validation
   Issue: Email input has no validation. Invalid emails will reach API.
   Fix: Add validation: if (!/\S+@\S+/.test(email)) { setError('Invalid email'); return; }
// ❌ BAD - Prefl detects:
<a href="">Settings</a>
<Link to="/admin">{user.name}</Link>

// Prefl reports:
🚨 CRITICAL: Empty href attribute
   Category: Navigation
   Issue: Link has empty href, will reload current page
   Fix: Provide valid href: <a href="/settings">Settings</a>

🚨 CRITICAL: No auth check before admin redirect
   Category: Navigation
   Issue: Link to /admin doesn't check if user has admin permissions
   Fix: Add permission check: {user.isAdmin && <Link to="/admin">}

API Call Issues

// ❌ BAD - Prefl detects:
const data = await fetch('/api/users').then(r => r.json());
return data.users.map(u => u.name);

// Prefl reports:
🚨 CRITICAL: No error handling for API call
   Category: Api Integration
   Issue: fetch() can fail (network error, timeout, 500). No try-catch.
   Fix: Wrap in try-catch and handle errors

🚨 CRITICAL: Unsafe property access
   Category: Edge Case
   Issue: data.users.map assumes data.users exists. Will crash if null/undefined.
   Fix: Add safety: return data?.users?.map(u => u?.name) || []

🎭 WARNING: No loading state for users
   Category: Ux Runtime
   Issue: No loading indicator while fetching. Poor UX.
   Fix: Add loading state: {isLoading ? <Spinner /> : <UserList />}

âš™ī¸ Configuration

Edit prefl.json in your project root:

{
  "ignore": {
    "globs": [
      "node_modules/**",
      "dist/**",
      ".git/**",
      "*.test.js",
      "coverage/**"
    ]
  },
  "review": {
    "blockSeverities": ["critical"],
    "context": {
      "baseLimit": 10,
      "importExpansionLimit": 20
    }
  }
}

Configuration Options

  • ignore.globs: Files/folders to skip (supports glob patterns)
  • review.blockSeverities: Which severity levels block commits (["critical"], ["critical", "warning"], or [])
  • review.context.baseLimit: How many files to include as context (default: 10)
  • review.context.importExpansionLimit: Max files to add via import tracking (default: 20)

🔧 Advanced Features

Generate and Apply Fixes

# Generate a patch file
prefl fix

# Validate the patch
prefl fix --dry-run

# Auto-apply the patch
prefl fix --apply

CI/CD Integration

# .github/workflows/code-review.yml
name: Prefl Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20 }
      - run: npm i -g @preflight-ai/cli
      - run: prefl analyze --format json
        env:
          GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}

🌟 Why Prefl?

Feature Prefl ESLint SonarQube
AI-Powered Analysis ✅ ❌ ❌
Production Bug Focus ✅ ❌ âš ī¸ Limited
Race Condition Detection ✅ ❌ ❌
Auto-Fix Suggestions ✅ âš ī¸ Limited ❌
Runtime Error Detection ✅ âš ī¸ Limited âš ī¸ Limited
Security Scanning ✅ âš ī¸ Plugins ✅
Memory Leak Detection ✅ ❌ âš ī¸ Limited
Multi-Language ✅ ❌ ✅
Context-Aware ✅ ❌ âš ī¸ Limited
Actionable Fixes ✅ âš ī¸ Sometimes âš ī¸ Sometimes
Beautiful Output ✅ ❌ âš ī¸ Web Only

Prefl uses AI to catch bugs that humans miss - issues that look correct in review, pass tests, but crash in production.


🤝 Contributing

We welcome contributions! Please see our Contributing Guide.


📄 License

Apache 2.0 - See LICENSE for details


đŸ’Ŧ Support


Made with â¤ī¸ by developers, for developers