Setup & Installation

Quick and easy setup guide for fast-brake ES feature detection

Quick Start

Get up and running with fast-brake in under 2 minutes:

1. Installation

npm install fast-brake
# or
yarn add fast-brake
# or
bun add fast-brake

2. Basic Usage

import { fastBrakeSync, fastBrake, check } from 'fast-brake';

// FASTEST: Sync API - no async overhead
const fb = fastBrakeSync();
const isES5Compatible = fb.check('const x = () => {}', { target: 'es5' });
console.log(isES5Compatible); // false - instant result!

// Async API when needed
const asyncIsCompatible = await check('const x = () => {}', { target: 'es5' });
const features = await fastBrake('const x = () => {}');
console.log(features);
// [{ name: 'arrow_functions', version: 'es2015' }]

3. That’s it!

fast-brake works out of the box with zero configuration. No setup files, no complex configuration - just install and use.

Installation Options

Package Managers

npm:

npm install fast-brake
npm install --save-dev fast-brake  # For build tools

Yarn:

yarn add fast-brake
yarn add --dev fast-brake  # For build tools

pnpm:

pnpm add fast-brake
pnpm add -D fast-brake  # For build tools

Bun:

bun add fast-brake
bun add --dev fast-brake  # For build tools

CDN Usage (Browser)

<!-- ES Modules -->
<script type="module">
  import { detect } from 'https://esm.sh/fast-brake';
  
  const features = await detect('const x = () => {}');
  console.log(features);
</script>

<!-- UMD (Global) -->
<script src="https://unpkg.com/fast-brake/dist/index.umd.js"></script>
<script>
  (async () => {
    const features = await FastBrake.detect('const x = () => {}');
    console.log(features);
  })();
</script>

Environment Setup

Node.js Requirements

  • Node.js: 14.0.0 or higher
  • TypeScript: 4.0.0 or higher (optional)

Browser Support

fast-brake works in all modern browsers:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Integration Examples

Build Tools

Webpack Integration (Sync - FASTEST)

// webpack.config.js
const { fastBrakeSync } = require('fast-brake');
const fb = fastBrakeSync();

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                ['@babel/preset-env', {
                  targets: 'es5'
                }]
              ]
            }
          },
          {
            loader: 'fast-brake-loader',
            options: {
              target: 'es5',
              mode: 'full'
            }
          }
        ]
      }
    ]
  }
};

// Custom loader (webpack-loader/fast-brake-loader.js)
const { fastBrakeSync } = require('fast-brake');
const fb = fastBrakeSync();

module.exports = function(source) {
  const options = this.getOptions();
  const target = options.target || 'es5';
  
  // Sync check - no async overhead
  const isCompatible = fb.check(source, { target });
  
  if (!isCompatible) {
    const features = fb.detect(source);
    
    this.emitWarning(new Error(
      `File contains incompatible ES features: ${
        features.map(f => f.name).join(', ')
      }`
    ));
  }
  
  return source;
};

Vite Integration

// vite.config.js
import { defineConfig } from 'vite';
import { detect } from 'fast-brake';

export default defineConfig({
  plugins: [
    {
      name: 'fast-brake',
      async transform(code, id) {
        if (id.endsWith('.js') || id.endsWith('.ts')) {
          const features = await detect(code, { target: 'es2018' });
          const incompatible = features.filter(f => 
            getVersionIndex(f.version) > getVersionIndex('es2018')
          );
          
          if (incompatible.length > 0) {
            console.warn(`${id} contains modern ES features:`, 
              incompatible.map(f => f.name));
          }
        }
        return null; // Don't transform, just analyze
      }
    }
  ]
});

Rollup Integration

// rollup.config.js
import { detect } from 'fast-brake';

function fastBrakePlugin(options = {}) {
  return {
    name: 'fast-brake',
    async transform(code, id) {
      const target = options.target || 'es5';
      const features = await detect(code, { target });
      
      const incompatible = features.filter(f => 
        getVersionIndex(f.version) > getVersionIndex(target)
      );
      
      if (incompatible.length > 0) {
        this.warn(`${id}: Incompatible features - ${
          incompatible.map(f => f.name).join(', ')
        }`);
      }
    }
  };
}

