CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-minify

Minifier of js, css, html and img files with CLI and programmatic interfaces

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

auto-detection.mddocs/

Auto-Detection Minification

Intelligent format detection and minification that automatically identifies content type and applies the appropriate minifier for maximum compatibility.

Capabilities

Auto-Detection Minifier Function

Automatically detects content format and applies the most suitable minifier using fallback chain processing.

/**
 * Automatically detects format and applies appropriate minifier
 * @param data - Source code content to minify (any supported format)
 * @param options - Configuration options for all minifier types
 * @returns Promise resolving to minified content or original data if no minifier succeeds
 */
function minify.auto(data: string, options?: MinifyOptions): Promise<string>;

interface MinifyOptions {
  js?: JSMinifyOptions;
  css?: CSSMinifyOptions;
  html?: HTMLMinifyOptions;
  img?: ImageOptions;
}

Usage Examples:

import { minify } from "minify";

// Auto-detect JavaScript
const jsCode = "function hello(world) { console.log(world); }";
const minifiedJS = await minify.auto(jsCode);
// Result: Minified JavaScript (detected and processed as JS)

// Auto-detect CSS
const cssCode = "body { color: red; margin: 0px; }";
const minifiedCSS = await minify.auto(cssCode, {
  css: { type: 'clean-css' }
});
// Result: Minified CSS (detected and processed as CSS)

// Auto-detect HTML
const htmlCode = "<html><body><h1>Hello</h1></body></html>";
const minifiedHTML = await minify.auto(htmlCode);
// Result: Minified HTML (detected and processed as HTML)

// Unknown format fallback
const unknownData = "This is plain text content";
const result = await minify.auto(unknownData);
// Result: Original data unchanged (no compatible minifier found)

Detection Algorithm

Fallback Chain Processing

The auto-detection uses a sequential fallback approach, trying minifiers in order:

const minifierChain = [
  'js',      // JavaScript minification (first attempt)
  'css',     // CSS minification (second attempt)
  'html',    // HTML minification (third attempt)
  'img'      // Image processing (final attempt)
];

interface DetectionProcess {
  inputData: string;                        // Original content
  currentMinifier: string;                  // Current minifier being tried
  lastError: Error | null;                  // Error from previous attempt
  result: string;                           // Final result (minified or original)
}

Detection Logic Flow

  1. JavaScript Detection: Attempts to parse and minify as JavaScript
  2. CSS Detection: If JS fails, tries CSS parsing and minification
  3. HTML Detection: If CSS fails, attempts HTML minification
  4. Image Processing: If HTML fails, tries image processing (requires file context)
  5. Fallback: If all fail, returns original data unchanged

Detection Examples:

// Clear JavaScript detection
const clearJS = `
  const greeting = "Hello World";
  function sayHello() {
    console.log(greeting);
  }
`;
const result1 = await minify.auto(clearJS);
// Detected as JavaScript, minified accordingly

// Ambiguous content (could be CSS or JS)
const ambiguous = "body { color: red }";
const result2 = await minify.auto(ambiguous);
// First tries JS (fails), then CSS (succeeds)

// Clear HTML detection
const clearHTML = "<!DOCTYPE html><html><head><title>Test</title></head></html>";
const result3 = await minify.auto(clearHTML);
// Detected as HTML after JS and CSS attempts fail

Error Handling and Tolerance

Graceful Failure Handling

Auto-detection is designed to be fault-tolerant and never throw errors:

interface ErrorTolerance {
  suppressErrors: boolean;                  // Always true - errors are caught
  returnOriginal: boolean;                  // Return original data on failure
  logErrors: boolean;                       // Errors are silently handled
}

const errorHandlingBehavior = {
  onMinifierError: 'try-next',              // Try next minifier in chain
  onAllMinifiersFail: 'return-original',    // Return input data unchanged
  onValidationError: 'skip-minifier',       // Skip to next in chain
};

Error Handling Examples:

// Malformed JavaScript
const malformedJS = "function unclosed() { console.log('test';";
const result1 = await minify.auto(malformedJS);
// JS minifier fails → tries CSS → tries HTML → returns original

// Binary data
const binaryData = Buffer.from([0x89, 0x50, 0x4E, 0x47]).toString();
const result2 = await minify.auto(binaryData);
// All minifiers fail gracefully → returns original data

// Empty input
const empty = "";
const result3 = await minify.auto(empty);
// Handled gracefully → returns empty string

Configuration Options

Multi-Format Configuration

Configure options for all possible minifiers since the format is unknown:

