npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

code-explainer

v2.1.2

Published

AI-Powered React Code Analyzer - Multi-level CLI tool for React components with security, quality, and maintainability insights

Readme

code-explainer

AI-Powered React Code Analyzer - Multi-level CLI tool for analyzing React components with security, quality, and maintainability insights.

npm version npm downloads license node typescript

Installation | Quick Start | Features | CLI Options | Configuration | API


Overview

code-explainer is a CLI tool that performs deep static analysis on React/TypeScript components. It combines AST-based code analysis with AI-powered explanations (via NVIDIA endpoints) to deliver actionable insights across three levels of depth.

What It Analyzes

| Category | Checks Performed | |:---------|:-----------------| | Security | Hardcoded secrets, unsafe API usage (eval, Function), XSS vulnerabilities, missing input validation, authentication gaps | | Code Quality | Unused imports, dead code, large functions, duplicate logic, formatting consistency | | Maintainability | Cyclomatic complexity, nesting depth, function length, state/effect counts, modularity | | Architecture | React patterns (Context, Refs, Suspense), hook usage, API call patterns, memoization adoption |


Installation

# Global install (recommended)
npm install -g code-explainer

# Or use npx directly
npx code-explainer <file.tsx>

# As a project dependency
npm install code-explainer

Requirements: Node.js >= 18.0.0


Quick Start

# Analyze a single component (default: senior level, terminal output)
code-explainer src/App.tsx

# Get architect-level audit
code-explainer src/App.tsx -e architect

# Save JSON report
code-explainer src/App.tsx -o json -s report.json

# Analyze all components in a directory
code-explainer src/components/

# Watch for changes
code-explainer src/ --watch

Sample Terminal Output

┌─────────────────────────────────────────────┐
│  Security    ████████░░  8/10  ✅ Good
│  Code Quality ██████░░░░  6/10  ⚠️  Needs Attention
│  Maintainability ███████░░░  7/10  ✅ Good
│  Risk Exposure    ██░░░░░░░░  2/10  ✅ Good
└─────────────────────────────────────────────┘

┌─────────────────────────────────────────────┐
│ SECURITY RISK ANALYSIS
│ 🔒 Secret scanning: ✅ Clean (0 issues)
│ 🛡️  XSS risk: ✅ Safe (0 instances)
│ 🌐 Unsafe API usage: ✅ None (0 calls)
│ ✅ Validation coverage: ✅ Complete (0 gaps)
│ 🔑 Auth review: ✅ Covered (0 checks)
└─────────────────────────────────────────────┘

┌─────────────────────────────────────────────┐
│ FINAL VERDICT
│ Overall Health: 🟡 Good with minor issues
│ Risk Category: Low-Medium
│ Immediate Actions: Review recommendations below
└─────────────────────────────────────────────┘

Features

AI-Powered Explanations

Three explanation levels powered by NVIDIA AI (Llama 3.1 70B):

| Level | Target Audience | Output Style | |:------|:---------------|:-------------| | junior | Beginners learning React | Tutorial format with analogies, step-by-step fixes, score | | senior | Experienced developers | Code health dashboard with metrics, severity counts | | architect | Tech leads / architects | System architecture audit with strategic recommendations |

code-explainer src/App.tsx -e junior    # Learning mode
code-explainer src/App.tsx -e senior    # Professional analysis (default)
code-explainer src/App.tsx -e architect # Strategic audit

Multiple Output Formats

| Format | Flag | Description | |:-------|:-----|:------------| | Terminal | -o terminal | Rich dashboard with KPI cards and panels (default) | | JSON | -o json | Structured data for programmatic consumption | | Markdown | -o markdown | Formatted report with tables and badges | | HTML | -o html | Self-contained interactive dashboard |

Watch Mode

Automatically re-analyze files when they change:

code-explainer src/ --watch

Caching

AI responses are cached locally to reduce API costs:

code-explainer src/App.tsx              # Uses cache (default)
code-explainer src/App.tsx --no-cache   # Skip cache
code-explainer --clear-cache            # Clear all cached responses

Glob Pattern Support

code-explainer "src/**/*.tsx"           # All TSX files
code-explainer "src/**/*.{ts,tsx}"      # All TS and TSX files
code-explainer src/components/          # All files in directory

CLI Options

| Flag | Short | Description | Default | |:-----|:------|:------------|:--------| | --explain <level> | -e | Explanation depth: junior, senior, architect | senior | | --output <format> | -o | Output format: terminal, json, markdown, html | terminal | | --save <filename> | -s | Save output to a file | (stdout) | | --watch | -w | Watch for file changes and re-analyze | false | | --no-cache | | Bypass AI response cache | false | | --clear-cache | | Clear the entire AI response cache | false | | --config <path> | -c | Path to config file | auto-discovered | | --no-color | | Disable colored terminal output | false | | --verbose | -v | Show detailed processing logs | false |

Shorthand Levels

| Short | Full | |:------|:-----| | j | junior | | s | senior | | ar | architect |


Configuration

Config File Discovery

The tool searches for configuration in this order:

  1. --config <path> (explicit)
  2. .code-explainerrc.json (CWD)
  3. .code-explainerrc (CWD)
  4. code-explainer.config.json (CWD)
  5. Built-in defaults

Config Schema

{
  "defaultLevel": "senior",
  "defaultOutput": "terminal",
  "apiKey": "nvapi-your-api-key-here",
  "baseUrl": "https://integrate.api.nvidia.com/v1",
  "model": "meta/llama-3.1-70b-instruct",
  "cacheEnabled": true,
  "cacheTTL": 24,
  "supportedExtensions": [".tsx", ".ts", ".jsx", ".js"],
  "ignorePatterns": ["node_modules", "dist", "build", ".next", ".git"]
}

