@dmitryrechkin/eslint-standard 1.4.2 โ†’ 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,800 +1,200 @@
1
-
2
1
  # @dmitryrechkin/eslint-standard
3
2
 
4
- A comprehensive ESLint configuration package with TypeScript support, featuring **automatic formatting and code organization**. This configuration enforces consistent code style across projects with powerful auto-fixing capabilities for imports, class members, JSDoc comments, and more.
5
-
6
- ## โœจ Features
7
-
8
- ### **Auto-Fixing Capabilities**
9
- - ๐Ÿ”„ **Automatic Import Sorting**: Organizes imports with type imports and regular imports properly grouped
10
- - ๐Ÿ—๏ธ **Class Member Ordering**: Auto-reorders class members by visibility (public โ†’ protected โ†’ private) and type (fields โ†’ constructor โ†’ methods)
11
- - ๐Ÿ“ **JSDoc Alignment**: Automatically fixes JSDoc comment indentation and alignment with proper tab formatting
12
- - ๐Ÿ“‘ **JSDoc Requirements**: Enforces comprehensive JSDoc documentation with auto-generation of comment blocks
13
- - ๐Ÿงน **Unused Import Removal**: Automatically detects and removes unused imports
14
-
15
- ### **Code Style Enforcement**
16
- - **TypeScript Support**: Full integration with `@typescript-eslint` for TypeScript-specific best practices
17
- - **Modern JavaScript**: Supports ECMAScript 2020 and newer features
18
- - **Consistent Formatting**: Enforces Allman brace style, tab indentation, single quotes, and semicolons
19
- - **Naming Conventions**: Comprehensive naming rules for variables, functions, classes, and more
20
- - **JSDoc Documentation**: Requires comprehensive documentation for all exported functions, classes, methods, interfaces, types, and enums
21
- - **Code Complexity Rules**: Industry-standard complexity metrics to ensure maintainable code
22
- - **Customizable**: Flexible configuration options for different project needs
23
-
24
- ## ๐Ÿ“ฆ Installation
25
-
26
- ### Install the Package and Peer Dependencies
27
-
28
- ```bash
29
- npm install @dmitryrechkin/eslint-standard --save-dev
30
- ```
3
+ A comprehensive ESLint configuration package with TypeScript support, featuring Prettier integration and industry-standard rules.
31
4
 
32
- ### Install Required Peer Dependencies
5
+ ## ๐Ÿš€ Quick Start
33
6
 
34
- ```bash
35
- npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-unused-imports @stylistic/eslint-plugin eslint-plugin-jsdoc eslint-plugin-simple-import-sort eslint-plugin-perfectionist --save-dev
36
- ```
7
+ ### Installation
37
8
 
38
- Or using a single command:
39
9
  ```bash
40
- npm install @dmitryrechkin/eslint-standard eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-unused-imports @stylistic/eslint-plugin eslint-plugin-jsdoc eslint-plugin-simple-import-sort eslint-plugin-perfectionist --save-dev
10
+ npm install -D @dmitryrechkin/eslint-standard
11
+ npx @dmitryrechkin/eslint-standard install-deps
41
12
  ```
42
13
 
43
- ## ๐Ÿš€ Usage
44
-
45
- ### ESLint 9+ Flat Config (Recommended)
46
-
47
- Create an `eslint.config.mjs` file in your project root:
14
+ ### Basic Usage
48
15
 
49
16
  ```javascript
50
- import eslintStandard from '@dmitryrechkin/eslint-standard';
17
+ // eslint.config.mjs
18
+ import config from '@dmitryrechkin/eslint-standard';
51
19
 
52
- export default eslintStandard({
53
- tsconfigPath: './tsconfig.json', // Optional: specify path to your tsconfig
54
- files: ['**/*.{js,jsx,ts,tsx}'], // Optional: specify file patterns
55
- ignores: ['dist/**', 'node_modules/**'] // Optional: additional ignore patterns
20
+ export default config({
21
+ tsconfigPath: './tsconfig.json'
56
22
  });
57
23
  ```
58
24
 
59
- ### Advanced Configuration
60
-
61
- ```javascript
62
- import eslintStandard from '@dmitryrechkin/eslint-standard';
63
-
64
- export default eslintStandard({
65
- tsconfigPath: './tsconfig.json',
66
- files: ['src/**/*.{ts,tsx}', 'tests/**/*.{ts,tsx}'],
67
- ignores: ['dist/**', 'coverage/**'],
68
- plugins: {
69
- // Add custom plugins
70
- },
71
- rules: {
72
- // Override or add custom rules
73
- 'no-console': 'warn',
74
- 'perfectionist/sort-classes': 'off', // Disable auto class member sorting if needed
75
- // Disable JSDoc requirements if needed
76
- 'jsdoc/require-jsdoc': 'off',
77
- 'jsdoc/require-description': 'off',
78
- // Disable type hint requirements (if you prefer TypeScript-only types)
79
- 'jsdoc/require-param-type': 'off',
80
- 'jsdoc/require-returns-type': 'off',
81
- 'jsdoc/no-types': ['error', { contexts: ['any'] }]
82
- }
83
- });
84
- ```
25
+ ## ๐Ÿ“‹ Available Presets
85
26
 
86
- ### Multiple Configurations
27
+ ### Standard (Default)
28
+ Balanced configuration suitable for most projects.
87
29
 
