eslint-plugin-sonarjs
SonarJS rules for ESLint
Last updated 2 years ago by sonartech .
LGPL-3.0-only · Repository · Bugs · Original npm · Tarball · package.json
$ npm install eslint-plugin-sonarjs 
SYNC missed versions from official npm registry.

eslint-plugin-sonarjs npm version

eslint-plugin-sonarjs is an ESLint plugin maintained by Sonar, designed to help developers write Clean Code. This plugin exposes to ESLint users all original JS/TS rules from SonarJS, an analyzer for JavaScript and TypeScript within the Sonar ecosystem. This plugin offers general-purpose rules for detecting code smells and bugs, as well as rules for other aspects of code quality, including testing, accessibility, and more. Additionally, it enhances code security by providing rules to report potential security vulnerabilities.

This ESLint plugin does not contain all the rules from the SonarQube JS/TS analyzer. Aside of the rules available here, SonarQube uses rules from other ESLint plugins (some used as they are, some others have been modified). We recommend installing those ESLint plugins and enabling those rules if you are looking for similar results to SonarQube using ESLint.

If you are a SonarQube Server or a SonarQube Cloud user, to lint your code locally, we suggest using the SonarQube for IDE extension (available for VSCode, JetBrains IDEs and Eclipse). You can connect SonarQube for IDE to your Server or Cloud project to synchronize rules configuration, issue statuses, etc.

Table of Contents

Changelog

Prerequisites

The prerequisites for using this plugin depend on the ESLint version you are using:

  • For ESLint 8, you need Node.js version >= 18.
  • For ESLint 9, you need Node.js version that complies with (^18.18.0 || ^20.9.0 || >=21).

Installation

First, ensure that your project is configured with ESLint. If it is not, please follow the ESLint instructions to set it up.

To install eslint-plugin-sonarjs, use the following npm command (or yarn equivalent):

npm install eslint-plugin-sonarjs --save-dev # locally
npm install eslint-plugin-sonarjs -g         # globally

Usage

The usage of eslint-plugin-sonarjs depends on the ESLint version used by your project.

For ESLint 9

This plugin provides a single configuration named recommended. This configuration enables most of the rules except for a few exceptions, and the rules are enabled with the error severity. You can enable the recommended configuration in your eslint.config.js file:

import sonarjs from 'eslint-plugin-sonarjs';

export default [sonarjs.configs.recommended];

If you don't use the recommended configuration, you need to declare the plugin manually in the plugins field. Enable or disable rules using the rules field:

import sonarjs from 'eslint-plugin-sonarjs';
export default [
  {
    plugins: { sonarjs },
    rules: {
      'sonarjs/no-implicit-dependencies': 'error',
    },
  },
];

For ESLint 8

We include a recommended-legacy configuration to be backward compatible with ESLint v8, equivalent to the recommended configuration for ESLint 9.

Add sonarjs to your .eslintrc file:

{
  "plugins": ["sonarjs"],
  "extends": ["plugin:sonarjs/recommended-legacy"]
}

You can enable some rules manually:

{
  "rules": {
    "sonarjs/cognitive-complexity": "error",
    "sonarjs/no-identical-expressions": "error"
  }
}

TypeScript ESLint parser

Several rules are designed for linting both JavaScript and TypeScript code, and some even rely on type checking through TypeScript. Therefore, you will need to install the @typescript-eslint/parser dependency and instruct ESLint to use this parser through the parserOptions property.

SonarQube for IDE

As an alternative to using this ESLint plugin, you can use SonarQube for IDE. SonarQube for IDE is an IDE extension that helps you detect and fix quality issues as you write code. It provides a broader set of rules compared to the ESLint plugin, improved versions of ESLint rules, and additional features that enhance your linting experience.

Feedback

If you have any questions, encounter any bugs, or have feature requests, please reach out to us through the Sonar Community Forum. Your messages will reach the maintainers of this GitHub repository.

Rules

