npm package: @ordojs/performance
Description: Performance optimization tools for OrdoJS applications
Author: OrdoJS Team
Latest version: 0.1.0

# @ordojs/performance

Performance optimization tools for OrdoJS applications. This package provides comprehensive tools
for analyzing, monitoring, and optimizing application performance.

## Features

- **Bundle Analysis**: Analyze bundle sizes, dependencies, and identify optimization opportunities
- **Code Splitting**: Automatic code splitting based on routes, components, and vendor dependencies
- **Caching Strategies**: Intelligent resource caching with service worker support
- **Performance Monitoring**: Real-time Core Web Vitals monitoring and reporting
- **Optimization Recommendations**: Automated performance optimization suggestions

## Installation

```bash
pnpm add @ordojs/performance
```

## Usage

### Bundle Analysis

```typescript
import { BundleAnalyzer } from '@ordojs/performance';

const analyzer = new BundleAnalyzer();

// Analyze a webpack bundle
const analysis = await analyzer.analyzeBundle('./dist/bundle.js');

// Generate a report
const report = analyzer.generateReport();
console.log(report);

// Get optimization recommendations
const optimizations = analyzer.identifyOptimizations();
console.log(optimizations);
```

### Code Splitting

```typescript
import { CodeSplitter } from '@ordojs/performance';

const splitter = new CodeSplitter({
  routes: true,
  components: true,
  vendors: true,
  maxChunkSize: 500 * 1024, // 500KB
  minChunkSize: 10 * 1024, // 10KB
});

// Analyze application structure
const strategy = await splitter.analyzeCodeSplitting(appStructure);

// Generate webpack configuration
const webpackConfig = splitter.generateWebpackConfig(strategy);
```

### Caching

```typescript
import { CacheManager } from '@ordojs/performance';

const cacheManager = new CacheManager({
  strategy: 'balanced',
  maxAge: 3600, // 1 hour
  staleWhileRevalidate: 300, // 5 minutes
});

// Generate cache headers for resources
const headers = cacheManager.generateCacheHeaders('/static/app.js', 'script');

// Generate service worker strategy
const swStrategy = cacheManager.generateServiceWorkerStrategy();

// Generate resource hints
const hints = cacheManager.generateResourceHints(
  ['/critical.js', '/critical.css'],
  ['/non-critical.js', '/non-critical.css']
);
```

### Performance Monitoring

```typescript
import { PerformanceMonitor } from '@ordojs/performance';

const monitor = new PerformanceMonitor({
  enabled: true,
  sampleRate: 1.0,
  reportUrl: 'https://api.example.com/metrics',
});

// Start monitoring Core Web Vitals
monitor.startMonitoring();

// Get current metrics
const metrics = monitor.getMetrics();

// Generate performance report
const budget = {
  maxBundleSize: 1024 * 1024,
  maxFirstContentfulPaint: 1800,
  maxLargestContentfulPaint: 2500,
  maxFirstInputDelay: 100,
  maxCumulativeLayoutShift: 0.1,
};

const report = monitor.generateReport(budget);
console.log(report.violations);
console.log(report.recommendations);
```

### Performance Optimization

```typescript
import { PerformanceOptimizer } from '@ordojs/performance';

const optimizer = new PerformanceOptimizer();

// Analyze and optimize bundle
const result = await optimizer.optimizeBundle(bundleAnalysis);

// Generate optimization report
const report = optimizer.generateOptimizationReport(result);
console.log(report);

// Access improvements
result.improvements.forEach(improvement => {
  console.log(`${improvement.type}: ${improvement.description}`);
  console.log(`Impact: ${improvement.impact}, Savings: ${improvement.estimatedSavings}`);
});
```

## API Reference

### BundleAnalyzer

#### `analyzeBundle(bundlePath: string): Promise<BundleAnalysis>`

Analyzes a webpack bundle and returns detailed analysis.

#### `generateReport(): string`

Generates a human-readable report of the bundle analysis.

#### `identifyOptimizations(): string[]`

Returns a list of optimization recommendations.

### CodeSplitter

#### `analyzeCodeSplitting(appStructure: AppStructure): Promise<CodeSplittingStrategy>`

Analyzes application structure and generates code splitting strategy.

#### `generateWebpackConfig(strategy: CodeSplittingStrategy): WebpackCodeSplittingConfig`

