uiaudit.js
v1.0.5
Published
A CLI and VS Code extension to audit React/Next.js Components
Downloads
668
Maintainers
Readme
UIAudit.js 🔍
UIAudit.js is a lightweight, high-performance, AST-based static analysis engine and CLI tool designed to audit React and Next.js components for Accessibility (a11y), Performance, and SEO issues.
Unlike browser-driven auditing tools which require mounting components, running a browser instance, or rendering a full DOM, UIAudit parses component source files directly into an Abstract Syntax Tree (AST) using Babel. This allows it to identify issues instantly during development, in IDE plugins, or as a blocking gate in your CI/CD pipeline — without building or running your application.
Why UIAudit?
- ⚡ Zero-Runtime: No browser, webpack, or build step needed
- 🎯 60+ Accessibility Checks: Full WCAG 2.1 Level A/AA/AAA compliance coverage
- 📊 Performance & SEO Audits: Detect React anti-patterns and crawlability issues
- 🚀 Fast & Scalable: Analyze thousands of components in seconds
- 🔗 CI/CD Ready: Non-zero exit codes for critical issues, JSON reports for automation
- 📦 Published on npm: Easy installation and updates via
npm install
Table of Contents
- Key Features
- Architecture Overview
- Audit Categories & Rules
- Installation & Build
- CLI Usage Guide
- Programmatic API (SDK)
- Scoring Methodology
- Extending & Contributing
- License
Key Features
- ⚡ Zero-Runtime Static Analysis: Scans
.js,.jsx,.ts, and.tsxsource files directly using static AST traversal. No webpack build or browser instantiation required. - ♿ 50+ Accessibility Checks: Detailed checkers mapped to WCAG 2.1 guidelines (Level A/AA/AAA), catching keyboard traps, labeling failures, semantic errors, and more.
- 📈 Performance Audits: Identifies common React performance pitfalls like missing keys in lists, missing
useEffectdependency arrays, and complex inline callbacks. - 🔍 Search Optimization (SEO): Flags unlabelled anchors, non-semantic HTML structures, and raw images that bypass Next.js optimization.
- 🎨 Premium Terminal UI: Outputs beautifully formatted summary reports with color-coded scoreboards, file locations, issue impact (Critical, Major, Minor), failing code snippets, and drop-in code fixes.
- 🤖 CI/CD Ready: Returns exit code
1if any Critical issues are found, letting you block commits or pipeline builds immediately. - 📦 Programmatic SDK: Fully typed public exports for embedding in IDE extensions, pre-commit hooks, or build tools.
Architecture Overview
The codebase is structured modularly to keep parsing, auditing, and reporting concerns separated:
graph TD
CLI[src/cli.ts CLI] --> Auditor[src/auditor.ts runAudit]
SDK[src/index.ts Programmatic API] --> Auditor
Auditor --> Parser[src/parser/index.ts File Collector & Babel Parser]
Parser --> Traverse[src/parser/traverse.ts Babel Traverse Interop]
Auditor --> PerfAud[src/auditors/performance.ts]
Auditor --> SEOMAud[src/auditors/seo.ts]
Auditor --> A11yAud[src/auditors/accessibility.ts]
Auditor --> Reporter[src/reporter/terminal.ts Terminal Renderer]Core Components
- src/index.ts: Exposes the public programmatic SDK and TypeScript typings.
- src/types.ts: Defines data contracts for issues, category metrics, configuration options, and the final report.
- src/auditor.ts: Orchestrates the overall audit, coordinates files, initiates audits, calculates scores, and aggregates results.
- src/parser/:
index.ts: Collects all supported files recursively (excluding common build/node folders) and parses them to AST using Babel.traverse.ts: Solves CommonJS interop quirks for@babel/traverseto ensure compatibility across Node version runtimes.
- src/auditors/:
accessibility.ts: Implements 50+ WCAG 2.1 checks.performance.ts: Implements React-specific static performance validations.seo.ts: Evaluates crawlability, indexability, and structural semantics.
- src/reporter/terminal.ts: Generates chalk-rendered scorecards, issue descriptions, code snippets, and interactive suggestions.
Audit Categories & Rules
Coverage
UIAudit includes 60+ accessibility rules, 10+ performance checks, and 8+ SEO validations.
1. Accessibility (a11y)
Maps to WCAG 2.1 success criteria (Level A/AA):
- Keyboard Operability: Elements with click handlers (
onClick) must also support key inputs (onKeyDown, etc.) and be keyboard-focusable via a validtabIndex. - Accessible Naming: Elements like
<img>,<button>,<a>,<iframe/>, and interactive ARIA controls must possess descriptive names (via text children,aria-label,aria-labelledby, oralttags). - Form Association: Form inputs (
<input>,<select>,<textarea>) must be linked to a<label>(viahtmlFor/idmatching) or wrapped implicitly. - Media Alternatives: Checks if audio/video elements are missing captions (
tracktags). - Structure & Page Rules: Checks for page titles, skip-to-content links, responsive viewports, and valid heading structures.
2. Performance
Catches patterns that lead to memory leaks, redundant DOM mutations, or render cycles:
- Missing Key Props: Lists rendered via
.map()returning JSX elements without a stable, uniquekeyprop. - Unbound useEffects:
useEffecthooks called without a second argument (dependency array), causing them to execute on every single render. - Leftover Debug Logs:
console.log,console.info, orconsole.debugreferences that leak data to the browser console. - Complex Inline Callbacks: Identifying large, multi-statement inline closures in React event handlers (like
onClick={() => { doA(); doB(); }}) that invalidate child shallow-equality comparisons (React.memo).
3. SEO
Analyzes document structures to improve Google ranking and search bot crawling:
- Crawler Visibility: Ensuring elements like images have alt text and anchors have descriptive, readable inner text (avoiding generic "Click here" or "Read more").
- Next.js Image Optimizations: Recommends Next.js’s
<Image>components instead of standard<img>tags inside Next.js components to prevent Layout Shifts (CLS) and enable modern format conversion (WebP/AVIF). - Document Outline Semantics: Flags generic
<div>tags carrying identifiers or class names that strongly indicate they should be semantic components (e.g.,<div className="navigation">should be<nav>).
Installation & Build
Option 1: Install from npm (Recommended)
The easiest way to use UIAudit is to install it as a global or local npm package:
# Install globally (recommended for CLI usage)
npm install -g uiaudit.js
# Or install locally in your project
npm install --save-dev uiaudit.jsOnce installed globally, you can use the uiaudit command directly:
uiaudit audit ./src
uiaudit a11y ./src/components
uiaudit perf ./src
uiaudit seo ./srcFor local installation, prefix with npx:
npx uiaudit audit ./src
npx uiaudit a11y ./src/componentsOption 2: Clone & Build from Source
If you want to contribute or build from source:
Prerequisites
- Node.js (v16.0.0 or higher)
- npm (v7.0.0 or higher)
Setup
- Clone this repository to your local workspace:
git clone https://github.com/yourusername/uiaudit.git cd uiaudit - Install all dependencies:
npm install - Compile the TypeScript source files to JavaScript:
npm run build - Run the CLI:
npm start -- audit ./src # Or directly with node node dist/cli.js audit ./src
CLI Usage Guide
Basic Usage
The main command is audit, which scans a directory recursively:
# Scan entire src directory (global installation)
uiaudit audit ./src
# Scan a specific component directory (global installation)
uiaudit audit ./src/components
# With npx (local installation)
npx uiaudit audit ./srcCategory-Specific Audits
Run audits for individual categories using shorthand commands:
# Accessibility audit only
uiaudit a11y ./src
# Performance audit only
uiaudit perf ./src
# SEO audit only
uiaudit seo ./srcCLI Options & Flags
-t, --type <categories>
Specify which categories to audit (comma-separated). Defaults to all categories.
# Audit only accessibility and performance
uiaudit audit ./src --type accessibility,performance
# Audit only SEO
uiaudit audit ./src -t seo-o, --output <format>
Change the output format. Options: terminal (default) or json.
# Output as JSON to stdout
uiaudit audit ./src --output json
# Output in terminal format (colorful with formatting)
uiaudit audit ./src -o terminal-f, --file <filepath>
Save detailed JSON report to a file for further processing or archival.
# Save JSON report to file
uiaudit audit ./src -f ./reports/audit-report.json
# Combine with JSON output
uiaudit audit ./src --output json -f ./audit-results.jsonComplete CLI Examples
# Audit accessibility only with JSON output saved to file
uiaudit a11y ./src/components -f ./a11y-report.json
# Audit performance with detailed output
uiaudit perf ./src --output terminal
# Run all audits and save JSON report
uiaudit audit ./src -f ./full-audit.json
# Audit specific folder for accessibility
uiaudit audit ./src/pages --type accessibilityCI/CD Integration
UIAudit is designed to integrate seamlessly into your continuous integration pipeline. It returns a non-zero exit code (1) if any Critical issues are found, allowing you to fail builds or block commits.
npm scripts Integration
Add UIAudit to your package.json scripts:
{
"scripts": {
"audit": "uiaudit audit ./src",
"audit:a11y": "uiaudit a11y ./src",
"audit:perf": "uiaudit perf ./src",
"audit:seo": "uiaudit seo ./src",
"pretest": "uiaudit audit ./src --type accessibility",
"prebuild": "uiaudit audit ./src"
}
}GitHub Actions Example
name: UI Audit
on: [pull_request, push]
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm install
- name: Run UI Audit
run: npm run audit
- name: Save audit report
if: always()
run: npx uiaudit audit ./src --output json -f audit-report.json
- name: Upload report
if: always()
uses: actions/upload-artifact@v3
with:
name: audit-report
path: audit-report.jsonPre-commit Hook
Use with husky to audit before commits:
# Install husky
npm install husky --save-dev
npx husky install
# Create pre-commit hook
npx husky add .husky/pre-commit "npx uiaudit audit ./src --type accessibility"Exit Code Behavior
- Exit Code 0: No critical issues found
- Exit Code 1: One or more critical issues found (fails CI)
# Will exit with code 1 if critical issues exist
uiaudit audit ./src
# Check exit code
echo $? # 0 = success, 1 = critical issues foundProgrammatic API (SDK)
You can import and execute the engine programmatically in your build scripts, custom tooling, IDE plug-ins, or test suites. UIAudit is available as both an npm package and source code.
Installation for Programmatic Use
# Install as a dependency (not just dev dependency, since it runs at build time)
npm install uiaudit.js
# Or as a dev dependency for build/test automation
npm install --save-dev uiaudit.jsBasic Usage Example
import { runAudit } from 'uiaudit.js';
import type { AuditReport } from 'uiaudit.js';
const targetPath = './src/components';
const options = {
types: ['accessibility', 'performance', 'seo']
};
try {
const report: AuditReport = runAudit(targetPath, options);
console.log(`Overall Score: ${report.overallScore}/100`);
console.log(`Scanned ${report.totalFiles} components.`);
console.log(`Total Issues Found: ${report.totalIssues}`);
// Inspect category-specific results
const perfResult = report.results.performance;
if (perfResult) {
console.log(`Performance Score: ${perfResult.score}`);
console.log(`Issues: ${perfResult.issues.length}`);
}
// Iterate through all issues
for (const issue of report.issues) {
console.log(`[${issue.impact.toUpperCase()}] ${issue.title}`);
console.log(` File: ${issue.file}:${issue.line}`);
console.log(` Suggestion: ${issue.suggestion}`);
}
} catch (error) {
console.error("Audit failed:", error.message);
process.exit(1);
}API Reference
runAudit(targetPath: string, options?: AuditOptions): AuditReport
Main entry point for running an audit.
Parameters:
targetPath(string): Path to directory or file to audit (e.g.,'./src/components')options(AuditOptions, optional): Configuration objecttypes: Array of audit categories ('accessibility' | 'performance' | 'seo'). Default: all threeexclude: Array of glob patterns to exclude
Returns: AuditReport object containing:
overallScore: Numeric score (0-100)totalFiles: Number of files scannedtotalIssues: Total issue count across all categoriesresults: Object with category-specific resultsissues: Flat array of all issues found
Advanced Usage: Build Tool Integration
// In your build script or webpack plugin
import { runAudit } from 'uiaudit.js';
export async function lintComponentsBeforeBuild() {
const report = runAudit('./src/components', {
types: ['accessibility', 'performance']
});
const criticalIssues = report.issues.filter(i => i.impact === 'critical');
if (criticalIssues.length > 0) {
console.error(`Build failed: ${criticalIssues.length} critical accessibility issues found`);
process.exit(1);
}
console.log(`✓ All ${report.totalFiles} components passed audit`);
}
lintComponentsBeforeBuild();TypeScript Support
UIAudit is fully typed and ships with TypeScript definitions. All exported types are available:
import type {
AuditReport, // Overall audit result
AuditResult, // Category-specific results
AuditOptions, // Configuration options
AuditCategory, // 'accessibility' | 'performance' | 'seo'
Issue, // Individual issue details
IssueImpact, // 'critical' | 'major' | 'minor'
IssueStatus // 'fail' | 'warning'
} from 'uiaudit.js';
---
## Scoring Methodology
Audit scores start at **100** points. For each rule violation, points are deducted based on the impact tier of the issue:
| Issue Impact | Score Deduction | Description / Examples |
| :--- | :--- | :--- |
| **Critical** | `-20` points | Major accessibility barriers (e.g., keyboard traps, clickable element missing a button role). |
| **Major** | `-10` points | Moderate issues (e.g., missing list keys, raw `<img>` without `alt` in non-decorative contexts). |
| **Minor** | `-5` points | Best-practice recommendations (e.g., left-over console logs, complex inline closures). |
Scores are clamped between `0` and `100`. The **Overall Score** of the report is calculated as the average score of all active categories.
---
## Extending & Contributing
Adding a new rule to UIAudit involves extending the respective auditor files inside `src/auditors/`.
### Writing a New Rule
1. Open the auditor file matching your category (e.g., `src/auditors/performance.ts`).
2. Add or edit a visitor within the `traverse` call.
> [!IMPORTANT]
> Babel's AST traverser does not support duplicate visitor keys. If your check relies on an existing node visitor (e.g. `CallExpression` or `JSXOpeningElement`), add your logic to the **existing** visitor method rather than creating a duplicate key.
3. Push your new issue to the `issues` array. Follow the `Issue` schema:
```typescript
issues.push({
id: 'unique-rule-id',
category: 'performance',
title: 'Descriptive title of the issue',
description: 'Why this is an issue and how it impacts the application.',
impact: 'major', // 'critical' | 'major' | 'minor'
status: 'fail', // 'fail' | 'warning'
suggestion: 'Step-by-step instructions or example of how to fix this issue.',
codeSnippet: '<ProblematicComponent />',
fixSnippet: '<FixedComponent />',
file: filePath,
line: node.loc?.start.line,
});
```
4. Recompile using `npm run build` and run the CLI command on your test components to verify the output formatting and line number coordinates.
---
## Troubleshooting
### Common Issues
#### "command not found: uiaudit"
You haven't installed UIAudit globally. Either:
- Install globally: `npm install -g uiaudit.js`
- Or use with npx: `npx uiaudit audit ./src`
#### "Cannot find module 'uiaudit.js'"
Make sure you've installed the package:
```bash
npm install uiaudit.jsNo issues found when expected
Ensure the path is correct and contains React/Next.js component files:
# Check what files are being scanned
uiaudit audit ./src --output json | head -20Performance issues on large codebases
UIAudit is optimized for large codebases but very large monorepos may take time. Consider:
- Auditing specific directories instead:
uiaudit audit ./src/components - Running specific categories:
uiaudit a11y ./src - Excluding heavy directories in the code
Package Information
Package Name: uiaudit.js
Repository: GitHub
npm: uiaudit.js on npm
Author: Dheeraj P
License: MIT
Installation
# Global (CLI)
npm install -g uiaudit.js
# Local (for programmatic use or local CLI)
npm install uiaudit.js
# Dev dependency
npm install --save-dev uiaudit.jsUpdating
Keep UIAudit up-to-date to get the latest rules and fixes:
# Check for updates
npm outdated uiaudit.js
# Update globally
npm update -g uiaudit.js
# Update locally
npm update uiaudit.jsPerformance Benchmarks
UIAudit is designed to be fast:
- Startup time: < 100ms
- Per file: ~1-5ms depending on complexity
- Full project (500 components): ~10-30 seconds
- Memory usage: ~50-200MB depending on project size
Version History
v1.0.0 (Current)
- Initial release
- 60+ accessibility checks (WCAG 2.1 Level A/AA)
- 10+ performance audits
- 8+ SEO validations
- CLI with JSON and terminal output
- Programmatic API (SDK)
- CI/CD integration ready
FAQ
Q: Does UIAudit require building my application?
A: No. It performs static AST analysis without compilation or runtime execution.
Q: Can I use UIAudit with Vue or Svelte?
A: Currently, UIAudit is designed for React and Next.js. Vue and Svelte support may be added in future releases.
Q: How often are new rules added?
A: Regular updates are released to expand coverage and improve detection accuracy.
Q: Can I customize the scoring system?
A: The current version uses a fixed scoring methodology. Customization support may be added in future versions.
Q: Is UIAudit suitable for large monorepos?
A: Yes. You can audit specific directories or use npm scripts to audit different sections. Consider running audits in parallel across packages.
Q: What Node.js versions are supported?
A: Node.js 16.0.0 and higher.
License
This project is licensed under the MIT License - see the LICENSE file for details.