💼 Configurations enabled in.
✅ Set in the recommended configuration.
🔧 Automatically fixable by the --fix CLI option.
💡 Manually fixable by editor suggestions.
💭 Requires type information.
❌ Deprecated.

Name Description 💼 🔧 💡 💭 ❌
anchor-precedence Alternatives in regular expressions should be grouped when used with anchors ✅ 💭
argument-type Arguments to built-in functions should match documented types ✅ 💭
arguments-order Parameters should be passed in the correct order ✅ 💭
arguments-usage "arguments" should not be accessed directly
array-callback-without-return Callbacks of array methods should have return statements ✅ 💭
array-constructor Array constructors should not be used 💡
arrow-function-convention Braces and parentheses should be used consistently with arrow functions
assertions-in-test-cases Assertions should be placed inside test cases or hooks ✅
assertions-in-tests Tests should include assertions ✅ 💭
async-test-assertions Async test assertions should be awaited or returned ✅
avoid-mutating-nested-properties-of-shallow-clones Nested properties of Lodash and Underscore.js clone results should not be mutated ✅ 💡
aws-apigateway-public-api AWS API Gateway should require authentication ✅
aws-ec2-rds-dms-public Public network access to cloud resources should be disabled ✅
aws-ec2-unencrypted-ebs-volume EBS volumes should be encrypted ✅
aws-efs-unencrypted Amazon EFS file systems should be encrypted ✅
aws-iam-all-privileges Policies should not grant all privileges ✅
aws-iam-all-resources-accessible IAM policies should not grant access to all account resources
aws-iam-privilege-escalation AWS IAM policies should limit the scope of permissions given ✅
aws-iam-public-access AWS resource-based policies should not grant public access ✅
aws-opensearchservice-domain OpenSearch domains should have encryption at rest enabled ✅
aws-rds-unencrypted-databases Amazon RDS resources should be encrypted at rest ✅
aws-restricted-ip-admin-access Administration services access should be restricted to specific IP addresses ✅
aws-s3-bucket-granted-access S3 buckets should not grant access to all users or authenticated users ✅
aws-s3-bucket-insecure-http S3 buckets should enforce HTTPS-only access ✅
aws-s3-bucket-public-access Amazon S3 bucket public access should be fully blocked ✅
aws-s3-bucket-versioning Amazon S3 buckets should have versioning enabled ✅
aws-sagemaker-unencrypted-notebook SageMaker notebook instances should be encrypted at rest ✅
aws-sns-unencrypted-topics Amazon SNS topics should be encrypted at rest ✅
aws-sqs-unencrypted-queue SQS queues should be encrypted ✅
bitwise-operators Bitwise operators should not be used in boolean contexts ✅ 💭
block-scoped-var Variables should be used in the blocks where they are declared ✅
bool-param-default Optional boolean parameters should have default value
call-argument-line Function call arguments should not start on new lines ✅
chai-determinate-assertion Chai assertions should have only one reason to succeed ✅
class-name Class names should comply with a naming convention ✅
class-prototype Class methods should be used instead of "prototype" assignments 💭
code-eval Dynamic code execution should not use user-controlled data ✅
cognitive-complexity Cognitive Complexity of functions should not be too high ✅
comma-or-logical-or-case Comma and logical OR operators should not be used in switch cases ✅
comment-regex Track comments matching a regular expression
composite-assertions Composite assertions should be split
concise-regex Regular expression quantifiers and character classes should be used concisely ✅ 💭
conditional-indentation A conditionally executed single line should be denoted by indentation ❌
confidential-information-logging Confidential information should not be logged ❌
constructor-for-side-effects Objects should not be created to be dropped immediately without being used ✅
content-length HTTP request content length should be limited ✅
content-security-policy Content security policy fetch directives should not be disabled ✅
cookie-no-httponly Cookies should have the "HttpOnly" flag ✅
cors Cross-Origin Resource Sharing (CORS) policy should be restricted to trusted origins ✅
csrf CSRF protections should not be disabled ✅
cyclomatic-complexity Cyclomatic Complexity of functions should not be too high
declarations-in-global-scope Variables and functions should not be declared in the global scope
deprecation Deprecated APIs should not be used ✅ 💭
destructuring-assignment-syntax Destructuring syntax should be used for assignments
different-types-comparison Strict equality operators should not be used with dissimilar types ✅ 💡 💭
disabled-auto-escaping Auto-escaping in HTML template engines should not be disabled ✅ 💭
disabled-resource-integrity Remote artifacts should not be used without integrity checks ✅ 💭
disabled-timeout Disabling Mocha timeouts should be explicit ✅
dompurify-unsafe-config DOMPurify configuration should not be bypassable ✅ 💭
duplicates-in-character-class Character classes in regular expressions should not contain the same character twice ✅ 💭
dynamically-constructed-templates Templates should not be constructed dynamically ✅
elseif-without-else "if ... else if" constructs should end with "else" clauses
empty-string-repetition Repeated patterns in regular expressions should not match the empty string ✅ 💭
encryption-secure-mode Encryption algorithms should be used with secure mode and padding scheme ✅
existing-groups Replacement strings should reference existing regular expression groups ✅ 💭
explicit-test-skip Tests should be skipped explicitly ✅ 💡
expression-complexity Expressions should not be too complex
file-header Track lack of copyright and license headers
file-name-differ-from-class Default export names and file names should match
file-permissions File permissions should not be set to world-accessible values ✅
file-uploads File uploads should be restricted ✅
fixme-tag Track uses of "FIXME" tags ✅
for-in "for...in" loops should filter properties before acting on them
for-loop-increment-sign A "for" loop update clause should move the counter in the right direction ✅
frame-ancestors Content Security Policy frame-ancestors directive should not be disabled ❌
function-inside-loop Functions should not be defined inside loops ✅
function-name Function and method names should comply with a naming convention
function-return-type Functions should always return the same type ✅ 💭
future-reserved-words Future reserved words should not be used as identifiers ✅
generator-without-yield Generators should explicitly "yield" a value ✅
hardcoded-secret-signatures Credentials should not be hard-coded ✅
hashing Weak hashing algorithms should not be used ✅
hidden-files Hidden files should not be served statically ❌
hooks-before-test-cases Lifecycle hooks should not be interleaved with test cases or nested suites ✅
in-operator-type-error "in" should not be used with primitive types ✅ 💭
inconsistent-function-call Functions should be called consistently with or without "new" ✅
index-of-compare-to-positive-number "indexOf" checks should not be for positive numbers ✅ 💭
insecure-cookie Cookies should have the "secure" flag ✅
insecure-jwt-token JWT should be signed and verified with strong cipher algorithms ✅
inverted-assertion-arguments Assertion arguments should be passed in the correct order ✅ 💡
jsx-no-leaked-render React components should not render non-boolean condition values ✅ 💡 💭
label-position Only "while", "do", "for" and "switch" statements should be labelled ✅
link-with-target-blank Opened windows should not have access to the originating page ✅
max-lines Files should not have too many lines of code
max-lines-per-function Functions should not have too many lines of code
max-switch-cases "switch" statements should not have too many "case" clauses ✅
max-union-size Union types should not have too many elements
memoize-cache-key Lodash and Underscore.js memoize calls on functions with multiple parameters should use an explicit cache key function ✅
misplaced-loop-counter "for" loop increment clauses should modify the loops' counters ✅
nested-control-flow Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
new-operator-misuse "new" should only be used with functions and classes ✅ 💭
no-all-duplicated-branches All branches in a conditional structure should not have exactly the same implementation ✅
no-alphabetical-sort "Array.prototype.sort()" and "Array.prototype.toSorted()" should use a compare function ✅ 💡 💭
no-angular-bypass-sanitization Angular built-in sanitization should not be disabled ✅
no-array-delete "delete" should not be used on arrays ✅ 💭
no-associative-arrays Array indexes should be numeric ✅ 💭
no-async-constructor Constructors should not contain asynchronous operations ✅ 💭
no-built-in-override Built-in objects should not be overridden
no-case-label-in-switch "switch" statements should not contain non-case labels ✅
no-clear-text-protocols Clear-text protocols should not be used ✅
no-code-after-done Tests should not execute any code after "done()" is called ✅
no-collapsible-if Mergeable "if" statements should be combined
no-collection-size-mischeck Collection size and array length comparisons should make sense ✅ 💡 💭
no-commented-code Sections of code should not be commented out 💡
no-control-regex Regular expressions should not contain control characters ✅ 💭
no-dead-store Unused assignments should be removed ✅
no-debounce-throttle-in-render Lodash and Underscore.js debounced or throttled functions should not be recreated on every React render ✅
no-debug-commands-in-ui-tests UI test debug commands should not be committed to version control ✅ 🔧
no-default-utility-imports Default imports from modular utility libraries should not be used ✅
no-delete-var "delete" should be used only with object properties ✅
no-duplicate-in-composite Union and intersection types should not include duplicated constituents ✅ 💡
no-duplicate-parameterized-test-case Parameterized tests should not contain duplicate test cases ✅ 🔧
no-duplicate-string String literals should not be duplicated
no-duplicate-test-title Test titles should be unique within the same suite ✅
no-duplicated-branches Two branches in a conditional structure should not have exactly the same implementation ✅
no-element-overwrite Collection elements should not be replaced unconditionally ✅
no-empty-after-reluctant Reluctant quantifiers in regular expressions should be followed by an expression that can't match the empty string ✅ 💭
no-empty-alternatives Alternation in regular expressions should not contain empty alternatives ✅ 💭
no-empty-character-class Empty character classes should not be used ✅ 💭
no-empty-collection Empty collections should not be accessed or iterated ✅
no-empty-group Regular expressions should not contain empty groups ✅ 💭
no-empty-parameterized-test-dataset Parameterized tests should not have empty datasets ✅
no-empty-test-file Test files should contain at least one test case ✅
no-empty-test-title Test and suite titles should not be empty or whitespace-only ✅
no-equals-in-for-termination Equality operators should not be used in "for" loop termination conditions ✅
no-exclusive-tests Exclusive tests should not be committed to version control ✅ 💡
no-extra-arguments Function calls should not pass extra arguments ✅
no-fallthrough Switch cases should end with an unconditional "break" statement ✅
no-fixed-wait-in-tests Fixed waits should not be used in tests ✅
no-floating-point-equality Floating point numbers should not be tested for equality ✅
no-for-in-iterable "for in" should not be used with iterables 💭
no-forced-browser-interaction Forced browser interactions should not bypass actionability checks ✅
no-function-declaration-in-block Function declarations should not be made within blocks
no-global-this The global "this" object should not be used ✅ 💡
no-globals-shadowing Special identifiers should not be bound or assigned ✅
no-gratuitous-expressions Boolean expressions should not be gratuitous ✅
no-hardcoded-ip IP addresses should not be hardcoded ✅
no-hardcoded-passwords Credentials should not be hard-coded ✅
no-hardcoded-secrets Secrets should not be hard-coded ✅
no-hook-setter-in-body React's useState hook should not be used directly in the render function or body of a component ✅
no-identical-conditions "if/else if" chains and "switch" cases should not have the same condition ✅
no-identical-expressions Identical expressions should not be used on both sides of a binary operator ✅
no-identical-functions Functions should not have identical implementations ✅
no-ignored-exceptions Exceptions should not be ignored ✅
no-ignored-return Return values from functions without side effects should not be ignored ✅ 💭
no-implicit-dependencies Dependencies should be explicit
no-implicit-global Variables should be declared explicitly ✅
no-in-misuse "in" should not be used on arrays ✅ 💡 💭
no-incompatible-assertion-types Assertions comparing incompatible types should not be made ✅ 💭
no-incomplete-assertions Assertions should be complete ✅
no-inconsistent-returns Functions should use "return" consistently 💭
no-incorrect-string-concat Strings and non-strings should not be added 💭
no-internal-api-use Users should not use internal APIs ✅
no-interpolation-in-inline-snapshots Inline snapshots should not contain interpolations ✅
no-intrusive-permissions Sensitive permissions should not be requested unnecessarily ❌
no-invalid-regexp Regular expressions should be syntactically valid ✅ 💭
no-invariant-returns Function returns should not be invariant ✅
no-inverted-boolean-check Boolean checks should not be inverted ✅ 💡
no-ip-forward Client IP address should not be forwarded to proxies ❌
no-labels Labels should not be used ✅
no-literal-call Literals should not be used as functions ✅
no-mime-sniff Browsers should not be allowed to perform MIME type sniffing ✅
no-misleading-array-reverse Array-mutating methods should not be used misleadingly ✅ 💡 💭
no-misleading-character-class Unicode Grapheme Clusters should be avoided inside regex character classes ✅ 💡 💭
no-mixed-completion-style Test and hook callbacks should use a single completion style
no-mixed-content Content Security Policy should block mixed-content ❌
no-mutate-reactive-state-in-updated-hook Reactive state should not be unconditionally mutated inside Vue's "updated" lifecycle hook ✅
no-nested-assignment Assignments should not be made from within sub-expressions ✅
no-nested-conditional Ternary operators should not be nested ✅
no-nested-functions Functions should not be nested too deeply ✅
no-nested-incdec Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression
no-nested-switch "switch" statements should not be nested
no-nested-template-literals Template literals should not be nested ✅
no-networkidle-wait Playwright "networkidle" waits should not be used
no-os-command-from-path OS commands should not rely on PATH resolution ✅
no-parameter-reassignment Initial values of parameters, caught exceptions, and loop variables should not be ignored ✅
no-primitive-wrappers Wrapper objects should not be used for primitive types ✅ 💡
no-redundant-assignments Assignments should not be redundant ✅
no-redundant-boolean Boolean literals should not be used in comparisons ✅ 💡
no-redundant-jump Jump statements should not be redundant ✅ 💡
no-redundant-optional Optional property declarations should not use both '?' and 'undefined' syntax ✅ 💡 💭
no-redundant-parentheses Redundant pairs of parentheses should be removed 💡 ❌
no-reference-error Variables should be defined before being used
no-referrer-policy HTTP Referrer-Policy should not be set to an unsafe value ✅
no-regex-spaces Regular expressions should not contain multiple spaces ✅ 💡 💭
no-require-or-define "import" should be used to include external code 💭
no-return-type-any Primitive return types should be used 💭
no-same-argument-assert Assertions should not be given twice the same argument ✅
no-same-line-conditional Conditionals should start on new lines ✅ 💡
no-selector-parameter Methods should not contain selector parameters ✅ 💭
no-session-cookies-on-static-assets Static Assets should not serve session cookies ✅
no-skipped-tests Tests should not be skipped without providing a reason ✅
no-small-switch "if" statements should be preferred over "switch" when simpler ✅ 💭
no-sonar-comments Track uses of "NOSONAR" comments
no-tab Tabulation characters should not be used ❌
no-table-as-layout HTML "<table>" should not be used for layout purposes ✅
no-trivial-assertions Assertions should not be trivially true ✅ 💡
no-try-promise Promise rejections should not be caught by "try" blocks ✅ 💭
no-undefined-argument "undefined" should not be passed as the value of optional parameters ✅ 💡 💭
no-undefined-assignment "undefined" should not be assigned
no-unenclosed-multiline-block Multiline blocks should be enclosed in curly braces ✅
no-uniq-key JSX list components keys should match up between renders ✅
no-unsafe-unzip Expanding archive files should not be done without controlling resource consumption ❌
no-unthrown-error Errors should not be created without being thrown ✅ 💡
no-unused-collection Collecti