88
30
  ```javascript
89
- import eslintStandard from '@dmitryrechkin/eslint-standard';
90
-
91
- export default [
92
- // Configuration for source files
93
- eslintStandard({
94
- tsconfigPath: './tsconfig.json',
95
- files: ['src/**/*.{ts,tsx}']
96
- }),
97
-
98
- // Configuration for test files with different rules
99
- eslintStandard({
100
- tsconfigPath: './tsconfig.json',
101
- files: ['tests/**/*.{ts,tsx}'],
102
- rules: {
103
- 'no-console': 'off' // Allow console in tests
104
- }
105
- })
106
- ];
107
- ```
108
-
109
- ## ๐Ÿ› ๏ธ Package.json Scripts
110
-
111
- Add these scripts to your `package.json` for easy linting and formatting:
112
-
113
- ```json
114
- {
115
- "scripts": {
116
- "lint": "eslint .",
117
- "lint:fix": "eslint . --fix",
118
- "format": "eslint . --fix"
119
- }
120
- }
31
+ import config from '@dmitryrechkin/eslint-standard';
32
+ export default config();
121
33
  ```
122
34
 
123
- ### Usage Examples
124
-
125
- ```bash
126
- # Check for linting errors
127
- npm run lint
128
-
129
- # Auto-fix all fixable issues (imports, member ordering, JSDoc alignment, etc.)
130
- npm run lint:fix
35
+ ### Aggressive
36
+ Enhanced unused code detection for maximum code quality.
131
37
 
132
- # Same as lint:fix
133
- npm run format
134
- ```
135
-
136
- ## ๐ŸŽฏ What Gets Auto-Fixed
137
-
138
- When you run `eslint --fix`, this configuration will automatically:
139
-
140
- 1. **๐Ÿ“ค Sort Imports**: Organize import statements with type imports grouped correctly
141
- 2. **๐Ÿ”„ Reorder Class Members**: Arrange class members by visibility and type:
142
- - Static properties โ†’ Instance properties โ†’ Constructor โ†’ Static methods โ†’ Instance methods
143
- - Within each group: public โ†’ protected โ†’ private
144
- 3. **๐Ÿ“ Fix JSDoc Comments**:
145
- - Generate missing JSDoc comment blocks for functions, classes, methods, interfaces, types, and enums
146
- - Align JSDoc comments with proper tab indentation
147
- - Add parameter and return value placeholders
148
- 4. **๐Ÿงน Remove Unused Imports**: Clean up unused import statements
149
- 5. **โœจ Format Code**: Apply consistent spacing, quotes, semicolons, and brace styles
150
-
151
- ## ๐Ÿ“Š Code Complexity Rules
152
-
153
- This configuration includes industry-standard complexity rules to ensure code maintainability:
154
-
155
- ### Why Complexity Matters
156
- Research shows that code complexity directly correlates with:
157
- - **Bug Density**: Complex code has 2-3x more bugs (McCabe, 1976)
158
- - **Maintenance Cost**: 80% of software cost is maintenance (Boehm, 1987)
159
- - **Developer Productivity**: Simple code is understood 5x faster (Shepperd, 1988)
160
- - **Testing Difficulty**: Complex functions require exponentially more test cases
161
-
162
- ### Industry Standards & Research
163
- Our pragmatic thresholds balance ideal practices with real-world needs:
164
- - **McCabe Cyclomatic Complexity**: <10 is ideal, 15 is acceptable (NIST 500-235)
165
- - **Function Length**: 50-100 lines is reasonable for complex business logic
166
- - **Code Complete** (Steve McConnell): Maximum nesting depth of 3-4 levels
167
- - **Linux Kernel Style Guide**: 3 levels of indentation maximum
168
- - **Google Style Guide**: Functions that fit on one screen (roughly 50-80 lines)
169
- - **Real-world experience**: Most well-maintained codebases have functions under 50 lines
170
-
171
- ### Built-in Complexity Metrics
172
- All complexity rules use ESLint's built-in rules - no additional packages needed:
173
- - **Cyclomatic Complexity**: Max 10 paths through a function (pragmatic balance)
174
- - **Function Length**: Max 100 lines per function (realistic for complex logic)
175
- - **Statement Count**: Max 20 statements per function
176
- - **Nesting Depth**: Max 3 levels of block nesting
177
- - **Callback Nesting**: Max 3 levels of nested callbacks
178
- - **Parameters**: Max 4 parameters per function
179
- - **File Length**: Warning at >300 lines per file
180
- - **Line Length**: Max 120 characters (ignoring URLs and strings)
181
- - **Early Returns**: Enforces guard clauses and early returns
182
- - **No Nested Ternary**: Prevents complex conditional expressions
183
-
184
- ### Customizing Complexity Thresholds
185
38
  ```javascript
186
- export default eslintStandard({
187
- tsconfigPath: './tsconfig.json',
188
- rules: {
189
- // Adjust complexity limits for legacy code
190
- 'complexity': ['error', 15], // Allow up to 15
191
- 'max-lines-per-function': ['error', { max: 100 }], // Allow longer functions
192
- 'max-depth': ['warn', { max: 4 }], // Warn instead of error
193
- // Or disable specific rules
194
- 'max-lines': 'off' // Disable file length check
195
- }
196
- });
39
+ import config from '@dmitryrechkin/eslint-standard/aggressive';
40
+ export default config();
197
41
  ```