export default {
  plugins: [
    fastBrakePlugin({ target: 'es2018' })
  ]
};

Linting Integration

ESLint Plugin

// .eslintrc.js
module.exports = {
  plugins: ['fast-brake'],
  rules: {
    'fast-brake/es-version': ['error', { target: 'es2018' }]
  }
};

// eslint-plugin-fast-brake/index.js
const { detect } = require('fast-brake');

module.exports = {
  rules: {
    'es-version': {
      create(context) {
        const target = context.options[0]?.target || 'es5';
        
        return {
          Program(node) {
            const sourceCode = context.getSourceCode();
            const text = sourceCode.getText();
            
            const features = detect(text, { target });
            const incompatible = features.filter(f => 
              getVersionIndex(f.version) > getVersionIndex(target)
            );
            
            incompatible.forEach(feature => {
              context.report({
                node,
                message: `ES feature "${feature.name}" requires ${feature.version} but target is ${target}`,
                loc: {
                  line: feature.line,
                  column: feature.column
                }
              });
            });
          }
        };
      }
    }
  }
};

CI/CD Integration

GitHub Actions

# .github/workflows/es-compatibility.yml
name: ES Compatibility Check

on: [push, pull_request]

jobs:
  compatibility:
    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 ci
        
      - name: Check ES compatibility
        run: |
          node -e "
            const { fastBrake } = require('fast-brake');
            const fs = require('fs');
            const path = require('path');
            
            const srcDir = 'src';
            const target = process.env.ES_TARGET || 'es2018';
            let hasErrors = false;
            
            function checkDirectory(dir) {
              const files = fs.readdirSync(dir, { withFileTypes: true });
              
              for (const file of files) {
                const filePath = path.join(dir, file.name);
                
                if (file.isDirectory()) {
                  checkDirectory(filePath);
                } else if (file.name.endsWith('.js') || file.name.endsWith('.ts')) {
                  try {
                    const code = fs.readFileSync(filePath, 'utf-8');
                    const isCompatible = await check(code, { target });
                    if (isCompatible) {
                      console.log('✓', filePath);
                    } else {
                      console.error('❌', filePath + ': Not compatible with', target);
                      hasErrors = true;
                    }
                  } catch (error) {
                    console.error('❌', filePath + ':', error.message);
                    hasErrors = true;
                  }
                }
              }
            }
            
            checkDirectory(srcDir);
            
            if (hasErrors) {
              console.error('\n❌ ES compatibility check failed');
              process.exit(1);
            } else {
              console.log('\n All files are compatible with', target);
            }
          "
        env:
          ES_TARGET: es2018

Jenkins Pipeline

// Jenkinsfile
pipeline {
    agent any
    
    stages {
        stage('Install') {
            steps {
                sh 'npm ci'
            }
        }
        
        stage('ES Compatibility') {
            steps {
                script {
                    def result = sh(
                        script: '''
                            node -e "
                                const { check } = require('fast-brake');
                                const fs = require('fs');
                                const glob = require('glob');
                                
                                const files = glob.sync('src/**/*.{js,ts}');
                                let compatible = true;
                                
                                (async () => {
                                    for (const file of files) {
                                        const code = fs.readFileSync(file, 'utf-8');
                                        const isCompatible = await check(code, { target: 'es2018' });
                                        if (!isCompatible) {
                                            console.error('Incompatible:', file);
                                            compatible = false;
                                        }
                                    }
                                    process.exit(compatible ? 0 : 1);
                                })();
                            "
                        ''',
                        returnStatus: true
                    )
                    
                    if (result != 0) {
                        error('ES compatibility check failed')
                    }
                }
            }
        }
    }
}

Testing Integration

Jest Setup

// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
};

// jest.setup.js
const { detect } = require('fast-brake');

// Custom Jest matcher
expect.extend({
  async toBeESCompatible(code, target = 'es5') {
    const features = await detect(code, { target });
    const incompatible = features.filter(f => 
      getVersionIndex(f.version) > getVersionIndex(target)
    );
    
    const pass = incompatible.length === 0;
    
    return {
      pass,
      message: () => pass
        ? `Expected code to NOT be ${target} compatible`
        : `Expected code to be ${target} compatible, but found: ${
            incompatible.map(f => f.name).join(', ')
          }`
    };
  }
});