interface AutoDetectionOptions {
  js?: {
    type?: 'putout' | 'terser' | 'esbuild' | 'swc';
    putout?: PutoutOptions;
    terser?: TerserOptions;
    esbuild?: ESBuildOptions;
    swc?: SWCOptions;
  };
  css?: {
    type?: 'lightningcss' | 'clean-css';
    'clean-css'?: CleanCSSOptions;
  };
  html?: HTMLMinifierOptions;
  img?: {
    maxSize?: number;
  };
}

Configuration Examples:

// Comprehensive configuration for all formats
const fullConfig = {
  js: {
    type: 'terser',
    terser: {
      mangle: false,
      compress: { drop_console: true }
    }
  },
  css: {
    type: 'clean-css',
    'clean-css': { level: 2 }
  },
  html: {
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: false,  // Don't double-minify embedded JS
    minifyCSS: false  // Don't double-minify embedded CSS
  },
  img: {
    maxSize: 50000  // 50KB limit for image inlining
  }
};

const result = await minify.auto(unknownContent, fullConfig);

// Format-specific configuration
const jsOptimized = await minify.auto(possibleJS, {
  js: {
    type: 'esbuild',
    esbuild: { minifyIdentifiers: true }
  }
  // Other formats use defaults
});

Use Cases and Applications

Content Type Unknown Scenarios

Perfect for situations where input format cannot be predetermined:

// User-uploaded content
const userContent = getUserUploadedContent();
const optimized = await minify.auto(userContent);

// Dynamic template processing
const templateContent = processTemplate(templateData);
const minified = await minify.auto(templateContent, {
  html: { removeComments: false }  // Preserve template comments
});

// API response optimization
const apiResponse = await fetch('/api/assets/content').then(r => r.text());
const compressed = await minify.auto(apiResponse);

Batch Processing

Ideal for processing mixed content collections:

const mixedAssets = [
  "function test() { return true; }",           // JavaScript
  "body { margin: 0; padding: 10px; }",        // CSS
  "<div>Hello World</div>",                     // HTML fragment
  "/* Unknown comment style */"                 // Ambiguous
];

const processedAssets = await Promise.all(
  mixedAssets.map(asset => minify.auto(asset, {
    js: { type: 'esbuild' },
    css: { type: 'lightningcss' },
    html: { collapseWhitespace: true }
  }))
);

Development Tools Integration

Useful for build tools and development workflows:

// Build tool integration
async function optimizeAsset(filePath, content) {
  // Don't need to determine file type - let auto-detection handle it
  return await minify.auto(content, {
    js: { type: 'terser' },
    css: { type: 'clean-css' },
    html: { minifyJS: true, minifyCSS: true }
  });
}

// Editor plugin
async function minifySelection(selectedText, userPreferences) {
  return await minify.auto(selectedText, userPreferences);
}

Performance Characteristics

Detection Overhead

Auto-detection involves trying multiple minifiers:

interface PerformanceConsiderations {
  minifierAttempts: number;                 // 1-4 minifiers tried per input
  errorHandlingCost: number;                // Minimal - errors caught efficiently
  memoryUsage: number;                      // Low - no format pre-analysis
  cpuUsage: number;                         // Variable - depends on successful minifier
}

const performanceNotes = {
  bestCase: 'First minifier succeeds (JS detection)',
  worstCase: 'All minifiers fail, returns original',
  averageCase: '2-3 minifier attempts before success',
  recommendation: 'Use specific minifiers when format is known'
};

Optimization Strategies

// When format is known, use specific minifiers for better performance
const knownJS = await minify.js(jsContent);      // Direct - fastest
const unknownContent = await minify.auto(content); // Auto-detect - flexible

// Batch processing optimization
const results = await Promise.all([
  minify.auto(content1, sharedConfig),
  minify.auto(content2, sharedConfig),
  minify.auto(content3, sharedConfig)
]);

Limitations and Considerations

Detection Accuracy

Auto-detection has inherent limitations:

  • Format Ambiguity: Some content may be valid in multiple formats
  • Malformed Content: Broken syntax may not be detected correctly
  • Mixed Content: HTML with embedded JS/CSS is processed as HTML only
  • Comments Only: Files containing only comments may not be detected

Recommended Usage Patterns

// Good: Use for truly unknown content
const userUpload = await minify.auto(unknownUserContent);

// Better: Use specific minifiers when possible
const knownCSS = await minify.css(cssContent);

// Best: Combine both approaches
async function smartMinify(content, detectedType = null) {
  if (detectedType) {
    return await minify[detectedType](content);
  }
  return await minify.auto(content);
}

docs

auto-detection.md

cli-interface.md

configuration.md

css-minification.md

html-minification.md

image-processing.md

index.md

javascript-minification.md

tile.json