198
42
 
199
- ## ๐Ÿ›ก๏ธ Additional Bulletproof Code Rules
200
-
201
- ### Currently Enforced
202
- Beyond complexity, this configuration enforces comprehensive bulletproof code rules using ESLint core and TypeScript ESLint plugin (no additional packages needed):
203
-
204
- **Type & Promise Safety**
205
- - Explicit function return types required
206
- - **No `any` type allowed** - use `unknown` or specific types
207
- - No floating promises - must await or handle
208
- - Only await actual promises (no awaiting non-thenables)
209
- - No unnecessary `return await`
210
- - Async functions must contain `await`
211
- - No async in Promise constructor
212
-
213
- **Array & Collection Safety**
214
- - No `delete` on arrays (use splice)
215
- - Array methods must return values in callbacks
216
- - No duplicate imports
217
- - Unique enum values
218
-
219
- **Error Handling & Control Flow**
220
- - Only throw Error objects (no string literals)
221
- - No empty catch blocks
222
- - No switch case fallthrough without comment
223
- - No unreachable code after return/throw
224
-
225
- **Null/Undefined Safety**
226
- - Warns on always-truthy/falsy conditions
227
- - Safe optional chaining usage
228
- - No variable shadowing
229
- - Define variables before use
230
-
231
- **Loop & Performance Safety**
232
- - Correct loop direction (prevents infinite loops)
233
- - Loop conditions must be modifiable
234
- - Warns on `await` in loops (performance)
235
-
236
- **Security Basics**
237
- - No `eval()` or implied eval
238
- - No `new Function()`
239
- - No string-based setTimeout/setInterval
240
-
241
- **Code Clarity & Immutability**
242
- - Always use curly braces (prevents bugs)
243
- - Strict equality (`===` and `!==`) required
244
- - `const` for unchanged variables, no `var`
245
- - **Magic numbers warning** - Common values allowed (0, 1, -1, 2, 10, 100, 1000, HTTP codes, time constants)
246
- - **No parameter reassignment** - Can't reassign parameters, but property mutation allowed for practical reasons
247
- - Console.log warnings (only warn/error allowed)
248
- - No side-effect free expressions (short-circuit `&&`/`||` allowed)
249
- - Early returns encouraged
250
-
251
- ### What's NOT Included (Too Strict for Most)
252
- These rules are powerful but may be too strict for some teams:
43
+ **Features:**
44
+ - โœ… Enhanced unused variable detection
45
+ - โœ… Import/export cleanup
46
+ - โœ… Dead code detection (unreachable code)
47
+ - โœ… Strict unused expressions rules
48
+ - โœ… TypeScript-specific cleanup
49
+
50
+ ### Library
51
+ Optimized for TypeScript libraries with strict API requirements.
253
52
 
254
53
  ```javascript
255
- export default eslintStandard({
256
- tsconfigPath: './tsconfig.json',
257
- rules: {
258
- // Ultra-strict type safety
259
- '@typescript-eslint/strict-boolean-expressions': 'error', // No truthy/falsy
260
- '@typescript-eslint/no-non-null-assertion': 'error', // No ! operator
261
-
262
- // Extreme conventions
263
- 'no-implicit-coercion': 'error', // Explicit type conversions
264
- 'id-length': ['error', { min: 2 }], // Minimum variable name length
265
-
266
- // Pure functional programming
267
- 'no-let': 'error', // Only const allowed
268
- '@typescript-eslint/prefer-readonly-parameter-types': 'error', // Deep immutability
269
- }
270
- });
54
+ import config from '@dmitryrechkin/eslint-standard/library';
55
+ export default config();
271
56
  ```
272
57
 
273
- ### Pragmatic Adjustments
58
+ **Features:**
59
+ - โœ… Very strict unused exports detection
60
+ - โœ… API documentation requirements (JSDoc)
61
+ - โœ… Explicit return types
62
+ - โœ… No console/debugging code
63
+ - โœ… Enhanced type safety rules
274
64
 
275
- Our rules balance strictness with real-world practicality:
65
+ ## โš™๏ธ Configuration Options
276
66
 
277
- 1. **Magic Numbers**: Set to `warn` instead of `error`, with common values pre-allowed
278
- 2. **Parameter Mutation**: Properties can be mutated (common in normalization functions)
279
- 3. **Short-Circuit Evaluation**: `condition && doSomething()` pattern is allowed
280
- 4. **Console Warnings**: Only warns to allow debugging
281
- 5. **Await in Loops**: Warning only - sometimes sequential is intentional
67
+ All configurations accept the same configuration options:
282
68
 
283
- ### Handling `any` Types
284
- While `any` is banned by default, you can:
285
- 1. Use `unknown` for truly unknown types
286
- 2. Use proper type assertions
287
- 3. Temporarily disable for migration:
288
69
  ```javascript
289
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
290
- const legacyData: any = oldApi.getData();
70
+ export default config({
71
+ tsconfigPath: './tsconfig.json', // Path to TypeScript config
72
+ ignores: ['build/**', 'dist/**'], // Additional ignore patterns
73
+ files: ['src/**/*'], // File patterns to lint
74
+ rules: { // Rule overrides
75
+ 'no-console': 'warn'
76
+ }
77
+ });
291
78
  ```
292
79
 
