Claude
Skills
Sign in
Back

JavaScript

Included with Lifetime
$97 forever

Execute these commands after EVERY implementation (see AGENT_AUTOMATION module for full workflow).

languageslanguageslanguage

What this skill does

<!-- JAVASCRIPT:START -->
# JavaScript Project Rules

## Agent Automation Commands

**CRITICAL**: Execute these commands after EVERY implementation (see AGENT_AUTOMATION module for full workflow).

```bash
# Complete quality check sequence:
npm run lint              # Linting (0 warnings required)
npm run format            # Code formatting
npm test                  # All tests (100% pass required)
npm run test:coverage     # Coverage check (95%+ required)
npm run build             # Build verification (if applicable)

# Security audit:
npm audit --production    # Vulnerability scan
npm outdated              # Check outdated deps
```

## JavaScript Configuration

**CRITICAL**: Use modern JavaScript (ES2022+) with strict linting and testing.

- **Version**: Node.js 18+
- **Recommended**: Node.js 22 LTS
- **Standard**: ES2022 or later
- **Module System**: ESM (ES Modules)
- **Type**: Set `"type": "module"` in package.json

### package.json Requirements

```json
{
  "name": "your-package",
  "version": "1.0.0",
  "description": "Package description",
  "type": "module",
  "main": "./dist/index.js",
  "exports": {
    ".": {
      "import": "./dist/index.js"
    }
  },
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ],
  "scripts": {
    "build": "esbuild src/index.js --bundle --platform=node --outfile=dist/index.js",
    "test": "vitest --run",
    "test:watch": "vitest",
    "test:coverage": "vitest --coverage",
    "lint": "eslint src/**/*.js tests/**/*.js",
    "lint:fix": "eslint src/**/*.js tests/**/*.js --fix",
    "format": "prettier --write 'src/**/*.js' 'tests/**/*.js'",
    "format:check": "prettier --check 'src/**/*.js' 'tests/**/*.js'"
  },
  "engines": {
    "node": ">=18.0.0"
  },
  "devDependencies": {
    "eslint": "^9.19.0",
    "prettier": "^3.4.0",
    "vitest": "^2.1.0",
    "@vitest/coverage-v8": "^2.1.0",
    "esbuild": "^0.24.0"
  }
}
```

## Code Quality Standards

### Mandatory Quality Checks

**CRITICAL**: After implementing ANY feature, you MUST run these commands in order.

**IMPORTANT**: These commands MUST match your GitHub Actions workflows to prevent CI/CD failures!

```bash
# Pre-Commit Checklist (MUST match .github/workflows/*.yml)

# 1. Lint (MUST pass with no warnings - matches workflow)
npm run lint

# 2. Format check (matches workflow - use check, not write!)
npm run format:check
# or: npx prettier --check 'src/**/*.js' 'tests/**/*.js'

# 3. Run all tests (MUST pass 100% - matches workflow)
npm test

# 4. Build (if applicable - matches workflow)
npm run build

# 5. Check coverage (MUST meet threshold)
npm run test:coverage

# If ANY fails: ❌ DO NOT COMMIT - Fix first!
```

**If ANY of these fail, you MUST fix the issues before committing.**

**Why This Matters:**
- Running different commands locally than in CI causes "works on my machine" failures
- CI/CD workflows will fail if commands don't match
- Example: Using `prettier --write` locally but `prettier --check` in CI = failure
- Example: Skipping lint locally = CI ESLint failures catch errors you missed

### Linting

- Use ESLint 9+ with flat config
- Configuration in `eslint.config.js`
- Must pass with no warnings
- Use recommended rule sets

Example `eslint.config.js`:
```javascript
import js from '@eslint/js';

export default [
  js.configs.recommended,
  {
    files: ['src/**/*.js', 'tests/**/*.js'],
    languageOptions: {
      ecmaVersion: 2022,
      sourceType: 'module',
      globals: {
        console: 'readonly',
        process: 'readonly',
      },
    },
    rules: {
      'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
      'no-console': 'off', // Allow console in Node.js
      'prefer-const': 'error',
      'no-var': 'error',
    },
  },
];
```

### Formatting