Generates webpack configuration for code splitting.

### CacheManager

#### `generateCacheHeaders(resourcePath: string, resourceType: string): CacheHeaders`

Generates appropriate cache headers for a resource.

#### `generateServiceWorkerStrategy(): ServiceWorkerStrategy`

Generates service worker caching strategy.

#### `generateResourceHints(criticalResources: string[], nonCriticalResources: string[]): ResourceHints`

Generates resource hints for preloading and prefetching.

### PerformanceMonitor

#### `startMonitoring(): void`

Starts monitoring Core Web Vitals and other performance metrics.

#### `stopMonitoring(): void`

Stops all performance monitoring.

#### `getMetrics(): PerformanceMetrics | null`

Returns current performance metrics.

#### `generateReport(budget: PerformanceBudget): PerformanceReport`

Generates a performance report against a budget.

### PerformanceOptimizer

#### `optimizeBundle(bundleAnalysis: BundleAnalysis): Promise<OptimizationResult>`

Analyzes bundle and provides optimization recommendations.

#### `generateOptimizationReport(result: OptimizationResult): string`

Generates a detailed optimization report.

## Configuration

### Code Splitting Configuration

```typescript
interface CodeSplittingConfig {
  routes: boolean; // Enable route-based splitting
  components: boolean; // Enable component-based splitting
  vendors: boolean; // Enable vendor splitting
  dynamic: boolean; // Enable dynamic import splitting
  maxChunkSize: number; // Maximum chunk size in bytes
  minChunkSize: number; // Minimum chunk size in bytes
}
```

### Caching Configuration

```typescript
interface CachingConfig {
  strategy: 'aggressive' | 'balanced' | 'conservative';
  maxAge: number; // Cache max age in seconds
  staleWhileRevalidate: number; // Stale-while-revalidate time
  cacheableResources: string[]; // Patterns for cacheable resources
  excludePatterns: string[]; // Patterns to exclude from caching
}
```

### Monitoring Configuration

```typescript
interface MonitoringConfig {
  enabled: boolean; // Enable/disable monitoring
  sampleRate: number; // Sampling rate (0.0 to 1.0)
  reportUrl?: string; // URL to report metrics to
  customMetrics?: Record<string, (performance: Performance) => number>;
}
```

## Performance Budget

```typescript
interface PerformanceBudget {
  maxBundleSize: number; // Maximum bundle size in bytes
  maxFirstContentfulPaint: number; // Maximum FCP in milliseconds
  maxLargestContentfulPaint: number; // Maximum LCP in milliseconds
  maxFirstInputDelay: number; // Maximum FID in milliseconds
  maxCumulativeLayoutShift: number; // Maximum CLS score
}
```

## Examples

### Complete Performance Optimization Workflow

```typescript
import {
  BundleAnalyzer,
  CodeSplitter,
  CacheManager,
  PerformanceMonitor,
  PerformanceOptimizer,
} from '@ordojs/performance';

async function optimizeApplication() {
  // 1. Analyze bundle
  const analyzer = new BundleAnalyzer();
  const analysis = await analyzer.analyzeBundle('./dist/bundle.js');

  // 2. Optimize bundle
  const optimizer = new PerformanceOptimizer();
  const optimizationResult = await optimizer.optimizeBundle(analysis);

  // 3. Generate code splitting strategy
  const splitter = new CodeSplitter();
  const strategy = await splitter.analyzeCodeSplitting(appStructure);

  // 4. Set up caching
  const cacheManager = new CacheManager();
  const swStrategy = cacheManager.generateServiceWorkerStrategy();

  // 5. Start monitoring
  const monitor = new PerformanceMonitor();
  monitor.startMonitoring();

  // 6. Generate reports
  const bundleReport = analyzer.generateReport();
  const optimizationReport = optimizer.generateOptimizationReport(optimizationResult);

  console.log('Bundle Analysis:', bundleReport);
  console.log('Optimization Report:', optimizationReport);
  console.log('Code Splitting Strategy:', strategy);
  console.log('Service Worker Strategy:', swStrategy);
}

optimizeApplication();
```

## Contributing

This package is part of the OrdoJS ecosystem. Please refer to the main OrdoJS repository for
contribution guidelines.

## License

MIT