293
- ## ๐Ÿ“Š Industry Standards Comparison
294
-
295
- ### How We Compare to Popular Configurations
296
-
297
- This configuration is **more comprehensive and stricter** than industry standards while maintaining practical flexibility:
80
+ ## ๐Ÿ› ๏ธ CLI Commands
298
81
 
299
- | Configuration | Immutability | Complexity | Security | TypeScript | Assessment |
300
- |---------------|-------------|------------|----------|------------|------------|
301
- | **Airbnb** | Basic (`prefer-const`, `no-param-reassign`) | None | Basic | Limited | โœ… Most popular |
302
- | **Google** | Basic (`prefer-const`) | None | Basic | Limited | โœ… Clean & simple |
303
- | **Standard** | Basic (`prefer-const`) | None | Basic | Limited | โœ… Zero config |
304
- | **This Config** | **Pragmatic immutability guidance** | **10+ complexity metrics** | **12+ security rules** | **25+ TS-specific rules** | ๐ŸŸข **Enterprise-grade** |
82
+ The package includes a CLI for dependency management:
305
83
 
306
- ### **๐ŸŽฏ Where We Excel Beyond Standards:**
307
-
308
- #### **Functional Programming & Immutability**
309
- - **Airbnb/Standard**: Only basic `prefer-const` and `no-param-reassign`
310
- - **This Config**: Pragmatic immutability guidance (`prefer-const`, `prefer-readonly-type`, `no-param-reassign`)
311
- - **Advantage**: Encourages immutability without dogmatic restrictions that break real-world patterns
312
-
313
- #### **Code Complexity Management**
314
- - **Industry Standard**: Usually no complexity rules (default: 20 cyclomatic complexity)
315
- - **This Config**: Comprehensive complexity metrics (cyclomatic: 10, cognitive: 15, max-lines: 100)
316
- - **Advantage**: Catches maintainability issues before they become technical debt
317
-
318
- #### **Security & Safety**
319
- - **Industry Standard**: Basic or no security rules
320
- - **This Config**: 12+ security rules + 25+ TypeScript safety rules
321
- - **Advantage**: Enterprise-level security scanning built-in
322
-
323
- #### **TypeScript Integration**
324
- - **Industry Standard**: Basic TypeScript support
325
- - **This Config**: Comprehensive TypeScript-specific safety and style rules
326
- - **Advantage**: Leverages TypeScript's full potential for bug prevention
327
-
328
- ### **๐Ÿ” Practical Impact vs Industry Standards**
329
-
330
- | Metric | Airbnb/Standard | This Configuration | Improvement |
331
- |--------|-----------------|-------------------|-------------|
332
- | **Bug Prevention** | ~60-70% | **~95%** | **+35% fewer bugs** |
333
- | **Security Coverage** | ~20% | **~90%** | **+70% security coverage** |
334
- | **Maintainability** | No metrics | **Comprehensive** | **Prevents technical debt** |
335
- | **Type Safety** | Basic | **Advanced** | **Prevents runtime errors** |
84
+ ```bash
85
+ # Install all peer dependencies
86
+ npx @dmitryrechkin/eslint-standard install-deps
336
87
 
337
- ### **โš–๏ธ Industry Position**
88
+ # Check if dependencies are installed
89
+ npx @dmitryrechkin/eslint-standard check-deps
338
90
 
91
+ # Auto-install missing dependencies
92
+ npx @dmitryrechkin/eslint-standard check-deps --install
339
93
  ```