Field Reference

| Field | Type | Default | Description | |:------|:-----|:--------|:------------| | defaultLevel | string | "senior" | Default explanation depth | | defaultOutput | string | "terminal" | Default output format | | apiKey | string? | (env) | NVIDIA API key for AI features | | baseUrl | string | https://integrate.api.nvidia.com/v1 | NVIDIA API endpoint | | model | string | meta/llama-3.1-70b-instruct | AI model identifier | | cacheEnabled | boolean | true | Enable/disable caching | | cacheTTL | number | 24 | Cache TTL in hours | | supportedExtensions | string[] | [".tsx", ".ts", ".jsx", ".js"] | File extensions to analyze | | ignorePatterns | string[] | ["node_modules", "dist", ...] | Directories to ignore |

NVIDIA API Key Setup

Option 1: Environment Variable (Recommended)

export NVIDIA_API_KEY="nvapi-your-api-key-here"

Option 2: Config File

{
  "apiKey": "nvapi-your-api-key-here"
}

Get your API key from NVIDIA AI Foundation Endpoints.


API Reference

Programmatic Usage

import { analyzeFile, formatTerminal, formatJSON, formatMarkdown, formatHTML } from "code-explainer";
import { loadConfig } from "code-explainer";

const config = loadConfig();
const summary = await analyzeFile("src/App.tsx", "senior", config);

console.log(formatTerminal(summary, "senior"));
console.log(formatJSON(summary));

Functions

analyzeFile(filePath, level, config, verbose?)

Analyzes a React component file and returns a detailed ComponentSummary.

async function analyzeFile(
  filePath: string,
  level: ExplanationLevel,
  config: CodeExplainerConfig,
  verbose?: boolean
): Promise<ComponentSummary>

formatTerminal(summary, level)

Formats analysis results for terminal dashboard display.

function formatTerminal(summary: ComponentSummary, level: ExplanationLevel): string

formatJSON(summary)

Generates structured JSON output.

function formatJSON(summary: ComponentSummary): string

formatMarkdown(summary)

Creates a markdown-formatted report.

function formatMarkdown(summary: ComponentSummary): string

formatHTML(summary)

Generates a self-contained interactive HTML dashboard.

function formatHTML(summary: ComponentSummary): string

loadConfig(configPath?)

Loads configuration with auto-discovery and defaults merging.

function loadConfig(configPath?: string): CodeExplainerConfig

Cache Functions

function getCached(code: string, level: string, ttlHours?: number): string | null
function setCache(code: string, level: string, result: string): void
function clearCache(): void

TypeScript Types

All types are fully exported:

import type {
  ExplanationLevel,      // "junior" | "senior" | "architect"
  OutputFormat,          // "terminal" | "json" | "markdown" | "html"
  CLIOptions,            // CLI flag options interface
  ComponentSummary,      // Main analysis result type
  SecurityFinding,       // Security issue with severity, location, recommendation
  CodeQualityIssue,      // Code quality issue
  MaintainabilityIssue,  // Maintainability issue
  ComplexityMetrics,     // Cyclomatic complexity, nesting depth, counts
  ComponentMetadata,     // Props, interfaces, imports
  EffectSummary,         // Hook effect details
  OptimizationSummary,   // Hook optimization details
  PropInfo,              // Property name and type
  InterfaceInfo,         // Interface name and members
  CodeExplainerConfig,   // Full configuration schema
} from "code-explainer";

Project Structure

code-explainer/
├── src/
│   ├── analyzer.ts       # AST analysis engine (ts-morph)
│   ├── cache.ts          # SHA-256-based response caching
│   ├── cli.ts            # CLI entry point (commander)
│   ├── config.ts         # Config file discovery & loading
│   ├── explainer.ts      # NVIDIA AI integration (openai SDK)
│   ├── formatters.ts     # Terminal, JSON, Markdown, HTML formatters
│   ├── types.ts          # Full TypeScript type definitions
│   └── __tests__/
│       ├── analyzer.test.ts  # Analyzer unit tests
│       └── cache.test.ts     # Cache unit tests
├── bin/
│   ├── ce                # CLI alias
│   └── code-explainer    # Main CLI entry
├── dist/                 # Built output (CJS, ESM, DTS)
├── package.json
├── tsconfig.json
├── README.md
└── CHANGELOG.md

Testing

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Type-check without emitting
npm run lint

Building

# Build for production
npm run build

# Output:
#   dist/cli.js      (CommonJS)
#   dist/cli.mjs     (ES Module)
#   dist/cli.d.ts    (TypeScript declarations)

Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repository
  2. Clone your fork:
    git clone https://github.com/<your-username>/Code-Analyzer-Tool.git
  3. Install dependencies:
    npm install
  4. Create a feature branch:
    git checkout -b feature/my-feature
  5. Make your changes and add tests
  6. Run tests:
    npm test
  7. Commit and push:
    git commit -m "feat: add my feature"
    git push origin feature/my-feature
  8. Open a Pull Request

Development Commands

| Command | Description | |:--------|:------------| | npm run dev | Run CLI in development mode | | npm run build | Build for production | | npm test | Run tests | | npm run test:watch | Run tests in watch mode | | npm run lint | Type-check the codebase |


Changelog

See CHANGELOG.md for a detailed history of all changes.


License

MIT © Rasul Ahmed Khan


Built with ❤️ for the React community

Report Bug | Request Feature