@cbrl/eslint-config 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kayron Cabral
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @cbrl/eslint-config
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Strict ESLint flat config for TypeScript, React and Next.js. Type-aware rules,
4
+ accessibility, test quality, architectural layering, and custom `cbrl/*` rules
5
+ that enforce fail-fast code.
6
+
7
+ ```sh
8
+ pnpm add -D @cbrl/eslint-config eslint typescript
9
+ ```
10
+
11
+ ```js
12
+ // eslint.config.mjs
13
+ import baseConfig from '@cbrl/eslint-config'
14
+
15
+ export default [...baseConfig]
16
+ ```
17
+
18
+ ## Layers
19
+
20
+ The default export composes these layers, also available as named exports:
21
+
22
+ | Export | What it does |
23
+ | ------------- | -------------------------------------------------------------------------------------------------- |
24
+ | `ignores` | Build output, coverage, generated files |
25
+ | `javascript` | `@eslint/js` recommended, sonarjs, `cbrl/*` rules, `noInlineConfig` |
26
+ | `typescript` | `typescript-eslint` type-aware (`no-unsafe-*`, `no-floating-promises`, `no-unsafe-type-assertion`) |
27
+ | `moduleSize` | Caps on file and function size |
28
+ | `layering` | `features/*/{ui,adapters,core}`: core stays pure, imports only point down |
29
+ | `testQuality` | Testing Library + Playwright rules; no `data-testid`, no hand-rolled UI primitives |
30
+ | `next` | Next.js-specific exceptions (no-op elsewhere) |
31
+
32
+ ```js
33
+ import { ignores, javascript, typescript } from '@cbrl/eslint-config'
34
+
35
+ export default [...ignores, ...javascript, ...typescript]
36
+ ```
37
+
38
+ ## Custom rules
39
+
40
+ | Rule | Default | Enforces |
41
+ | ---------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
42
+ | `cbrl/no-eslint-disable` | error | No `eslint-disable*` comments. `noInlineConfig` backs it up so it cannot be silenced inline |
43
+ | `cbrl/no-env-value-fallback` | error | No literal fallback on `process.env.X` (`?? 'x'`, `\|\| 'x'`); read it with `@cbrl/env` |
44
+ | `cbrl/no-conditional-spread-chain` | error | No conditional spread nested in another conditional spread |
45
+ | `cbrl/no-non-doc-comments` | off | Only machine pragmas and attached TSDoc with a tag survive (autofix removes the rest). Opt in: `rules: { 'cbrl/no-non-doc-comments': 'error' }` |
46
+
47
+ Each rule documents its rationale in the header of `rules/<name>.mjs`. The plugin
48
+ is exported from `@cbrl/eslint-config/plugin` and file globs from
49
+ `@cbrl/eslint-config/globs`.
@@ -0,0 +1,7 @@
1
+ // Layer: global ignores. Must stay a standalone config object (no `files`)
2
+ // so ESLint treats it as global — applies before every other layer.
3
+
4
+ import { GLOB_IGNORES } from '../globs.mjs'
5
+
6
+ /** @type {import('eslint').Linter.Config[]} */
7
+ export const ignores = [{ ignores: GLOB_IGNORES }]
@@ -0,0 +1,73 @@
1
+ // Layer: JavaScript baseline — ESLint recommended, runtime globals, and the
2
+ // language-agnostic maintainability gates. TS-only rules live in `typescript.mjs`.
3
+
4
+ import js from '@eslint/js'
5
+ import sonarjs from 'eslint-plugin-sonarjs'
6
+ import globals from 'globals'
7
+
8
+ import { GLOB_ALL, GLOB_SERVICE_WORKER } from '../globs.mjs'
9
+ import { cbrlPlugin } from '../plugin.mjs'
10
+
11
+ /** @type {import('eslint').Linter.Config[]} */
12
+ export const javascript = [
13
+ js.configs.recommended,
14
+ {
15
+ // Backstop for `cbrl/no-eslint-disable`: neutralizes every `eslint-disable*` / inline
16
+ // `/* eslint */` comment (the suppressed rule fires anyway), so the
17
+ // `cbrl/no-eslint-disable` error below can't itself be silenced inline.
18
+ linterOptions: { noInlineConfig: true },
19
+ },
20
+ {
21
+ files: [GLOB_ALL],
22
+ languageOptions: {
23
+ globals: { ...globals.browser, ...globals.node },
24
+ },
25
+ },
26
+ {
27
+ // Public service workers run in a separate global scope. Without this
28
+ // override `self` collides with the default `globals.browser` declaration
29
+ // and triggers `no-redeclare`.
30
+ files: GLOB_SERVICE_WORKER,
31
+ languageOptions: {
32
+ globals: { ...globals.serviceworker },
33
+ },
34
+ },
35
+ {
36
+ files: [GLOB_ALL],
37
+ plugins: { cbrl: cbrlPlugin, sonarjs },
38
+ rules: {
39
+ 'cbrl/no-conditional-spread-chain': 'error',
40
+ 'cbrl/no-env-value-fallback': 'error',
41
+ 'cbrl/no-eslint-disable': 'error',
42
+ // Maintainability gates (high-signal, error). Existing violations are
43
+ // grandfathered via the native ESLint bulk-suppressions file
44
+ // (`eslint-suppressions.json`) and pruned as they're fixed — new code
45
+ // must comply.
46
+ //
47
+ // Cognitive complexity (SonarJS — the SonarQube metric) is the gate: it
48
+ // weights how hard code is to *understand*, not just branch count. We
49
+ // deliberately do NOT gate cyclomatic `complexity` (flags readable flat
50
+ // switches), `max-nested-callbacks` (flags legit describe/it test nesting)
51
+ // or raw lines-per-function (formatting noise, gameable) — high bar on the
52
+ // metric that signals, not on the noisy ones.
53
+ 'sonarjs/cognitive-complexity': ['error', 15],
54
+ 'max-depth': ['error', 4],
55
+ 'max-params': ['error', 4],
56
+ // Native ESLint rule paired with `cbrl/no-conditional-spread-chain`.
57
+ // Catches the *direct* nested-ternary form (`a ? b ? x : y : z`) that the
58
+ // custom rule doesn't target (the custom rule targets the spread nesting
59
+ // form). Together they close both faces of "ternary legibility" the team
60
+ // has flagged.
61
+ 'no-nested-ternary': 'error',
62
+ // Keep the rule enforced (catches the real bug, `const {} = x`) but allow
63
+ // an empty object pattern as a *parameter* — the canonical Playwright
64
+ // no-dependency fixture signature `async ({}, use) => …`. Avoids a blanket
65
+ // `no-empty-pattern: off` exception for e2e dirs.
66
+ 'no-empty-pattern': ['error', { allowObjectPatternsAsParameters: true }],
67
+ 'sonarjs/no-commented-code': 'error',
68
+ 'no-inline-comments': 'error',
69
+ 'line-comment-position': ['error', 'above'],
70
+ 'no-warning-comments': ['error', { terms: ['hack'], location: 'anywhere' }],
71
+ },
72
+ },
73
+ ]
@@ -0,0 +1,202 @@
1
+ // Layer: architectural layering gate — turns the feature-slice ring model into
2
+ // a machine-checked dependency graph instead of a prose convention. Two walls:
3
+ //
4
+ // 1. PURITY — `features/*/core/**` is the functional core: pure rules, view
5
+ // models, parsing. It MUST NOT reach for React, Next, Firestore, or any
6
+ // I/O. The whole point is that core is unit-testable with zero harness, so
7
+ // coverage + mutation have teeth. Enforced with stock `no-restricted-imports`
8
+ // (zero false positives — purity is literally "doesn't import these").
9
+ //
10
+ // 2. DIRECTION — dependencies only ever point DOWN the ring stack:
11
+ // ui → adapters → core
12
+ // A component may call an adapter; an adapter may call core; never the
13
+ // reverse. core importing an adapter (or ui) is the classic leak that makes
14
+ // the "pure" core impure by transitivity. Enforced with eslint-plugin-
15
+ // boundaries' element-types graph.
16
+ //
17
+ // Scoped entirely to the `features/<slice>/<ring>/` convention — an app that
18
+ // hasn't adopted feature slices has no matching files, so this layer is a no-op
19
+ // there. Adopt the folders, get the wall; nothing to opt into per-app.
20
+ //
21
+ // External packages (`@acme/shared`, `@cbrl/design`, …) are deliberately
22
+ // unclassified: `default: 'allow'` means only the upward-import rules below bite.
23
+ // A pure-domain shared package can be imported from core.
24
+
25
+ import boundaries from 'eslint-plugin-boundaries'
26
+ import { GLOB_SRC } from '../globs.mjs'
27
+
28
+ const CORE_FILES = ['**/features/*/core/**/*.{ts,tsx}']
29
+
30
+ /** @type {import('eslint').Linter.Config[]} */
31
+ export const layering = [
32
+ // ── Wall 1: core purity ────────────────────────────────────────────────
33
+ {
34
+ files: CORE_FILES,
35
+ rules: {
36
+ 'no-restricted-imports': [
37
+ 'error',
38
+ {
39
+ patterns: [
40
+ {
41
+ group: ['react', 'react-dom', 'next', 'next/*'],
42
+ message:
43
+ 'core/ é o functional core: sem React/Next. Estado, efeito ou render vivem em ui/ ou adapters/.',
44
+ },
45
+ {
46
+ group: [
47
+ 'firebase',
48
+ 'firebase/*',
49
+ 'firebase-admin',
50
+ 'firebase-admin/*',
51
+ '@/shared/db',
52
+ '@/shared/db/*',
53
+ 'server-only',
54
+ ],
55
+ message:
56
+ 'core/ é puro: sem Firestore/admin/server-only. Acesso a dado mora em adapters/ (ex.: *.repo.ts).',
57
+ },
58
+ {
59
+ group: ['**/adapters/*', '**/ui/*', '@/features/*/adapters/*', '@/features/*/ui/*'],
60
+ message:
61
+ 'Dependência só desce (ui→adapters→core). core/ não pode importar adapters/ nem ui/.',
62
+ },
63
+ {
64
+ group: ['@/app/*', '@/app/**'],
65
+ message:
66
+ 'features/ não importa app/ — app é a casca externa de roteamento (inversão).',
67
+ },
68
+ ],
69
+ },
70
+ ],
71
+ },
72
+ },
73
+ // ── Wall 1b: domain kernel purity ──────────────────────────────────────
74
+ // `domain/` is the innermost ring (ES aggregates, read-model schemas, pure
75
+ // rules). It depends on NOTHING above it — no framework, no I/O, no app infra
76
+ // (`shared/`), no features. Keeps the kernel mutation-testable + reusable.
77
+ {
78
+ files: ['**/domain/**/*.{ts,tsx}'],
79
+ rules: {
80
+ 'no-restricted-imports': [
81
+ 'error',
82
+ {
83
+ patterns: [
84
+ {
85
+ group: ['react', 'react-dom', 'next', 'next/*'],
86
+ message: 'domain/ é o kernel puro: sem React/Next.',
87
+ },
88
+ {
89
+ group: [
90
+ 'firebase',
91
+ 'firebase/*',
92
+ 'firebase-admin',
93
+ 'firebase-admin/*',
94
+ '@/shared/db',
95
+ '@/shared/db/*',
96
+ 'server-only',
97
+ ],
98
+ message: 'domain/ é puro: sem Firestore/admin/server-only.',
99
+ },
100
+ {
101
+ group: ['@/shared/*', '@/features/*', '@/app/*'],
102
+ message: 'domain/ é o anel mais interno — não importa shared/, features/ nem app/.',
103
+ },
104
+ ],
105
+ },
106
+ ],
107
+ },
108
+ },
109
+ // ── Wall 1c: no layer inversion ────────────────────────────────────────
110
+ // Dependencies point inward only: app → features → shared → domain. These
111
+ // catch the upward (inverted) imports the per-ring walls above don't:
112
+ // • features (adapters/ui) → app (app is the outer routing shell)
113
+ // • shared → features / app (shared is below features)
114
+ // • components → app (shared visual is below routing)
115
+ // Scopes are disjoint from the core/domain walls above (no rule-merge clash).
116
+ {
117
+ files: ['**/features/*/adapters/**/*.{ts,tsx}', '**/features/*/ui/**/*.{ts,tsx}'],
118
+ rules: {
119
+ 'no-restricted-imports': [
120
+ 'error',
121
+ {
122
+ patterns: [
123
+ {
124
+ group: ['@/app/*', '@/app/**'],
125
+ message:
126
+ 'features/ não importa app/ — app é a casca externa de roteamento (inversão).',
127
+ },
128
+ ],
129
+ },
130
+ ],
131
+ },
132
+ },
133
+ {
134
+ files: ['**/shared/**/*.{ts,tsx}'],
135
+ rules: {
136
+ 'no-restricted-imports': [
137
+ 'error',
138
+ {
139
+ patterns: [
140
+ {
141
+ group: ['@/features/*', '@/features/**', '@/app/*', '@/app/**'],
142
+ message:
143
+ 'shared/ é infra abaixo de features/ — não importa features/ nem app/ (inversão de camada).',
144
+ },
145
+ ],
146
+ },
147
+ ],
148
+ },
149
+ },
150
+ {
151
+ files: ['**/components/**/*.{ts,tsx}'],
152
+ rules: {
153
+ 'no-restricted-imports': [
154
+ 'error',
155
+ {
156
+ patterns: [
157
+ {
158
+ group: ['@/app/*', '@/app/**'],
159
+ message:
160
+ 'components/ é visual compartilhado — não importa app/ (inversão de camada).',
161
+ },
162
+ ],
163
+ },
164
+ ],
165
+ },
166
+ },
167
+ // ── Wall 2: ring direction ─────────────────────────────────────────────
168
+ {
169
+ files: [GLOB_SRC],
170
+ plugins: { boundaries },
171
+ settings: {
172
+ 'boundaries/include': ['**/features/**'],
173
+ 'boundaries/elements': [
174
+ { type: 'feat-core', pattern: 'features/*/core/**', mode: 'full' },
175
+ { type: 'feat-adapters', pattern: 'features/*/adapters/**', mode: 'full' },
176
+ { type: 'feat-ui', pattern: 'features/*/ui/**', mode: 'full' },
177
+ ],
178
+ },
179
+ rules: {
180
+ 'boundaries/element-types': [
181
+ 'error',
182
+ {
183
+ default: 'allow',
184
+ rules: [
185
+ {
186
+ from: ['feat-core'],
187
+ disallow: ['feat-adapters', 'feat-ui'],
188
+ message:
189
+ 'core ({{from}}) não importa {{target}} — dependência só desce (ui→adapters→core).',
190
+ },
191
+ {
192
+ from: ['feat-adapters'],
193
+ disallow: ['feat-ui'],
194
+ message:
195
+ 'adapters ({{from}}) não importa ui — o fluxo é ui→adapters, nunca o contrário.',
196
+ },
197
+ ],
198
+ },
199
+ ],
200
+ },
201
+ },
202
+ ]
@@ -0,0 +1,27 @@
1
+ // Layer: module-size gate — Uncle Bob's "module sizes". Caps a source module
2
+ // so god-files get flagged structurally (a 900-line module hides too much).
3
+ // Counts CODE lines only (blanks + comments skipped) so it tracks real size,
4
+ // not formatting/docs. Scoped to `src/**` source: test/spec/e2e/smoke files are
5
+ // exempt (large fixtures/table-driven specs are legitimate), as are configs
6
+ // (outside src). Existing violations are grandfathered via the bulk-suppressions
7
+ // file and pruned as files are split. This is the FILE metric only — we still
8
+ // deliberately do NOT gate lines-per-function (gameable, formatting noise; see
9
+ // the maintainability block in `javascript.mjs`).
10
+ //
11
+ // Cap = 500 code-lines: generous enough that cohesive modules (a fixture, a saga
12
+ // shell) aren't forced into artificial splits, strict enough that a god-file is
13
+ // still flagged. No clean file sits in the 400-500 band, so the bar is real (not
14
+ // a loophole). Recalibrado 400→500 em 2026-06-09.
15
+
16
+ import { GLOB_SRC, GLOB_TESTS } from '../globs.mjs'
17
+
18
+ /** @type {import('eslint').Linter.Config[]} */
19
+ export const moduleSize = [
20
+ {
21
+ files: [GLOB_SRC],
22
+ ignores: GLOB_TESTS,
23
+ rules: {
24
+ 'max-lines': ['error', { max: 500, skipBlankLines: true, skipComments: true }],
25
+ },
26
+ },
27
+ ]
@@ -0,0 +1,24 @@
1
+ // Next.js framework adjustments shared by every Next app on this base.
2
+ //
3
+ // Statically-typed routes (`typedRoutes`) brand `Route`. A route built from a
4
+ // dynamic string can't be statically inferred AND has no runtime shape to
5
+ // validate against (any string is a syntactically valid path), so `as Route` is
6
+ // irreducible — it is Next's own documented pattern. The convention is to confine
7
+ // it to a single `toRoute` seam at `src/shared/routes.ts`; this turns off the two
8
+ // assertion rules for THAT FILE ONLY (every other file stays strict).
9
+ //
10
+ // Both rules are disabled because the cast reads differently depending on whether
11
+ // `.next/types` has been generated when ESLint runs:
12
+ // - with generated route types → `Route` is branded → `no-unsafe-type-assertion`
13
+ // - without them (bare `eslint`) → `Route` ≈ `string` → `no-unnecessary-type-assertion`
14
+ // Disabling both keeps the seam green in both modes (CI runs `next typegen` first
15
+ // via the package `lint` script; a bare `eslint .` does not).
16
+ export const next = [
17
+ {
18
+ files: ['**/src/shared/routes.ts'],
19
+ rules: {
20
+ '@typescript-eslint/no-unsafe-type-assertion': 'off',
21
+ '@typescript-eslint/no-unnecessary-type-assertion': 'off',
22
+ },
23
+ },
24
+ ]
@@ -0,0 +1,93 @@
1
+ // Layer: test-quality & ownership gates (paved road). See CONTRIBUTING.md
2
+ // §"Princípios de engenharia". Prefer the canonical community plugin over a
3
+ // custom rule; a built-in `no-restricted-*` is used ONLY where no plugin rule
4
+ // exists (the data-testid and raw-primitive bans). Existing violations are
5
+ // grandfathered via the native bulk-suppressions file and pruned over time —
6
+ // new code must comply.
7
+
8
+ import jsxA11y from 'eslint-plugin-jsx-a11y'
9
+ import playwright from 'eslint-plugin-playwright'
10
+ import testingLibrary from 'eslint-plugin-testing-library'
11
+
12
+ import { GLOB_APPS, GLOB_E2E_SPECS, GLOB_TEST_FILES, GLOB_TS, GLOB_TSX } from '../globs.mjs'
13
+
14
+ // `data-testid` is banned everywhere: tests must target accessible
15
+ // roles/labels/text (reachable via the jsx-a11y layer). A test that can only be
16
+ // written against a testid signals inaccessible markup — fix the markup, not the
17
+ // test. No community rule bans the attribute at the source, so this is the
18
+ // built-in no-restricted-syntax (not a custom cbrl/* rule).
19
+ const NO_DATA_TESTID = {
20
+ selector: "JSXAttribute[name.name='data-testid']",
21
+ message:
22
+ 'Do not use data-testid. Make the element queryable by role/label/text (see jsx-a11y) so tests target accessible semantics, not test hooks.',
23
+ }
24
+
25
+ // Apps must not hand-roll UI primitives the design system owns.
26
+ const NO_RAW_PRIMITIVE = {
27
+ selector: 'JSXOpeningElement[name.name=/^(button|input|textarea|select)$/]',
28
+ message:
29
+ 'Do not hand-roll UI primitives in an app. Import Button/Input/Textarea/Select from @cbrl/design — the design system owns primitives so they are built and tested in one place.',
30
+ }
31
+
32
+ // The playwright recommended set ships several rules as `warn`; force every one
33
+ // to `error` — an advisory that never blocks is documentation in disguise. A
34
+ // flaky-test smell must fail loud and be fixed now, not accumulate.
35
+ const playwrightErrors = Object.fromEntries(
36
+ Object.entries(playwright.configs['flat/recommended'].rules).map(([rule, level]) => [
37
+ rule,
38
+ level === 'warn' || level === 1 ? 'error' : level,
39
+ ]),
40
+ )
41
+
42
+ /** @type {import('eslint').Linter.Config[]} */
43
+ export const testQuality = [
44
+ // Accessibility — jsx-a11y. Beyond the a11y win, `htmlFor`/role pairing is
45
+ // what lets Playwright/Testing-Library query by role+label instead of brittle
46
+ // selectors. The upstream half of "no data-testid".
47
+ { ...jsxA11y.flatConfigs.recommended, files: [GLOB_TSX] },
48
+
49
+ // Testing Library — query best practices (prefer getByRole, no direct
50
+ // container.querySelector, await async queries). Component/unit tests only.
51
+ { ...testingLibrary.configs['flat/react'], files: [GLOB_TEST_FILES] },
52
+
53
+ // Playwright — web-first assertions, no arbitrary waitForTimeout/networkidle,
54
+ // no ElementHandle. Scoped to the e2e specs.
55
+ {
56
+ ...playwright.configs['flat/recommended'],
57
+ files: GLOB_E2E_SPECS,
58
+ rules: {
59
+ ...playwrightErrors,
60
+ // Teach expect-expect about our custom assertion helpers so a test that
61
+ // asserts *through* a helper isn't flagged as assertion-less.
62
+ 'playwright/expect-expect': ['error', { assertFunctionNames: ['assertOk', 'assertNoCrash'] }],
63
+ },
64
+ },
65
+
66
+ // `data-testid` banned everywhere.
67
+ {
68
+ files: [GLOB_TS],
69
+ rules: { 'no-restricted-syntax': ['error', NO_DATA_TESTID] },
70
+ },
71
+
72
+ // Test-ownership / no-duplication gate. Apps must not re-implement design
73
+ // primitives nor reach for Radix directly — that path belongs to @cbrl/design.
74
+ // Keeps app code about business rules and primitives built/tested in one place.
75
+ {
76
+ files: [GLOB_APPS],
77
+ rules: {
78
+ 'no-restricted-syntax': ['error', NO_DATA_TESTID, NO_RAW_PRIMITIVE],
79
+ 'no-restricted-imports': [
80
+ 'error',
81
+ {
82
+ patterns: [
83
+ {
84
+ group: ['radix-ui', '@radix-ui/*'],
85
+ message:
86
+ 'Radix belongs to @cbrl/design. Apps consume design components, not Radix directly — promote the primitive to @cbrl/design instead.',
87
+ },
88
+ ],
89
+ },
90
+ ],
91
+ },
92
+ },
93
+ ]
@@ -0,0 +1,68 @@
1
+ // Layer: TypeScript — typescript-eslint *type-checked* preset plus the
2
+ // project's type-safety rules.
3
+ //
4
+ // This layer turns on TYPED LINTING: `projectService: true` makes the parser
5
+ // build a TS program per file, which unlocks the `no-unsafe-*` family,
6
+ // `no-floating-promises`, `no-misused-promises`, and `no-unsafe-type-assertion`
7
+ // (the type-aware replacement for the old `cbrl/no-ts-escape-hatches` custom
8
+ // rule — it sees `as any`, `as unknown as X` AND any cast that widens safety).
9
+ //
10
+ // Type-aware rules only make sense on real source files that belong to a
11
+ // tsconfig. Plain `.js/.mjs/.cjs` (configs, scripts) get `disableTypeChecked`
12
+ // so the parser doesn't try to find a program for them.
13
+ //
14
+ // gabar is NOT special-cased here: a `**/gabar/**` glob can't work, because
15
+ // each workspace lints with cwd = its own dir (`eslint .`), so paths are
16
+ // relative to that dir and never contain `gabar`. gabar's pre-migration debt
17
+ // is grandfathered the same way every other app's is — via a per-app
18
+ // `eslint-suppressions.json` snapshot — which also gives it the same ratchet
19
+ // (new violations fail) instead of a silently-ignored warn tier.
20
+
21
+ import tseslint from 'typescript-eslint'
22
+
23
+ import { GLOB_TS } from '../globs.mjs'
24
+ import { cbrlPlugin } from '../plugin.mjs'
25
+
26
+ /** @type {import('eslint').Linter.Config[]} */
27
+ export const typescript = [
28
+ ...tseslint.configs.recommendedTypeChecked,
29
+ {
30
+ files: [GLOB_TS],
31
+ languageOptions: {
32
+ parserOptions: {
33
+ // Auto-discovers the nearest tsconfig per file. tsconfigRootDir
34
+ // defaults to process.cwd() — the app dir when `eslint .` runs there.
35
+ projectService: true,
36
+ },
37
+ },
38
+ plugins: { cbrl: cbrlPlugin },
39
+ rules: {
40
+ '@typescript-eslint/no-unused-vars': [
41
+ 'error',
42
+ { argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
43
+ ],
44
+ '@typescript-eslint/consistent-type-imports': 'error',
45
+ // Type-aware successor to the retired `cbrl/no-ts-escape-hatches`.
46
+ '@typescript-eslint/no-unsafe-type-assertion': 'error',
47
+ // Promise hygiene — the most common real bug typed linting catches.
48
+ '@typescript-eslint/no-floating-promises': 'error',
49
+ '@typescript-eslint/no-misused-promises': 'error',
50
+ },
51
+ },
52
+ {
53
+ // Non-typed files (plain JS configs/scripts) have no TS program — turn the
54
+ // type-aware rules off so the parser doesn't error looking for one.
55
+ files: ['**/*.{js,mjs,cjs}'],
56
+ ...tseslint.configs.disableTypeChecked,
57
+ },
58
+ {
59
+ // TS config files (vitest/playwright/next.config.ts …) usually aren't in
60
+ // any tsconfig, so `projectService` can't find a program for them and
61
+ // throws a parse error (which `--suppress-all` can't grandfather). Opt
62
+ // them out of the project service entirely + disable type-aware rules.
63
+ // `disableTypeChecked` already resets parserOptions (project/projectService
64
+ // → false), which is what stops the parse error.
65
+ files: ['**/*.config.{ts,cts,mts}', '**/*.config.*.{ts,cts,mts}'],
66
+ ...tseslint.configs.disableTypeChecked,
67
+ },
68
+ ]
package/globs.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Centralized glob patterns shared across config layers.
2
+ // One source of truth — change a pattern here, every layer picks it up.
3
+
4
+ /** All lintable source/script files. */
5
+ export const GLOB_ALL = '**/*.{js,mjs,cjs,ts,tsx}'
6
+
7
+ /** TypeScript files (TS-specific rules attach here). */
8
+ export const GLOB_TS = '**/*.{ts,tsx}'
9
+
10
+ /** React/JSX files — jsx-a11y attaches here. */
11
+ export const GLOB_TSX = '**/*.tsx'
12
+
13
+ /** Unit/component test files — testing-library query rules attach here. */
14
+ export const GLOB_TEST_FILES = '**/*.test.{ts,tsx}'
15
+
16
+ /** Playwright e2e specs — the playwright plugin attaches here. */
17
+ export const GLOB_E2E_SPECS = ['**/tests/e2e/**', '**/*.spec.ts']
18
+
19
+ /** App source — the ownership gate (no raw primitives / no Radix) attaches here. */
20
+ export const GLOB_APPS = 'apps/**/*.{ts,tsx}'
21
+
22
+ /** TypeScript files under a `src/` source root (excludes configs at the root). */
23
+ export const GLOB_SRC = '**/src/**/*.{ts,tsx}'
24
+
25
+ /** Service workers — separate global scope (`self`, no DOM `window`). */
26
+ export const GLOB_SERVICE_WORKER = ['**/public/sw.js', '**/public/**/sw.js']
27
+
28
+ /** Build artifacts, generated output, and config files to never lint. */
29
+ export const GLOB_IGNORES = [
30
+ '**/node_modules/**',
31
+ '**/.next/**',
32
+ '**/dist/**',
33
+ '**/build/**',
34
+ '**/coverage/**',
35
+ '**/playwright-report/**',
36
+ '**/test-results/**',
37
+ '**/.stryker-tmp/**',
38
+ '**/*.config.js',
39
+ // Rule-test fixtures: deliberately violating source fed to RuleTester/tsc.
40
+ '**/rules/fixtures/**',
41
+ ]
42
+
43
+ /**
44
+ * Test/spec/e2e/smoke files — exempt from the module-size gate. Large
45
+ * table-driven specs and fixtures are legitimate; the cap targets god-files
46
+ * in production source only.
47
+ */
48
+ export const GLOB_TESTS = [
49
+ '**/*.test.{ts,tsx}',
50
+ '**/*.spec.{ts,tsx}',
51
+ '**/*.integration.test.{ts,tsx}',
52
+ '**/_e2e/**',
53
+ '**/_smoke/**',
54
+ '**/e2e/**',
55
+ ]
package/index.mjs ADDED
@@ -0,0 +1,38 @@
1
+ // Canonical ESLint flat config (`@cbrl/eslint-config`).
2
+ //
3
+ // Consumed by `apps/<x>/eslint.config.mjs` via:
4
+ // import cbrlBase from '@cbrl/eslint-config'
5
+ // export default cbrlBase
6
+ //
7
+ // Workspaces that need extra rules can spread + extend:
8
+ // export default [...cbrlBase, { rules: { /* per-app overrides */ } }]
9
+ //
10
+ // This file is a thin composition root: each config "layer" lives in its own
11
+ // module under `configs/`, glob patterns in `globs.mjs`, custom rules in
12
+ // `rules/` (registered via `plugin.mjs`). To change behavior, edit the layer —
13
+ // not this list. Order matters: ignores first, then language baselines, then
14
+ // the structural gate.
15
+
16
+ import { ignores } from './configs/ignores.mjs'
17
+ import { javascript } from './configs/javascript.mjs'
18
+ import { layering } from './configs/layering.mjs'
19
+ import { moduleSize } from './configs/module-size.mjs'
20
+ import { next } from './configs/next.mjs'
21
+ import { testQuality } from './configs/test-quality.mjs'
22
+ import { typescript } from './configs/typescript.mjs'
23
+
24
+ // Named exports let a workspace compose individual layers when the full preset
25
+ // is too much (e.g. a config-only package that wants `ignores` + `javascript`).
26
+ export { ignores, javascript, layering, moduleSize, next, testQuality, typescript }
27
+
28
+ export default [
29
+ ...ignores,
30
+ ...javascript,
31
+ ...typescript,
32
+ ...moduleSize,
33
+ ...layering,
34
+ ...testQuality,
35
+ // Next-framework adjustments last, so its scoped `routes.ts` exception wins
36
+ // over the generic TS assertion rules above. No-op for non-Next workspaces.
37
+ ...next,
38
+ ]
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@cbrl/eslint-config",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Strict ESLint flat config for TypeScript, React and Next.js apps, with custom fail-fast rules (no eslint-disable, no env fallbacks).",
5
+ "license": "MIT",
6
+ "author": "Kayron Cabral",
7
+ "homepage": "https://github.com/kaycabral/toolkit/tree/main/packages/eslint-config#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/kaycabral/toolkit/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/kaycabral/toolkit.git",
14
+ "directory": "packages/eslint-config"
15
+ },
16
+ "keywords": [
17
+ "eslint",
18
+ "eslint-config",
19
+ "flat-config",
20
+ "typescript",
21
+ "nextjs"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./index.mjs",
26
+ "./plugin": "./plugin.mjs",
27
+ "./globs": "./globs.mjs"
28
+ },
29
+ "files": [
30
+ "index.mjs",
31
+ "globs.mjs",
32
+ "plugin.mjs",
33
+ "configs/",
34
+ "rules/*.mjs",
35
+ "!rules/*.test.mjs"
36
+ ],
37
+ "dependencies": {
38
+ "@eslint/js": "^9.39.4",
39
+ "eslint-plugin-boundaries": "^6.0.2",
40
+ "eslint-plugin-jsx-a11y": "^6.10.2",
41
+ "eslint-plugin-playwright": "^2.2.2",
42
+ "eslint-plugin-sonarjs": "^4.0.3",
43
+ "eslint-plugin-testing-library": "^7.13.1",
44
+ "globals": "^15.15.0",
45
+ "typescript-eslint": "^8.59.3"
46
+ },
47
+ "peerDependencies": {
48
+ "eslint": "^9.0.0",
49
+ "typescript": ">=5.0.0 <7"
50
+ },
51
+ "devDependencies": {
52
+ "eslint": "^9.39.4",
53
+ "publint": "^0.3.25",
54
+ "typescript": "^5.9.3"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "scripts": {
60
+ "lint": "eslint .",
61
+ "test": "node --test rules/*.test.mjs",
62
+ "check:package": "node ../../scripts/check-package.mjs"
63
+ }
6
64
  }