340
- Basic Standard Airbnb This Config Ultra-Strict
341
- โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
342
- โ””โ”€ Google โ””โ”€ Most โ””โ”€ You're here โ””โ”€ Impractical
343
- Standard teams (dogmatic)
344
- ```
345
-
346
- **Verdict**: This configuration provides **enterprise-grade code quality** while remaining **practically usable** - significantly more comprehensive than industry standards.
347
-
348
- ## โš ๏ธ Warning vs Error Philosophy
349
-
350
- ### **The Problem with Warnings Nobody Fixes**
351
-
352
- > *"If we can pass then should not even display anything because nobody is going to get back to fix it"*
353
-
354
- This configuration takes a **practical approach** to warning vs error severity:
355
-
356
- ### **๐Ÿ”ด Rules Set to ERROR (Build Breaking)**
357
- These **must be fixed** before deployment - they represent serious bugs or security issues:
358
-
359
- **Type & Promise Safety**
360
- - `@typescript-eslint/no-explicit-any` - No `any` types (use `unknown`)
361
- - `@typescript-eslint/no-floating-promises` - Must await or handle promises
362
- - `@typescript-eslint/no-misused-promises` - Correct promise usage
363
- - `@typescript-eslint/only-throw-error` - Only throw Error objects
364
-
365
- **Security & Safety**
366
- - `no-eval`, `no-implied-eval` - No eval usage
367
- - `security/detect-pseudoRandomBytes` - Cryptographically secure random
368
- - `security/detect-unsafe-regex` - Prevent ReDoS attacks
369
- - `no-secrets/no-secrets` - Block secrets in code
370
94
 
371
- **Code Quality**
372
- - `complexity: 10` - Hard limit on function complexity
373
- - `max-params: 4` - Maximum 4 parameters per function
374
- - `sonarjs/cognitive-complexity: 15` - Cognitive complexity limit
95
+ ## ๐ŸŽฏ Rule Categories
375
96
 
376
- ### **โš ๏ธ Rules Set to WARN (Guidance Only)**
377
- These provide **guidance** but don't break builds - developers **should** address them but **can** proceed:
97
+ ### Code Quality & Safety
98
+ - **Type Safety**: Strict TypeScript rules, ban `any` type
99
+ - **Error Prevention**: Catch common bugs and unsafe patterns
100
+ - **Security**: Prevent common security vulnerabilities
101
+ - **Performance**: Avoid performance anti-patterns
378
102
 
379
- **Code Improvement**
380
- - `no-magic-numbers` - Named constants preferred (but exceptions allowed)
381
- - `id-length` - Descriptive names encouraged
382
- - `@typescript-eslint/naming-convention` - Consistent naming
103
+ ### Code Style & Formatting
104
+ - **Brace Style**: Allman style (braces on new lines) via Prettier
105
+ - **Indentation**: Tabs with consistent spacing
106
+ - **Import Organization**: Automatic import sorting and grouping
107
+ - **JSDoc**: Required documentation with proper formatting
383
108
 
384
- **Performance Hints**
385
- - `no-await-in-loop` - Usually better alternatives exist
386
- - `promise/prefer-await-to-then` - Modern async/await preferred
387
- - `unicorn/no-array-reduce` - Often clearer alternatives exist
109
+ ### Modern JavaScript/TypeScript
110
+ - **ES2020+ Features**: Prefer modern syntax and APIs
111
+ - **Functional Programming**: Pragmatic immutability patterns
112
+ - **Promise Handling**: Proper async/await usage
113
+ - **Import/Export**: Clean module system usage
388
114
 
389
- **File Organization**
390
- - `max-lines: 300` - Suggests file splitting
391
- - `import/max-dependencies: 20` - Suggests decoupling
115
+ ## ๐Ÿ“Š Preset Comparison
392
116
 
393
- **Test-Specific Flexibility**
394
- - Test files have relaxed warnings since test code has different requirements
117
+ | Feature | Standard | Aggressive | Library |
118
+ |---------|----------|------------|---------|
119
+ | Unused imports cleanup | โœ… | โœ… | โœ… |
120
+ | Unused variables detection | Basic | Enhanced | Enhanced |
121
+ | Dead code detection | Basic | โœ… | โœ… |
122
+ | Unused exports check | โŒ | โœ… | Very Strict |
123
+ | JSDoc requirements | Basic | Basic | Strict |
124
+ | Console statements | Warning | Warning | Error |
125
+ | Return type hints | Error | Error | Explicit |
126
+ | Type safety | High | High | Very High |
395
127
 
396
- ### **๐ŸŽฏ Conversion Strategy**
128
+ ## ๐Ÿ”ง External Tools Integration
397
129
 
398
- **Practical Functional Programming Rules Applied:**
399
- - `functional/no-let` โ†’ **DISABLED** (replaced with smarter `prefer-const` rule)
400
- - `functional/prefer-readonly-type` โ†’ Keep as `warn` (immutability guidance for interfaces)
401
- - `functional/immutable-data` โ†’ **DISABLED** (incompatible with common JS/TS patterns)
402
-
403
- **Reasoning**:
404
-
405
- **๐Ÿšซ Why `functional/immutable-data` is Disabled:**
406
- This rule is fundamentally incompatible with common, legitimate JavaScript/TypeScript patterns:
407
-
408
- ```typescript
409
- // โŒ Rule would complain about these common patterns:
410
- const result = {};
411
- result.user = await findUser(); // Builder pattern
412
- result.customer = await findCustomer(); // Gradual construction
413
-
414
- const config = {};
415
- config.apiUrl = process.env.API_URL; // Configuration building
416
- config.timeout = 5000; // Property assignment
417
-
418
- const data = [];
419
- data.push(item); // Array building
420
- ```
421
-
422
- **๐Ÿ”„ Why `functional/no-let` is Replaced:**
423
-
424
- The `functional/no-let` rule produces **misleading warnings** because it can't understand control flow:
425
-
426
- ```typescript
427
- // โŒ functional/no-let incorrectly warns about these:
428
- let events = []; // But gets reassigned in try-catch!
429
- let claimId = undefined; // But gets reassigned conditionally!
430
-
431
- // โœ… Built-in prefer-const is much smarter:
432
- let count = 0; // No warning - gets incremented
433
- const name = 'x'; // Would warn if you used 'let' here
434
- ```
435
-
436
- **Alternative**: Use ESLint's built-in `prefer-const` rule - it's **smarter** and produces **fewer false positives**.
437
-
438
- ### **๐Ÿ—๏ธ Build vs Development Experience**
130
+ For comprehensive unused code detection, consider these additional tools:
439
131
 
440
132
  ```bash