Current Tags

  • 0.5.0-internal                                ...           internal (7 years ago)
  • 4.2.2                                ...           latest (2 months ago)
  • 2.0.0-alpha.0                                ...           next (2 years ago)

67 Versions

  • 4.2.2                                ...           2 months ago
  • 4.2.1                                ...           2 months ago
  • 4.2.0                                ...           4 months ago
  • 4.1.0                                ...           5 months ago
  • 4.0.3                                ...           7 months ago
  • 4.0.2                                ...           9 months ago
  • 4.0.1                                ...           9 months ago
  • 4.0.0                                ...           9 months ago
  • 3.0.7                                ...           10 months ago
  • 3.0.6                                ...           10 months ago
  • 3.0.5                                ...           a year ago
  • 3.0.4                                ...           a year ago
  • 3.0.3                                ...           a year ago
  • 3.0.2                                ...           2 years ago
  • 3.0.1                                ...           2 years ago
  • 3.0.0                                ...           2 years ago
  • 2.0.4                                ...           2 years ago
  • 2.0.3                                ...           2 years ago
  • 2.0.2                                ...           2 years ago
  • 2.0.1                                ...           2 years ago
  • 2.0.1-alpha.2                                ...           2 years ago
  • 2.0.1-alpha.1                                ...           2 years ago
  • 2.0.1-alpha.0                                ...           2 years ago
  • 2.0.0                                ...           2 years ago
  • 2.0.0-alpha.0                                ...           2 years ago
  • 1.0.4                                ...           2 years ago
  • 1.0.4-alpha.2                                ...           2 years ago
  • 1.0.4-alpha.1                                ...           2 years ago
  • 1.0.4-alpha.0                                ...           2 years ago
  • 1.0.3                                ...           3 years ago
  • 1.0.2                                ...           3 years ago
  • 1.0.0                                ...           3 years ago
  • 0.25.1                                ...           3 years ago
  • 0.25.0                                ...           3 years ago
  • 0.24.0                                ...           3 years ago
  • 0.23.0                                ...           3 years ago
  • 0.22.0                                ...           3 years ago
  • 0.21.0                                ...           3 years ago
  • 0.20.0                                ...           3 years ago
  • 0.19.0                                ...           4 years ago
  • 0.18.0                                ...           4 years ago
  • 0.17.0                                ...           4 years ago
  • 0.16.0                                ...           4 years ago
  • 0.15.0                                ...           4 years ago
  • 0.14.0                                ...           4 years ago
  • 0.13.0                                ...           5 years ago
  • 0.12.0                                ...           5 years ago
  • 0.11.0                                ...           5 years ago
  • 0.10.0                                ...           5 years ago
  • 0.9.1                                ...           5 years ago
  • 0.9.0                                ...           5 years ago
  • 0.8.0-125                                ...           5 years ago
  • 0.7.1-117                                ...           5 years ago
  • 0.7.1-116                                ...           5 years ago
  • 0.7.0                                ...           6 years ago
  • 0.6.0                                ...           6 years ago
  • 0.5.0                                ...           7 years ago
  • 0.5.0-internal                                ...           7 years ago
  • 0.4.0                                ...           7 years ago
  • 0.3.0                                ...           8 years ago
  • 0.3.0-2                                ...           8 years ago
  • 0.3.0-1                                ...           8 years ago
  • 0.3.0-0                                ...           8 years ago
  • 0.2.0                                ...           8 years ago
  • 0.1.1                                ...           8 years ago
  • 0.1.0                                ...           9 years ago
  • 0.1.0-0                                ...           9 years ago
Downloads
Total 68
Today 0
This Week 1
This Month 68
Last Day 0
Last Week 33
Last Month 0
Dependencies (9)
Dev Dependencies (0)
None
Dependents (1)

© 2010 - cnpmjs.org x YWFE | Home | YWFE