package/plugin.mjs ADDED
@@ -0,0 +1,13 @@
1
+ import { noConditionalSpreadChain } from './rules/no-conditional-spread-chain.mjs'
2
+ import { noEnvValueFallback } from './rules/no-env-value-fallback.mjs'
3
+ import { noEslintDisable } from './rules/no-eslint-disable.mjs'
4
+ import { noNonDocComments } from './rules/no-non-doc-comments.mjs'
5
+
6
+ export const cbrlPlugin = {
7
+ rules: {
8
+ 'no-conditional-spread-chain': noConditionalSpreadChain,
9
+ 'no-env-value-fallback': noEnvValueFallback,
10
+ 'no-eslint-disable': noEslintDisable,
11
+ 'no-non-doc-comments': noNonDocComments,
12
+ },
13
+ }
@@ -0,0 +1,107 @@
1
+ // Custom rule: proíbe spread condicional aninhado em outro spread condicional.
2
+ //
3
+ // Codifica decisão canônica do PR #971 (commit `abec9de7`) + recidiva no
4
+ // PR #972 (commit `285e0f1c`). Memória de projeto não previne recidiva
5
+ // cross-instância de Claude; análise sintática previne.
6
+ //
7
+ // Anti-pattern:
8
+ //
9
+ // const obj = {
10
+ // base: 1,
11
+ // ...(c1
12
+ // ? { foo: mapValue({
13
+ // ...(c2 ? { a: x } : {}), // ← spread aninhado dentro
14
+ // ...(c3 ? { b: y } : {}), // de outro spread cond
15
+ // }) }
16
+ // : {}),
17
+ // }
18
+ //
19
+ // Por quê é ruim:
20
+ // - Legibilidade ruim (nesting profundo, ternário + spread misturados)
21
+ // - TypeScript infer fica frágil (vira `Partial<X>` / `Record<string,unknown>`)
22
+ // - Repetição da expressão de teste (`c1.x` 3-6× no mesmo bloco)
23
+ // - Esconde forma final do objeto — leitor expande mentalmente
24
+ //
25
+ // Padrão correto: record intermediário + `if`s explícitos.
26
+ //
27
+ // const inner: Record<string, X> = {}
28
+ // if (c2) inner.a = x
29
+ // if (c3) inner.b = y
30
+ // const obj: Record<string, Y> = { base: 1 }
31
+ // if (c1) obj.foo = mapValue(inner)
32
+ //
33
+ // Distinção (NÃO confundir):
34
+ // - Spread condicional ÚNICO E RASO (`...(opts.foo ? { foo: ... } : {})`)
35
+ // é idiomático — esta rule NÃO dispara nele.
36
+ // - Só dispara quando há aninhamento (spread cond dentro de spread cond).
37
+
38
+ function isConditionalSpread(node) {
39
+ return node?.type === 'SpreadElement' && node.argument?.type === 'ConditionalExpression'
40
+ }
41
+
42
+ // Walk recursivo procurando outro spread condicional dentro do nó dado.
43
+ // Caminha por ObjectExpression, CallExpression args, ArrayExpression,
44
+ // ConditionalExpression branches e Property values — cobre os formatos
45
+ // reais do anti-pattern (incluindo o caso `mapValue({...cond...})` onde o
46
+ // spread aninhado mora dentro de uma chamada de helper).
47
+ function containsConditionalSpread(node, depthBudget = 50) {
48
+ if (!node || depthBudget <= 0) return false
49
+ if (isConditionalSpread(node)) return true
50
+
51
+ switch (node.type) {
52
+ case 'ObjectExpression':
53
+ return node.properties.some((p) => containsConditionalSpread(p, depthBudget - 1))
54
+ case 'CallExpression':
55
+ case 'NewExpression':
56
+ return (node.arguments ?? []).some((a) => containsConditionalSpread(a, depthBudget - 1))
57
+ case 'ConditionalExpression':
58
+ return (
59
+ containsConditionalSpread(node.consequent, depthBudget - 1) ||
60
+ containsConditionalSpread(node.alternate, depthBudget - 1)
61
+ )
62
+ case 'ArrayExpression':
63
+ return (node.elements ?? []).some((e) => e && containsConditionalSpread(e, depthBudget - 1))
64
+ case 'Property':
65
+ return containsConditionalSpread(node.value, depthBudget - 1)
66
+ case 'SpreadElement':
67
+ return containsConditionalSpread(node.argument, depthBudget - 1)
68
+ case 'LogicalExpression':
69
+ case 'BinaryExpression':
70
+ return (
71
+ containsConditionalSpread(node.left, depthBudget - 1) ||
72
+ containsConditionalSpread(node.right, depthBudget - 1)
73
+ )
74
+ default:
75
+ return false
76
+ }
77
+ }
78
+
79
+ export const noConditionalSpreadChain = {
80
+ meta: {
81
+ type: 'problem',
82
+ docs: {
83
+ description:
84
+ 'Disallow nested conditional-spread (`...(c ? {...(c2 ? {} : {}), ...} : {})`); use intermediate record + explicit ifs.',
85
+ recommended: true,
86
+ },
87
+ schema: [],
88
+ messages: {
89
+ chain:
90
+ 'Conditional spread nested inside another conditional spread. Build an intermediate record with explicit `if`s instead. A single, shallow conditional spread is fine; only nesting is banned.',
91
+ },
92
+ },
93
+ create(context) {
94
+ return {
95
+ SpreadElement(node) {
96
+ if (node.argument?.type !== 'ConditionalExpression') return
97
+ const cond = node.argument
98
+ if (
99
+ containsConditionalSpread(cond.consequent) ||
100
+ containsConditionalSpread(cond.alternate)
101
+ ) {
102
+ context.report({ node, messageId: 'chain' })
103
+ }
104
+ },
105
+ }
106
+ },
107
+ }
@@ -0,0 +1,107 @@
1
+ // Custom rule: proíbe fallback hardcoded de VALOR em `process.env.<ANY>`.
2
+ //
3
+ // Codifica princípio canônico do harness: "fail-fast > silent default".
4
+ // Vale pra QUALQUER env var (não só secrets): um default literal mascara
5
+ // misconfig — o app roda com um valor trivial em vez de quebrar e expor que a
6
+ // env não foi setada.
7
+ //
8
+ // Anti-pattern detectado (right operand é um literal de VALOR):
9
+ // const url = process.env.APP_URL ?? 'http://localhost:3000'
10
+ // const x = process.env.X || 'default'
11
+ // process.env.X ??= 'literal'
12
+ // process.env.X ||= 'literal'
13
+ // const p = process.env.A ?? process.env.B ?? 'literal' // cadeia que termina em literal
14
+ //
15
+ // Padrão correto: leia e falhe alto se ausente.
16
+ // const url = process.env.APP_URL
17
+ // if (!url) throw new Error('APP_URL not set')
18
+ // // ou um helper `env('APP_URL')` que faz isso.
19
+ //
20
+ // NÃO viola (default não é literal de valor — não mascara misconfig):
21
+ // - `||` booleano / lógica: `if (process.env.X || process.env.Y)`, `!!a || !!b`
22
+ // - cadeia env→env sem literal: `process.env.A ?? process.env.B` (termina em throw downstream)
23
+ // - normalização de ausência: `process.env.X ?? null`, `?? undefined`
24
+ // - fallback que não é literal: `process.env.XDG_CONFIG_HOME ?? join(homedir(), ...)`
25
+
26
+ // Literal de VALOR: string/number/boolean/bigint/template. Exclui `null`
27
+ // (ESLint: Literal com value === null) — `?? null` é normalização, não default.
28
+ function isValueLiteralFallback(node) {
29
+ if (!node) return false
30
+ if (node.type === 'TemplateLiteral') return true
31
+ if (node.type === 'Literal') return node.value !== null
32
+ return false
33
+ }
34
+
35
+ function isProcessEnvAccess(node) {
36
+ return (
37
+ node?.type === 'MemberExpression' &&
38
+ node.object?.type === 'MemberExpression' &&
39
+ node.object?.object?.name === 'process' &&
40
+ node.object?.property?.name === 'env'
41
+ )
42
+ }
43
+
44
+ // `left` "vem de process.env" se é um acesso direto OU uma cadeia ??/|| cuja
45
+ // raiz à esquerda é process.env — pega `process.env.A ?? process.env.B ?? 'lit'`.
46
+ function leftRootIsProcessEnv(node) {
47
+ if (isProcessEnvAccess(node)) return true
48
+ if (node?.type === 'LogicalExpression' && (node.operator === '??' || node.operator === '||')) {
49
+ return leftRootIsProcessEnv(node.left)
50
+ }
51
+ return false
52
+ }
53
+
54
+ // Nome da env mais à esquerda (pra mensagem), descendo a cadeia ??/||.
55
+ function leftmostEnvVarName(node) {
56
+ if (isProcessEnvAccess(node)) return node.property?.name
57
+ if (node?.type === 'LogicalExpression') return leftmostEnvVarName(node.left)
58
+ return undefined
59
+ }
60
+
61
+ export const noEnvValueFallback = {
62
+ meta: {
63
+ type: 'problem',
64
+ docs: {
65
+ description:
66
+ 'Disallow hardcoded value fallback on `process.env.<ANY>` — read and fail-fast instead.',
67
+ recommended: true,
68
+ },
69
+ schema: [],
70
+ messages: {
71
+ envFallback:
72
+ "A literal fallback on `process.env.{{varName}}` hides misconfiguration: the app runs with a trivial value instead of failing. Read it fail-fast (`requireEnv('{{varName}}')` from @cbrl/env). Non-value defaults are fine: `?? null`, an env→env chain, or a computed path.",
73
+ },
74
+ },
75
+ create(context) {
76
+ function report(opNode, nameSourceNode) {
77
+ const varName = leftmostEnvVarName(nameSourceNode)
78
+ if (!varName) return
79
+ context.report({ node: opNode, messageId: 'envFallback', data: { varName } })
80
+ }
81
+
82
+ return {
83
+ // process.env.X ?? 'lit' | process.env.X || 'lit' | A ?? B ?? 'lit'
84
+ 'LogicalExpression[operator="??"]'(node) {
85
+ if (leftRootIsProcessEnv(node.left) && isValueLiteralFallback(node.right)) {
86
+ report(node, node.left)
87
+ }
88
+ },
89
+ 'LogicalExpression[operator="||"]'(node) {
90
+ if (leftRootIsProcessEnv(node.left) && isValueLiteralFallback(node.right)) {
91
+ report(node, node.left)
92
+ }
93
+ },
94
+ // process.env.X ??= 'lit' | process.env.X ||= 'lit'
95
+ 'AssignmentExpression[operator="??="]'(node) {
96
+ if (isProcessEnvAccess(node.left) && isValueLiteralFallback(node.right)) {
97
+ report(node, node.left)
98
+ }
99
+ },
100
+ 'AssignmentExpression[operator="||="]'(node) {
101
+ if (isProcessEnvAccess(node.left) && isValueLiteralFallback(node.right)) {
102
+ report(node, node.left)
103
+ }
104
+ },
105
+ }
106
+ },
107
+ }
@@ -0,0 +1,41 @@
1
+ // Custom rule: bans EVERY `eslint-disable*` directive in code. A wrong rule is
2
+ // changed in eslint.config.mjs through review, never silenced inline.
3
+ //
4
+ // Por que custom e não só o nativo `linterOptions.noInlineConfig`:
5
+ // noInlineConfig neutraliza os directives mas reporta apenas WARNING (não
6
+ // configurável pra error) — não barra um lint que roda sem `--max-warnings 0`.
7
+ // Esta rule reporta ERROR (hard-fail). O `noInlineConfig` fica ligado em
8
+ // paralelo como backstop: torna o disable inerte, então NÃO dá pra silenciar
9
+ // esta própria regra com um `// eslint-disable-line cbrl/no-eslint-disable`.
10
+
11
+ export const noEslintDisable = {
12
+ meta: {
13
+ type: 'problem',
14
+ docs: {
15
+ description: 'Disallow all eslint-disable directives',
16
+ recommended: true,
17
+ },
18
+ schema: [],
19
+ messages: {
20
+ disableForbidden:
21
+ 'eslint-disable directive is forbidden. If the rule is wrong, change it in eslint.config.mjs.',
22
+ },
23
+ },
24
+ create(context) {
25
+ return {
26
+ Program() {
27
+ const comments = context.getSourceCode().getAllComments()
28
+ for (const comment of comments) {
29
+ const text = comment.value.trim()
30
+ // Match: eslint-disable, eslint-disable-line, eslint-disable-next-line
31
+ if (/^eslint-disable(-line|-next-line)?(\s|$)/.test(text)) {
32
+ context.report({
33
+ loc: comment.loc,
34
+ messageId: 'disableForbidden',
35
+ })
36
+ }
37
+ }
38
+ },
39
+ }
40
+ },
41
+ }
@@ -0,0 +1,115 @@
1
+ import ts from 'typescript'
2
+
3
+ const MACHINE_PRAGMAS = [
4
+ /^\s*@ts-(expect-error|ignore|nocheck|check)\b/,
5
+ /^\/\s*<(reference|amd-module|amd-dependency)\b/,
6
+ /^\s*globals?\s/,
7
+ /^\s*eslint-env\b/,
8
+ /^\s*prettier-ignore\b/,
9
+ /^\s*(c8|v8|istanbul|node:coverage)\b/,
10
+ /^\s*@(jest|vitest)-environment\b/,
11
+ /^\s*#!/,
12
+ /^\s*#?__(PURE|NO_SIDE_EFFECTS)__\s*$/,
13
+ /^\s*@(license|preserve|__PURE__|__NO_SIDE_EFFECTS__|vite-ignore)\b/,
14
+ /webpackChunkName|webpackPrefetch|webpackPreload|webpackMode|webpackIgnore/,
15
+ /^#\s*sourceMappingURL=/,
16
+ /^\s*#?(end)?region\b/,
17
+ ]
18
+
19
+ const ESLINT_DIRECTIVE = /^\s*eslint(-disable(-line|-next-line)?|-enable)?\b/
20
+
21
+ function collectTaggedJsDocRanges(tsSource) {
22
+ const ranges = new Set()
23
+ const visit = (node) => {
24
+ const jsDoc = node.jsDoc
25
+ if (Array.isArray(jsDoc)) {
26
+ for (const doc of jsDoc) {
27
+ if (Array.isArray(doc.tags) && doc.tags.length > 0) {
28
+ ranges.add(`${doc.pos}:${doc.end}`)
29
+ }
30
+ }
31
+ }
32
+ ts.forEachChild(node, visit)
33
+ }
34
+ visit(tsSource)
35
+ return ranges
36
+ }
37
+
38
+ function isMachinePragma(text) {
39
+ return MACHINE_PRAGMAS.some((pattern) => pattern.test(text))
40
+ }
41
+
42
+ function jsxContainerAround(sourceCode, comment) {
43
+ const node = sourceCode.getNodeByRangeIndex(comment.range[0])
44
+ if (node === null) return null
45
+ if (node.type === 'JSXExpressionContainer' && node.expression?.type === 'JSXEmptyExpression') {
46
+ return node
47
+ }
48
+ if (node.type === 'JSXEmptyExpression' && node.parent?.type === 'JSXExpressionContainer') {
49
+ return node.parent
50
+ }
51
+ return null
52
+ }
53
+
54
+ export const noNonDocComments = {
55
+ meta: {
56
+ type: 'problem',
57
+ fixable: 'code',
58
+ docs: {
59
+ description:
60
+ 'Disallow every comment except machine pragmas and compiler-attached TSDoc — the code is the single source of truth.',
61
+ recommended: false,
62
+ },
63
+ schema: [],
64
+ messages: {
65
+ prose:
66
+ 'Comments are forbidden here. Only machine pragmas (@ts-*, ///<reference>, prettier-ignore, coverage) and compiler-attached TSDoc (/** */ above a declaration) survive — everything a human reads must live in the code itself, never in prose that can drift from it. Delete this comment; make the code self-explanatory, promote a load-bearing reason to a test, or attach TSDoc to the symbol.',
67
+ },
68
+ },
69
+ create(context) {
70
+ const sourceCode = context.sourceCode
71
+ const services = sourceCode.parserServices
72
+ const program = services?.program
73
+ const tsSource = program?.getSourceFile(context.filename)
74
+ const hasProgram = tsSource !== undefined && tsSource !== null
75
+ const taggedJsDoc = hasProgram ? collectTaggedJsDocRanges(tsSource) : new Set()
76
+
77
+ return {
78
+ Program() {
79
+ for (const comment of sourceCode.getAllComments()) {
80
+ const text = comment.value
81
+
82
+ if (ESLINT_DIRECTIVE.test(text)) continue
83
+ if (isMachinePragma(text)) continue
84
+
85
+ if (comment.type === 'Block' && text.startsWith('*')) {
86
+ if (!hasProgram) continue
87
+ const key = `${comment.range[0]}:${comment.range[1]}`
88
+ if (taggedJsDoc.has(key)) continue
89
+ }
90
+
91
+ context.report({
92
+ loc: comment.loc,
93
+ messageId: 'prose',
94
+ fix(fixer) {
95
+ const fullText = sourceCode.getText()
96
+ const container = jsxContainerAround(sourceCode, comment)
97
+ const [rangeStart, rangeEnd] = container === null ? comment.range : container.range
98
+
99
+ let from = rangeStart
100
+ while (from > 0 && (fullText[from - 1] === ' ' || fullText[from - 1] === '\t')) {
101
+ from -= 1
102
+ }
103
+ let to = rangeEnd
104
+ const lineStartIsBlank = from === 0 || fullText[from - 1] === '\n'
105
+ if (lineStartIsBlank && fullText[to] === '\n') {
106
+ to += 1
107
+ }
108
+ return fixer.removeRange([from, to])
109
+ },
110
+ })
111
+ }
112
+ },
113
+ }
114
+ },
115
+ }