441
- # โœ… BUILD PASSES - Critical issues only
442
- npm run lint
443
-
444
- # โš ๏ธ SHOWS WARNINGS - Full guidance
445
- npm run lint:dev # (if you want to see all warnings)
446
- ```
447
-
448
- **Result**: Builds only fail for **serious issues** that **must** be fixed, while warnings provide **improvement guidance** without blocking development.
133
+ # Find unused exports
134
+ npx ts-prune
449
135
 
450
- ## ๐Ÿ”„ Pragmatic Approach to Functional Programming
136
+ # Find unused files
137
+ npx unimported
451
138
 
452
- ### **Philosophy: Flexibility Over Dogma**
139
+ # Advanced dead code analysis
140
+ npx knip
453
141
 
454
- This configuration takes a **pragmatic approach** to functional programming rules, allowing developers to choose the right tool for each situation rather than enforcing rigid patterns that often conflict with real-world JavaScript/TypeScript development.
455
-
456
- ### **๐ŸŽฏ Key Rule Decisions**
457
-
458
- #### **Loop Statements: Choose What's Best**
459
- - `functional/no-loop-statements`: **OFF** - Use `forEach`, `for...of`, or traditional loops based on what's clearest
460
- - `unicorn/no-array-for-each`: **OFF** - Prevents automatic conversion that fights with your choices
461
-
462
- **Why**: Different situations call for different approaches:
463
- ```typescript
464
- // โœ… forEach for side effects with clean syntax
465
- items.forEach(item => console.log(item));
466
-
467
- // โœ… for...of when you need break/continue
468
- for (const item of items) {
469
- if (shouldSkip(item)) continue;
470
- if (shouldStop(item)) break;
471
- process(item);
472
- }
473
-
474
- // โœ… Traditional for loop when you need the index
475
- for (let i = 0; i < items.length; i++) {
476
- items[i] = transform(items[i], i);
477
- }
478
- ```
479
-
480
- #### **Readonly Types: Practical Over Pure**
481
- - `functional/prefer-readonly-type`: **OFF** - Too aggressive, adds `readonly` everywhere breaking compilation
482
-
483
- **Why**: This rule breaks practical patterns:
484
- ```typescript
485
- // โŒ Rule would force this everywhere:
486
- interface Config {
487
- readonly apiUrl: readonly string;
488
- readonly timeout: readonly number;
489
- readonly headers: readonly ReadonlyArray<readonly string>;
490
- }
491
-
492
- // โœ… We prefer developer choice:
493
- interface Config {
494
- apiUrl: string; // Immutable by convention
495
- timeout: number; // No need for readonly noise
496
- readonly token: string; // Explicitly readonly where it matters
497
- }
498
- ```
499
-
500
- #### **Immutable Data: Incompatible with JavaScript**
501
- - `functional/immutable-data`: **OFF** - Fundamentally incompatible with normal JS/TS patterns
502
-
503
- **Why**: Even with exceptions, this rule fights against JavaScript's nature:
504
- ```typescript
505
- // โŒ Rule complains about common patterns:
506
- const config = {};
507
- config.apiUrl = getApiUrl(); // Building objects incrementally
508
- config.timeout = getTimeout(); // Normal property assignment
509
-
510
- const results = [];
511
- for (const item of items) {
512
- results.push(await process(item)); // Building arrays
513
- }
142
+ # Find unused dependencies
143
+ npx depcheck
514
144
  ```
515
145
 
516
- ### **โš–๏ธ Industry Comparison**
517
-
518
- Our approach aligns with **real-world usage** rather than theoretical purity:
519
-
520
- | Approach | forEach Usage | Immutability | Real Projects | Our Config |
521
- |----------|--------------|--------------|---------------|------------|
522
- | **Airbnb** | Prefers functional | Basic (`const`) | React, Netflix | โœ… Flexible |
523
- | **Google** | No preference | Basic (`const`) | Angular, Chrome | โœ… Flexible |
524
- | **Functional Purists** | Banned | Everything readonly | Few | โŒ Too rigid |
525
-
526
- **Popular Projects Using Pragmatic Approaches:**
527
- - **React**: Uses `forEach`, `for...of`, and mutable operations internally
528
- - **Vue**: Extensive use of mutable state and traditional loops
529
- - **Node.js**: Built on mutable patterns, uses all loop types
530
- - **TypeScript Compiler**: Uses traditional loops and mutable data structures
531
-
532
- ### **๐ŸŽจ When to Use What**
533
-
534
- **Use `forEach` when:**
535
- - Performing side effects on each element
536
- - The operation is simple and doesn't need early exit
537
- - You want clean, functional-looking code
146
+ ## ๐Ÿšฆ Usage Recommendations
538
147
 
539
- **Use `for...of` when:**
540
- - You need `break` or `continue`
541
- - Working with iterables (not just arrays)
542
- - You want cleaner syntax than traditional `for`
148
+ ### For Applications
149
+ Use **Standard** preset - provides good balance of strictness and practicality.
543
150
 
544
- **Use traditional `for` when:**
545
- - You need the index
546
- - Performance is critical (marginally faster)
547
- - You're modifying the array during iteration
151
+ ### For Libraries
152
+ Use **Library** preset - ensures clean public APIs and comprehensive documentation.
548
153
 
549
- **Use functional methods (`map`, `filter`, `reduce`) when:**
550
- - Transforming data immutably
551
- - Chaining operations
552
- - The intent is clearer than loops
154
+ ### For Maximum Code Quality
155
+ Use **Aggressive** preset - comprehensive unused code detection.
553
156
 
554
- ### **๐Ÿ“Š The Numbers**
157
+ ## ๐Ÿ” Example Projects
555
158
 
556
- Based on analysis of top GitHub projects:
557
- - **70%** use mixed approaches (loops AND functional methods)
558
- - **25%** prefer functional style but still use loops when needed
559
- - **5%** attempt pure functional (often with heavy libraries)
560
- - **0%** successfully avoid all mutations in real applications
561
-
562
- **Conclusion**: This configuration reflects how **successful projects actually work**, not how theoretical articles say they should work.
563
-
564
- ## ๐Ÿ“ˆ Real Impact
565
-
566
- With all these rules enabled, this configuration catches:
567
- - **95%** of common JavaScript/TypeScript bugs
568
- - **100%** of promise-related errors
569
- - **100%** of null/undefined access errors
570
- - **90%** of infinite loop bugs
571
- - **100%** of precision loss bugs
572
- - **100%** of security issues from eval/Function
573
-
574
- The rules are based on real bugs found in production codebases and focus on pragmatic safety without dogma.
575
-
576
- ## ๐Ÿ“‹ Code Style Overview
577
-
578
- ### ๐Ÿ”ง Formatting Rules
579
-
580
- - **Brace Style**: Allman style (braces on new lines)
581
- - **Indentation**: Tabs (configurable tab width)
582
- - **Quotes**: Single quotes for strings
583
- - **Semicolons**: Required at statement ends
584
- - **Trailing Spaces**: Automatically removed
585
-
586
- ### ๐Ÿ“ Before and After Examples
587
-
588
- #### Import Sorting
589
- ```typescript
590
- // โŒ Before
591
- import { TypeResponse } from '../types';
592
- import type { SomeInterface } from './interfaces';
593
- import { EnumErrorCode } from '../enums';
594
- import type { BaseConfig } from '../config';
595
-
596
- // โœ… After (auto-fixed)
597
- import type { BaseConfig } from '../config';
598
- import type { SomeInterface } from './interfaces';
599
- import { EnumErrorCode } from '../enums';
600
- import { TypeResponse } from '../types';
601
- ```
602
-
603
- #### Class Member Ordering
604
- ```typescript
605
- // โŒ Before
606
- export class UserService
607
- {
608
- private isInitialized = false;
609
- public static VERSION = '1.0.0';
610
- public name: string;
611
-
612
- private validateUser() { /* ... */ }
613
- public async getUser() { /* ... */ }
614
- public static getInstance() { /* ... */ }
615
- constructor(name: string) { /* ... */ }
616
- }
617
-
618
- // โœ… After (auto-fixed)
619
- export class UserService
620
- {
621
- public static VERSION = '1.0.0';
622
-
623
- public name: string;
624
- private isInitialized = false;
625
-
626
- constructor(name: string) { /* ... */ }
627
-
628
- public static getInstance() { /* ... */ }
629
-
630
- public async getUser() { /* ... */ }
631
-
632
- private validateUser() { /* ... */ }
633
- }
634
- ```
635
-
636
- #### JSDoc Documentation with Type Hints
637
- ```typescript
638
- // โŒ Before - Missing JSDoc
639
- export function processUser(userData: UserData): ProcessedResult {
640
- return process(userData);
641
- }
642
-
643
- // โš ๏ธ After (auto-fixed) - JSDoc block generated but missing type hints
644
- /**
645
- *
646
- * @param userData
647
- * @returns
648
- */
649
- export function processUser(userData: UserData): ProcessedResult {
650
- return process(userData);
651
- }
652
-
653
- // โŒ Still fails - Missing type hints and descriptions
654
- // ESLint errors:
655
- // - Missing JSDoc @param "userData" type
656
- // - Missing JSDoc @param "userData" description
657
- // - Missing JSDoc @returns type
658
- // - Missing JSDoc block description
659
-
660
- // โœ… Complete JSDoc with type hints (must be added manually)
661
- /**
662
- * Processes user data and returns formatted result.
663
- * @param {UserData} userData - The user data to process
664
- * @returns {ProcessedResult} The processed user result
665
- */
666
- export function processUser(userData: UserData): ProcessedResult {
667
- return process(userData);
668
- }
669
-
670
- // โš ๏ธ Note: ESLint cannot auto-generate type hints from TypeScript types.
671
- // Type annotations must be added manually to satisfy the linter requirements.
672
- ```
159
+ ### React Application
160
+ ```javascript
161
+ // eslint.config.mjs
162
+ import config from '@dmitryrechkin/eslint-standard';
673
163
 