// Usage in tests
test('generated code should be ES5 compatible', () => {
  const generatedCode = transpileToES5(sourceCode);
  expect(generatedCode).toBeESCompatible('es5');
});

Vitest Setup

// vitest.config.js
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    setupFiles: ['./vitest.setup.js']
  }
});

// vitest.setup.js
import { expect } from 'vitest';
import { check } from 'fast-brake';

expect.extend({
  async toBeESCompatible(code, target) {
    const isCompatible = await check(code, { target });
    
    return {
      pass: isCompatible,
      message: () => isCompatible
        ? `Expected code to NOT be ${target} compatible`
        : `Expected code to be ${target} compatible`
    };
  }
});

Configuration

TypeScript Configuration

// types/fast-brake.d.ts (if needed)
declare module 'fast-brake' {
  export interface DetectedFeature {
    name: string;
    version: string;
  }
  
  export interface DetectionOptions {
    target: string;
    quick?: boolean;
    throwOnFirst?: boolean;
  }
  
  export function fastBrake(code: string): Promise<DetectedFeature[]>;
  export function detect(code: string): Promise<DetectedFeature[]>;
  export function check(code: string, options: DetectionOptions): Promise<boolean>;
}

Package.json Scripts

{
  "scripts": {
    "check-es5": "node scripts/check-compatibility.js es5",
    "check-es2018": "node scripts/check-compatibility.js es2018",
    "analyze-features": "node scripts/analyze-features.js",
    "prebuild": "npm run check-es2018"
  }
}
// scripts/check-compatibility.js
const { fastBrake } = require('fast-brake');
const fs = require('fs');
const glob = require('glob');

const target = process.argv[2] || 'es5';
const files = glob.sync('src/**/*.{js,ts}');

let hasErrors = false;

console.log(` Checking ${files.length} files for ${target} compatibility...`);

for (const file of files) {
  try {
    const code = fs.readFileSync(file, 'utf-8');
    const isCompatible = await check(code, { target });
    if (isCompatible) {
      console.log(`✓ ${file}`);
    } else {
      console.error(`❌ ${file}: Not compatible with ${target}`);
      hasErrors = true;
    }
  } catch (error) {
    console.error(`❌ ${file}: ${error.message}`);
    hasErrors = true;
  }
}

if (hasErrors) {
  console.error(`\n❌ Compatibility check failed for ${target}`);
  process.exit(1);
} else {
  console.log(`\n All files are ${target} compatible`);
}

Development Setup

Local Development

# Clone and setup for contributing
git clone https://github.com/yowainwright/fast-brake.git
cd fast-brake

# Install dependencies
npm install

# Run tests
npm test

# Run benchmarks
npm run benchmark

# Build
npm run build

Testing Your Integration

// test-integration.js
const { detect, check, getMinimumESVersion } = require('fast-brake');

// Test basic functionality
console.log('Testing fast-brake integration...');

const testCode = `
  const arrow = () => {};
  class MyClass {
    #private = 'secret';
  }
`;

(async () => {
  console.log('Features:', await detect(testCode));
  console.log('ES5 compatible:', await check(testCode, { target: 'es5' }));
  console.log('FastBrake results:', await fastBrake(testCode));
  
  console.log('✓ Integration test passed!');
})();

Next Steps

Once you have fast-brake installed and working:

  1. Explore the API - Check out the API Reference for detailed documentation
  2. Understand the Architecture - Learn about the pattern matching system in Architecture
  3. Advanced Usage - Discover power-user features in Advanced Features
  4. Get Help - Visit Troubleshooting if you run into issues

Quick Reference

import { fastBrakeSync, fastBrake, detect, check } from 'fast-brake';

// FASTEST: Sync API
const fb = fastBrakeSync();
const isCompatible = fb.check(code, { target: 'es2018' }); // instant
const features = fb.detect(code); // instant

// Async API when needed
const asyncResults = await fastBrake(code);
const asyncFeatures = await detect(code);
const asyncIsCompatible = await check(code, { target: 'es2018' });

That’s it! You’re ready to start using fast-brake for ES feature detection.