- Use Prettier for code formatting
- Configuration in `.prettierrc.json`
- Integrate with ESLint for consistency
- Format before committing

Example `.prettierrc.json`:
```json
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "arrowParens": "always"
}
```

### Testing

- **Framework**: Vitest (recommended), Jest, or Mocha
- **Location**: `/tests` directory
- **Coverage**: Must meet project threshold (default 80%)
- **Watch Mode**: Use `vitest` or `vitest --watch` for development
- **CI Mode**: **CRITICAL** - Default `npm test` command MUST include `--run` flag
  - This prevents Vitest from entering watch mode, which never terminates
  - In `package.json`: `"test": "vitest --run"`
  - For manual development, use `npm run test:watch`

Example test structure:
```javascript
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { myFunction } from '../src/module.js';

describe('myFunction', () => {
  let testData;

  beforeEach(() => {
    testData = { value: 'test' };
  });

  afterEach(() => {
    // Cleanup
  });

  it('should return expected value', () => {
    const result = myFunction(testData);
    expect(result).toBe('expected');
  });

  it('should throw on invalid input', () => {
    expect(() => myFunction(null)).toThrow('Invalid input');
  });
});
```

### S2S (Server-to-Server) and Slow Tests

**CRITICAL**: Separate fast tests from slow/S2S tests.

**Problem**: Mixing fast unit tests with slow integration tests or tests requiring external servers causes:
- ❌ Slow CI/CD pipelines (10+ minutes instead of < 2 minutes)
- ❌ Flaky tests (external services unreliable)
- ❌ Developer frustration (slow test feedback)
- ❌ Blocked commits (waiting for slow tests)

**Solution**: Isolate S2S and slow tests using environment variables and tags.

#### What are S2S/Slow Tests?

**S2S (Server-to-Server) Tests**:
- Require external running servers (databases, APIs, message queues)
- Network I/O heavy
- Typically 5-30 seconds per test
- Examples: Database integration tests, API endpoint tests, message queue tests

**Slow Tests**:
- Long-running operations (processing large files, complex calculations)
- Typically > 5 seconds per test
- Examples: File processing tests, image manipulation, encryption tests

**Fast Tests** (Regular Unit Tests):
- No external dependencies
- In-memory only
- < 100ms per test
- Should be 95%+ of your test suite

#### Implementation Pattern

**1. Mark S2S/slow tests with conditional execution**:

```javascript
// tests/integration/database.test.js
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { setupDatabase, teardownDatabase } from './test-helpers.js';

// Only run if RUN_S2S_TESTS environment variable is set
const runS2STests = process.env.RUN_S2S_TESTS === '1';
const describeS2S = runS2STests ? describe : describe.skip;

describeS2S('Database Integration', () => {
  beforeAll(async () => {
    await setupDatabase();
  });

  afterAll(async () => {
    await teardownDatabase();
  });

  it('should connect to database', async () => {
    const result = await query('SELECT 1');
    expect(result).toBeDefined();
  }, { timeout: 30000 }); // 30 second timeout for S2S tests
});
```

**2. Mark slow tests similarly**:

```javascript
// tests/slow/file-processing.test.js
const runSlowTests = process.env.RUN_SLOW_TESTS === '1';
const describeSlow = runSlowTests ? describe : describe.skip;

describeSlow('Large File Processing', () => {
  it('should process 1GB file', async () => {
    const result = await processLargeFile('large-file.dat');
    expect(result).toBeDefined();
  }, { timeout: 60000 }); // 60 second timeout
});
```

**3. Organize tests by speed**:

```
tests/
├── unit/           # Fast tests (< 100ms) - DEFAULT
│   ├── parser.test.js
│   └── validator.test.js
├── integration/    # S2S tests (require servers)
│   ├── database.test.js
│   └── api.test.js
└── slow/           # Slow tests (> 5 seconds)
    └── file-processing.test.js
```

**4. Add npm scripts in `package.json`**:

```json
{
  "scripts": {
    "test": "vitest --run",
    "test:watch": "vitest",
    "test:s2s": "RUN_S2S_TESTS=1 vitest --run",
    "test:slow": "RUN_SLOW_TESTS=1 vi

Related in languages