674
- #### JSDoc Alignment
675
- ```typescript
676
- // โŒ Before
677
- /**
678
- * Process user data
679
- * @param userData - The user data
680
- * @returns Processed result
681
- */
682
-
683
- // โœ… After (auto-fixed)
684
- /**
685
- * Process user data
686
- * @param userData - The user data
687
- * @returns Processed result
688
- */
164
+ export default config({
165
+ tsconfigPath: './tsconfig.json',
166
+ ignores: ['dist/**', 'build/**', 'public/**']
167
+ });
689
168
  ```
690
169
 
691
- ### ๐Ÿท๏ธ Naming Conventions
692
-
693
- - **Variables & Functions**: `camelCase`
694
- - **Classes & Interfaces**: `PascalCase`
695
- - **Constants**: `UPPER_CASE` or `camelCase`
696
- - **Enum Members**: `UPPER_CASE` or `PascalCase`
697
- - **Type Parameters**: `PascalCase`
698
-
699
- ### ๐Ÿ“ JSDoc with Type Hints Requirements
700
-
701
- This configuration requires comprehensive JSDoc documentation with type hints:
702
-
703
- - **Type Annotations Required**: All parameters and return values must include JSDoc type hints
704
- - **Description Required**: All functions, parameters, and return values must have descriptions
705
- - **Auto-generation Limited**: ESLint can generate JSDoc blocks but cannot infer TypeScript types
706
- - **Manual Completion Needed**: Type hints must be added manually after auto-generation
707
-
708
- #### Required JSDoc Format
709
-
170
+ ### TypeScript Library
710
171
  ```javascript
711
- /**
712
- * Function description is required.
713
- * @param {string} name - Parameter description is required
714
- * @param {number} age - Type hint {number} is required
715
- * @returns {string} Return type and description required
716
- */
717
- function greet(name: string, age: number): string {
718
- return `Hello ${name}, you are ${age} years old`;
719
- }
720
- ```
172
+ // eslint.config.mjs
173
+ import config from '@dmitryrechkin/eslint-standard/library';
721
174
 
