Files

359 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* ESLint конфигурация для backend (TypeScript, Node.js, ES Modules).
* strictTypeChecked + sonarjs + import-x + eslint-comments.
*/
import js from '@eslint/js';
import comments from '@eslint-community/eslint-plugin-eslint-comments';
import importX from 'eslint-plugin-import-x';
import sonarjs from 'eslint-plugin-sonarjs';
import globals from 'globals';
import { defineConfig, globalIgnores } from 'eslint/config';
import tseslint from 'typescript-eslint';
const CONFIG_ROOT = import.meta.dirname;
const TEST_FILES = ['**/*.{test,spec}.ts', 'tests/**/*.{ts,mts,cts}'];
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/eslint.config.*', '**/vite.config.*'];
export default defineConfig(
/* ── Глобальные игноры ─────────────────────────────────────── */
globalIgnores([
'**/node_modules/**',
'**/dist/**',
'**/build/**',
'**/coverage/**',
'**/uploads/**',
'**/*.min.js',
]),
/* ── Политика линтера ─────────────────────────────────────── */
{
name: 'server/linter-policy',
linterOptions: {
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
// Единственный способ отключить правило — file-level override в этом конфиге.
noInlineConfig: true,
reportUnusedDisableDirectives: 'error',
reportUnusedInlineConfigs: 'error',
},
},
/* ── TypeScript — strict mode ──────────────────────────────── */
...tseslint.configs.strictTypeChecked,
/* ── Импорты (import-x) ────────────────────────────────────── */
importX.flatConfigs.recommended,
importX.flatConfigs.typescript,
/* ── SonarJS ───────────────────────────────────────────────── */
sonarjs.configs.recommended,
/* ── Правила сервера ───────────────────────────────────────── */
{
name: 'server/rules',
files: ['**/*.ts'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: globals.node,
parserOptions: {
projectService: {
allowDefaultProject: ['*.config.ts'],
},
tsconfigRootDir: CONFIG_ROOT,
},
},
settings: {
'import-x/resolver': {
typescript: { alwaysTryTypes: true },
node: true,
},
},
plugins: {
'@eslint-community/eslint-comments': comments,
},
rules: {
...js.configs.recommended.rules,
/* Отключаем базовые правила, которые заменяет TS */
'no-redeclare': 'off',
'no-unused-vars': 'off',
'no-use-before-define': 'off',
'no-shadow': 'off',
'no-throw-literal': 'off',
'consistent-return': 'off',
'prefer-promise-reject-errors': 'off',
'require-await': 'off',
/* Корректность */
'array-callback-return': ['error', { allowImplicit: false, checkForEach: true }],
curly: ['error', 'all'],
eqeqeq: ['error', 'always', { null: 'ignore' }],
'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }],
'no-console': ['error', { allow: ['error', 'warn'] }],
'no-debugger': 'error',
'no-eval': 'error',
'no-alert': 'error',
'no-else-return': ['error', { allowElseIf: false }],
'no-extend-native': 'error',
'no-implicit-coercion': 'error',
'no-lone-blocks': 'error',
'no-nested-ternary': 'error',
'no-param-reassign': ['error', { props: true }],
'no-promise-executor-return': 'error',
'no-return-assign': ['error', 'always'],
'no-self-compare': 'error',
'no-sequences': 'error',
'no-unneeded-ternary': 'error',
'no-useless-concat': 'error',
'no-useless-return': 'error',
'object-shorthand': ['error', 'always'],
'prefer-const': 'error',
'prefer-object-spread': 'error',
'require-atomic-updates': 'error',
/* TS — типы */
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-check': false,
'ts-expect-error': 'allow-with-description',
'ts-ignore': true,
'ts-nocheck': true,
minimumDescriptionLength: 20,
},
],
'@typescript-eslint/consistent-type-assertions': ['error', { assertionStyle: 'never' }],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': ['error', { checkLiteralConstAssertions: true }],
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unsafe-type-assertion': 'error',
/* TS — контракты */
'@typescript-eslint/consistent-return': 'error',
'@typescript-eslint/consistent-type-exports': 'error',
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports', fixStyle: 'separate-type-imports' },
],
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/no-misused-promises': [
'error',
{
checksConditionals: true,
checksSpreads: true,
checksVoidReturn: {
arguments: true,
properties: true,
returns: true,
variables: true,
},
},
],
'@typescript-eslint/no-unnecessary-condition': [
'error',
{ allowConstantLoopConditions: 'only-allowed-literals' },
],
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
'@typescript-eslint/only-throw-error': 'error',
'@typescript-eslint/prefer-nullish-coalescing': [
'error',
{
ignoreBooleanCoercion: false,
ignoreConditionalTests: false,
ignorePrimitives: { bigint: false, boolean: false, number: false, string: false },
ignoreTernaryTests: false,
},
],
'@typescript-eslint/prefer-optional-chain': [
'error',
{
allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: false,
checkAny: true,
checkBigInt: true,
checkBoolean: true,
checkNumber: true,
checkString: true,
requireNullish: true,
},
],
'@typescript-eslint/require-await': 'error',
'@typescript-eslint/return-await': ['error', 'error-handling-correctness-only'],
'@typescript-eslint/strict-boolean-expressions': 'error',
'@typescript-eslint/promise-function-async': 'error',
'@typescript-eslint/no-floating-promises': ['error', { ignoreIIFE: false, ignoreVoid: false }],
'@typescript-eslint/no-shadow': 'error',
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
'@typescript-eslint/switch-exhaustiveness-check': [
'error',
{
allowDefaultCaseForExhaustiveSwitch: false,
considerDefaultExhaustiveForUnions: false,
requireDefaultForNonUnion: true,
},
],
/* Сложность */
complexity: ['error', 10],
'max-classes-per-file': ['error', 1],
'max-depth': ['error', 3],
'max-lines': ['error', { max: 400, skipBlankLines: true, skipComments: true }],
'max-lines-per-function': ['error', { IIFEs: true, max: 80, skipBlankLines: true, skipComments: true }],
'max-nested-callbacks': ['error', 3],
'max-params': ['error', 4],
'max-statements': ['error', 25],
'sonarjs/cognitive-complexity': ['error', 10],
'sonarjs/no-duplicate-string': 'error',
/* Импорты */
'import-x/first': 'error',
'import-x/newline-after-import': 'error',
'import-x/no-absolute-path': 'error',
'import-x/no-cycle': ['warn', { ignoreExternal: true, maxDepth: 5 }],
'import-x/no-duplicates': 'error',
'import-x/no-extraneous-dependencies': [
'error',
{ devDependencies: false, optionalDependencies: false, peerDependencies: false },
],
'import-x/no-named-as-default': 'error',
'import-x/no-named-as-default-member': 'error',
'import-x/no-self-import': 'error',
'import-x/no-useless-path-segments': 'error',
'import-x/order': ['error', {
alphabetize: { caseInsensitive: true, order: 'asc' },
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'type'],
'newlines-between': 'always',
}],
},
},
/* ── Конфигурационные файлы ────────────────────────────────── */
{
name: 'server/config-files',
files: CONFIG_AND_SCRIPT_FILES,
rules: {
'no-console': ['error', { allow: ['error', 'warn'] }],
'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }],
},
},
/* ── Тестовые файлы ────────────────────────────────────────── */
{
name: 'server/tests',
files: TEST_FILES,
rules: {
'max-lines': ['error', { max: 700, skipBlankLines: true, skipComments: true }],
'max-lines-per-function': 'off',
'max-statements': 'off',
'sonarjs/cognitive-complexity': 'off',
'sonarjs/no-duplicate-string': 'off',
'sonarjs/no-hardcoded-passwords': 'off',
'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }],
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
// Тесты извлекают поля из unknown-ответов (supertest body)
'@typescript-eslint/consistent-type-assertions': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
},
},
/* ── Файловые исключения (единственный способ отключить правило) ── */
{
name: 'server/express-assertions',
files: [
'src/routes/news.routes.ts',
'src/routes/auth.routes.ts',
'src/routes/upload.routes.ts',
'src/routes/notification.routes.ts',
'src/middleware/auth.middleware.ts',
],
rules: {
// Express req расширяется middleware — assertion неизбежен
'@typescript-eslint/consistent-type-assertions': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off',
},
},
{
name: 'server/auth-middleware',
files: ['src/middleware/auth.middleware.ts'],
rules: {
// req.user устанавливается auth middleware (стандартный паттерн Express)
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['req'] }],
},
},
{
name: 'server/error-middleware',
files: ['src/middleware/error.middleware.ts'],
rules: {
// Сигнатура ErrorRequestHandler требует 4 аргумента
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
},
{
name: 'server/jwt',
files: ['src/utils/jwt.ts'],
rules: {
// env.jwtExpiresIn — string, а SignOptions.expiresIn ожидает StringValue из пакета ms;
// double-assertion — стандартная практика для env-значений
'@typescript-eslint/consistent-type-assertions': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off',
},
},
{
name: 'server/import-default-exports',
files: ['src/app.ts', 'src/middleware/upload.middleware.ts', 'src/utils/jwt.ts'],
rules: {
// express.static, jwt.sign/verify, multer.diskStorage — default export API
'import-x/no-named-as-default-member': 'off',
},
},
{
name: 'server/auth-mongoose',
files: ['src/routes/auth.routes.ts'],
rules: {
// Mongoose документ (без IUser-интерфейса) — no-unsafe срабатывает
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
// Email-regex на ограниченном input (после trim)
'sonarjs/slow-regex': 'off',
},
},
{
name: 'server/upload-routes',
files: ['src/routes/upload.routes.ts'],
rules: {
// asyncHandler требует async-обёртку
'@typescript-eslint/require-await': 'off',
},
},
{
name: 'server/scheduler',
files: ['src/services/publicationScheduler.service.ts'],
rules: {
// Логирование факта публикации в production
'no-console': ['error', { allow: ['error', 'warn', 'log'] }],
},
},
{
name: 'server/socket',
files: ['src/socket/socketServer.ts'],
rules: {
// socket.userId — стандартный паттерн Socket.IO (socket.data)
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['socket'] }],
// socket.join — fire-and-forget (void)
'@typescript-eslint/no-floating-promises': 'off',
},
},
);