722
- #### Common Type Hint Patterns
723
-
724
- ```javascript
725
- // Basic types
726
- @param {string} name
727
- @param {number} count
728
- @param {boolean} isActive
729
- @param {Object} config
730
- @param {Array<string>} items
731
- @param {Function} callback
732
-
733
- // Complex types
734
- @param {UserData} userData - Custom type
735
- @param {Promise<Response>} response - Generic type
736
- @param {string|number} id - Union type
737
- @param {{name: string, age: number}} person - Object type
738
- @param {string[]} names - Array shorthand
739
- @returns {void} - For functions with no return
175
+ export default config({
176
+ tsconfigPath: './tsconfig.json',
177
+ ignores: ['dist/**', 'examples/**']
178
+ });
740
179
  ```
741
180
 
742
- #### Important Notes
743
-
744
- 1. **ESLint Cannot Auto-Generate Types**: While ESLint can create JSDoc blocks, it cannot determine TypeScript types
745
- 2. **Manual Work Required**: After running `--fix`, you must manually add all type hints
746
- 3. **Duplication with TypeScript**: This approach duplicates type information already in TypeScript
747
- 4. **Maintenance Overhead**: Types must be kept in sync between TypeScript and JSDoc
748
-
749
- ## โš ๏ธ Troubleshooting
750
-
751
- ### Peer Dependency Warnings
752
-
753
- If you see peer dependency warnings, install all required dependencies:
754
- ```bash
755
- npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-unused-imports @stylistic/eslint-plugin eslint-plugin-jsdoc eslint-plugin-simple-import-sort eslint-plugin-perfectionist --save-dev
181
+ ### Node.js API
182
+ ```javascript
183
+ // eslint.config.mjs
184
+ import config from '@dmitryrechkin/eslint-standard/aggressive';
185
+
186
+ export default config({
187
+ tsconfigPath: './tsconfig.json',
188
+ rules: {
189
+ 'no-console': 'off', // Allow console in Node.js
190
+ }
191
+ });
756
192
  ```
757
193
 
758
- ### ESLint Version Compatibility
759
-
760
- This package requires **ESLint 9+** for flat config support. For older ESLint versions, please use an earlier version of this package.
761
-
762
- ### TypeScript Configuration
763
-
764
- Ensure your `tsconfig.json` is properly configured and the path specified in `tsconfigPath` is correct.
765
-
766
- ## ๐Ÿ”ง Configuration Options
767
-
768
- The configuration function accepts these options:
769
-
770
- | Option | Type | Default | Description |
771
- |--------|------|---------|-------------|
772
- | `tsconfigPath` | `string` | `'./tsconfig.json'` | Path to your TypeScript config file |
773
- | `files` | `string[]` | `['**/*.{js,jsx,ts,tsx}']` | File patterns to lint |
774
- | `ignores` | `string[]` | `['node_modules/**', 'dist/**']` | Patterns to ignore |
775
- | `plugins` | `object` | `{}` | Additional ESLint plugins |
776
- | `rules` | `object` | `{}` | Additional or overridden rules |
777
-
778
- ## ๐Ÿ“š Plugin Documentation
779
-
780
- This configuration uses several powerful ESLint plugins:
781
-
782
- - **[@typescript-eslint](https://typescript-eslint.io/)**: TypeScript-specific linting rules
783
- - **[eslint-plugin-perfectionist](https://perfectionist.dev/)**: Auto-sorting for classes, imports, and more
784
- - **[eslint-plugin-simple-import-sort](https://github.com/lydell/eslint-plugin-simple-import-sort)**: Simple and reliable import sorting
785
- - **[@stylistic/eslint-plugin](https://eslint.style/)**: Stylistic formatting rules
786
- - **[eslint-plugin-unused-imports](https://github.com/sweepline/eslint-plugin-unused-imports)**: Automatic unused import removal
787
-
788
194
  ## ๐Ÿค Contributing
789
195
 
790
- Contributions to improve this ESLint configuration are welcome! Please feel free to:
791
-
792
- - ๐Ÿ› [Report bugs](https://github.com/dmitryrechkin/eslint-standard/issues)
793
- - ๐Ÿ’ก [Suggest new features](https://github.com/dmitryrechkin/eslint-standard/issues)
794
- - ๐Ÿ”ง [Submit pull requests](https://github.com/dmitryrechkin/eslint-standard/pulls)
196
+ Issues and pull requests are welcome on [GitHub](https://github.com/dmitryrechkin/eslint-standard).
795
197
 
796
198
  ## ๐Ÿ“„ License
797
199
 
798
- MIT License - see the [LICENSE](LICENSE) file for details.
799
-
800
-
200
+ MIT License - see LICENSE file for details.