@cbrl/eslint-config 0.0.0-stage → 0.1.1

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/ is the functional core: no React/Next. State, effects and rendering live in ui/ or 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/ is pure: no Firestore/admin/server-only. Data access lives in adapters/ (e.g. *.repo.ts).',
57
+ },
58
+ {
59
+ group: ['**/adapters/*', '**/ui/*', '@/features/*/adapters/*', '@/features/*/ui/*'],
60
+ message:
61
+ 'Dependencies only point down (ui→adapters→core): core/ must not import adapters/ or ui/.',
62
+ },
63
+ {
64
+ group: ['@/app/*', '@/app/**'],
65
+ message:
66
+ 'features/ must not import app/: app is the outer routing shell (inversion).',
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/ is the pure kernel: no 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/ is pure: no Firestore/admin/server-only.',
99
+ },
100
+ {
101
+ group: ['@/shared/*', '@/features/*', '@/app/*'],
102
+ message:
103
+ 'domain/ is the innermost ring: it must not import shared/, features/ or app/.',
104
+ },
105
+ ],
106
+ },
107
+ ],
108
+ },
109
+ },
110
+ // ── Wall 1c: no layer inversion ────────────────────────────────────────
111
+ // Dependencies point inward only: app → features → shared → domain. These
112
+ // catch the upward (inverted) imports the per-ring walls above don't:
113
+ // • features (adapters/ui) → app (app is the outer routing shell)
114
+ // • shared → features / app (shared is below features)
115
+ // • components → app (shared visual is below routing)
116
+ // Scopes are disjoint from the core/domain walls above (no rule-merge clash).
117
+ {
118
+ files: ['**/features/*/adapters/**/*.{ts,tsx}', '**/features/*/ui/**/*.{ts,tsx}'],
119
+ rules: {
120
+ 'no-restricted-imports': [
121
+ 'error',
122
+ {
123
+ patterns: [
124
+ {
125
+ group: ['@/app/*', '@/app/**'],
126
+ message:
127
+ 'features/ must not import app/: app is the outer routing shell (inversion).',
128
+ },
129
+ ],
130
+ },
131
+ ],
132
+ },
133
+ },
134
+ {
135
+ files: ['**/shared/**/*.{ts,tsx}'],
136
+ rules: {
137
+ 'no-restricted-imports': [
138
+ 'error',
139
+ {
140
+ patterns: [
141
+ {
142
+ group: ['@/features/*', '@/features/**', '@/app/*', '@/app/**'],
143
+ message:
144
+ 'shared/ is infrastructure below features/: it must not import features/ or app/ (layer inversion).',
145
+ },
146
+ ],
147
+ },
148
+ ],
149
+ },
150
+ },
151
+ {
152
+ files: ['**/components/**/*.{ts,tsx}'],
153
+ rules: {
154
+ 'no-restricted-imports': [
155
+ 'error',
156
+ {
157
+ patterns: [
158
+ {
159
+ group: ['@/app/*', '@/app/**'],
160
+ message: 'components/ is shared UI: it must not import app/ (layer inversion).',
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}}) must not import {{target}}: dependencies only point down (ui→adapters→core).',
190
+ },
191
+ {
192
+ from: ['feat-adapters'],
193
+ disallow: ['feat-ui'],
194
+ message:
195
+ 'adapters ({{from}}) must not import ui: the flow is ui→adapters, never the reverse.',
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,92 @@
1
+ // Layer: test-quality & ownership gates (paved road). Prefer the canonical community plugin over a
2
+ // custom rule; a built-in `no-restricted-*` is used ONLY where no plugin rule
3
+ // exists (the data-testid and raw-primitive bans). Existing violations are
4
+ // grandfathered via the native bulk-suppressions file and pruned over time —
5
+ // new code must comply.
6
+
7
+ import jsxA11y from 'eslint-plugin-jsx-a11y'
8
+ import playwright from 'eslint-plugin-playwright'
9
+ import testingLibrary from 'eslint-plugin-testing-library'
10
+
11
+ import { GLOB_APPS, GLOB_E2E_SPECS, GLOB_TEST_FILES, GLOB_TS, GLOB_TSX } from '../globs.mjs'
12
+
13
+ // `data-testid` is banned everywhere: tests must target accessible
14
+ // roles/labels/text (reachable via the jsx-a11y layer). A test that can only be
15
+ // written against a testid signals inaccessible markup — fix the markup, not the
16
+ // test. No community rule bans the attribute at the source, so this is the
17
+ // built-in no-restricted-syntax (not a custom cbrl/* rule).
18
+ const NO_DATA_TESTID = {
19
+ selector: "JSXAttribute[name.name='data-testid']",
20
+ message:
21
+ 'Do not use data-testid. Make the element queryable by role/label/text (see jsx-a11y) so tests target accessible semantics, not test hooks.',
22
+ }
23
+
24
+ // Apps must not hand-roll UI primitives the design system owns.
25
+ const NO_RAW_PRIMITIVE = {
26
+ selector: 'JSXOpeningElement[name.name=/^(button|input|textarea|select)$/]',
27
+ message:
28
+ '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.',
29
+ }
30
+
31
+ // The playwright recommended set ships several rules as `warn`; force every one
32
+ // to `error` — an advisory that never blocks is documentation in disguise. A
33
+ // flaky-test smell must fail loud and be fixed now, not accumulate.
34
+ const playwrightErrors = Object.fromEntries(
35
+ Object.entries(playwright.configs['flat/recommended'].rules).map(([rule, level]) => [
36
+ rule,
37
+ level === 'warn' || level === 1 ? 'error' : level,
38
+ ]),
39
+ )
40
+
41
+ /** @type {import('eslint').Linter.Config[]} */
42
+ export const testQuality = [
43
+ // Accessibility — jsx-a11y. Beyond the a11y win, `htmlFor`/role pairing is
44
+ // what lets Playwright/Testing-Library query by role+label instead of brittle
45
+ // selectors. The upstream half of "no data-testid".
46
+ { ...jsxA11y.flatConfigs.recommended, files: [GLOB_TSX] },
47
+
48
+ // Testing Library — query best practices (prefer getByRole, no direct
49
+ // container.querySelector, await async queries). Component/unit tests only.
50
+ { ...testingLibrary.configs['flat/react'], files: [GLOB_TEST_FILES] },
51
+
52
+ // Playwright — web-first assertions, no arbitrary waitForTimeout/networkidle,
53
+ // no ElementHandle. Scoped to the e2e specs.
54
+ {
55
+ ...playwright.configs['flat/recommended'],
56
+ files: GLOB_E2E_SPECS,
57
+ rules: {
58
+ ...playwrightErrors,
59
+ // Teach expect-expect about our custom assertion helpers so a test that
60
+ // asserts *through* a helper isn't flagged as assertion-less.
61
+ 'playwright/expect-expect': ['error', { assertFunctionNames: ['assertOk', 'assertNoCrash'] }],
62
+ },
63
+ },
64
+
65
+ // `data-testid` banned everywhere.
66
+ {
67
+ files: [GLOB_TS],
68
+ rules: { 'no-restricted-syntax': ['error', NO_DATA_TESTID] },
69
+ },
70
+
71
+ // Test-ownership / no-duplication gate. Apps must not re-implement design
72
+ // primitives nor reach for Radix directly — that path belongs to @cbrl/design.
73
+ // Keeps app code about business rules and primitives built/tested in one place.
74
+ {
75
+ files: [GLOB_APPS],
76
+ rules: {
77
+ 'no-restricted-syntax': ['error', NO_DATA_TESTID, NO_RAW_PRIMITIVE],
78
+ 'no-restricted-imports': [
79
+ 'error',
80
+ {
81
+ patterns: [
82
+ {
83
+ group: ['radix-ui', '@radix-ui/*'],
84
+ message:
85
+ 'Radix belongs to @cbrl/design. Apps consume design components, not Radix directly — promote the primitive to @cbrl/design instead.',
86
+ },
87
+ ],
88
+ },
89
+ ],
90
+ },
91
+ },
92
+ ]
@@ -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.1",
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,105 @@
1
+ // Custom rule: bans a conditional spread nested inside another conditional spread.
2
+ //
3
+ // A recurring review finding turned into a syntactic check, so it cannot regress.
4
+ //
5
+ // Anti-pattern:
6
+ //
7
+ // const obj = {
8
+ // base: 1,
9
+ // ...(c1
10
+ // ? { foo: mapValue({
11
+ // ...(c2 ? { a: x } : {}), // ← spread nested inside
12
+ // ...(c3 ? { b: y } : {}), // another conditional spread
13
+ // }) }
14
+ // : {}),
15
+ // }
16
+ //
17
+ // Why it hurts:
18
+ // - Poor readability (deep nesting, ternaries mixed with spreads)
19
+ // - Fragile TypeScript inference (degrades to `Partial<X>` / `Record<string, unknown>`)
20
+ // - The test expression repeats (`c1.x` 3-6 times in the same block)
21
+ // - Hides the final shape of the object — the reader expands it mentally
22
+ //
23
+ // Correct pattern: an intermediate record plus explicit `if`s.
24
+ //
25
+ // const inner: Record<string, X> = {}
26
+ // if (c2) inner.a = x
27
+ // if (c3) inner.b = y
28
+ // const obj: Record<string, Y> = { base: 1 }
29
+ // if (c1) obj.foo = mapValue(inner)
30
+ //
31
+ // Do NOT confuse with:
32
+ // - A SINGLE, SHALLOW conditional spread (`...(opts.foo ? { foo: ... } : {})`)
33
+ // is idiomatic — this rule does NOT fire on it.
34
+ // - It only fires on nesting (a conditional spread inside a conditional spread).
35
+
36
+ function isConditionalSpread(node) {
37
+ return node?.type === 'SpreadElement' && node.argument?.type === 'ConditionalExpression'
38
+ }
39
+
40
+ // Recursive walk looking for another conditional spread inside the given node.
41
+ // Visits ObjectExpression, CallExpression args, ArrayExpression,
42
+ // ConditionalExpression branches and Property values — the real shapes of the
43
+ // anti-pattern (including `mapValue({...cond...})`, where the nested spread
44
+ // lives inside a helper call).
45
+ function containsConditionalSpread(node, depthBudget = 50) {
46
+ if (!node || depthBudget <= 0) return false
47
+ if (isConditionalSpread(node)) return true
48
+
49
+ switch (node.type) {
50
+ case 'ObjectExpression':
51
+ return node.properties.some((p) => containsConditionalSpread(p, depthBudget - 1))
52
+ case 'CallExpression':
53
+ case 'NewExpression':
54
+ return (node.arguments ?? []).some((a) => containsConditionalSpread(a, depthBudget - 1))
55
+ case 'ConditionalExpression':
56
+ return (
57
+ containsConditionalSpread(node.consequent, depthBudget - 1) ||
58
+ containsConditionalSpread(node.alternate, depthBudget - 1)
59
+ )
60
+ case 'ArrayExpression':
61
+ return (node.elements ?? []).some((e) => e && containsConditionalSpread(e, depthBudget - 1))
62
+ case 'Property':
63
+ return containsConditionalSpread(node.value, depthBudget - 1)
64
+ case 'SpreadElement':
65
+ return containsConditionalSpread(node.argument, depthBudget - 1)
66
+ case 'LogicalExpression':
67
+ case 'BinaryExpression':
68
+ return (
69
+ containsConditionalSpread(node.left, depthBudget - 1) ||
70
+ containsConditionalSpread(node.right, depthBudget - 1)
71
+ )
72
+ default:
73
+ return false
74
+ }
75
+ }
76
+
77
+ export const noConditionalSpreadChain = {
78
+ meta: {
79
+ type: 'problem',
80
+ docs: {
81
+ description:
82
+ 'Disallow nested conditional-spread (`...(c ? {...(c2 ? {} : {}), ...} : {})`); use intermediate record + explicit ifs.',
83
+ recommended: true,
84
+ },
85
+ schema: [],
86
+ messages: {
87
+ chain:
88
+ '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.',
89
+ },
90
+ },
91
+ create(context) {
92
+ return {
93
+ SpreadElement(node) {
94
+ if (node.argument?.type !== 'ConditionalExpression') return
95
+ const cond = node.argument
96
+ if (
97
+ containsConditionalSpread(cond.consequent) ||
98
+ containsConditionalSpread(cond.alternate)
99
+ ) {
100
+ context.report({ node, messageId: 'chain' })
101
+ }
102
+ },
103
+ }
104
+ },
105
+ }
@@ -0,0 +1,106 @@
1
+ // Custom rule: bans a hardcoded VALUE fallback on `process.env.<ANY>`.
2
+ //
3
+ // Encodes "fail-fast over silent default". It applies to ANY env var, not only
4
+ // secrets: a literal default hides misconfiguration — the app runs with a
5
+ // trivial value instead of failing and revealing the variable was never set.
6
+ //
7
+ // Flagged anti-pattern (the right operand is a VALUE literal):
8
+ // const url = process.env.APP_URL ?? 'http://localhost:3000'
9
+ // const x = process.env.X || 'default'
10
+ // process.env.X ??= 'literal'
11
+ // process.env.X ||= 'literal'
12
+ // const p = process.env.A ?? process.env.B ?? 'literal' // chain ending in a literal
13
+ //
14
+ // Correct pattern: read it and fail loudly when missing.
15
+ // const url = process.env.APP_URL
16
+ // if (!url) throw new Error('APP_URL not set')
17
+ // // or `requireEnv('APP_URL')` from @cbrl/env.
18
+ //
19
+ // NOT a violation (the default is not a value literal, so nothing is masked):
20
+ // - boolean / logical `||`: `if (process.env.X || process.env.Y)`, `!!a || !!b`
21
+ // - env→env chain with no literal: `process.env.A ?? process.env.B` (throws downstream)
22
+ // - absence normalization: `process.env.X ?? null`, `?? undefined`
23
+ // - non-literal fallback: `process.env.XDG_CONFIG_HOME ?? join(homedir(), ...)`
24
+
25
+ // VALUE literal: string/number/boolean/bigint/template. Excludes `null`
26
+ // (an ESLint Literal with value === null): `?? null` normalizes, it is not a default.
27
+ function isValueLiteralFallback(node) {
28
+ if (!node) return false
29
+ if (node.type === 'TemplateLiteral') return true
30
+ if (node.type === 'Literal') return node.value !== null
31
+ return false
32
+ }
33
+
34
+ function isProcessEnvAccess(node) {
35
+ return (
36
+ node?.type === 'MemberExpression' &&
37
+ node.object?.type === 'MemberExpression' &&
38
+ node.object?.object?.name === 'process' &&
39
+ node.object?.property?.name === 'env'
40
+ )
41
+ }
42
+
43
+ // `left` "comes from process.env" when it is a direct access OR a ??/|| chain
44
+ // whose leftmost root is process.env — catches `process.env.A ?? process.env.B ?? 'lit'`.
45
+ function leftRootIsProcessEnv(node) {
46
+ if (isProcessEnvAccess(node)) return true
47
+ if (node?.type === 'LogicalExpression' && (node.operator === '??' || node.operator === '||')) {
48
+ return leftRootIsProcessEnv(node.left)
49
+ }
50
+ return false
51
+ }
52
+
53
+ // Leftmost env var name (for the message), walking down the ??/|| chain.
54
+ function leftmostEnvVarName(node) {
55
+ if (isProcessEnvAccess(node)) return node.property?.name
56
+ if (node?.type === 'LogicalExpression') return leftmostEnvVarName(node.left)
57
+ return undefined
58
+ }
59
+
60
+ export const noEnvValueFallback = {
61
+ meta: {
62
+ type: 'problem',
63
+ docs: {
64
+ description:
65
+ 'Disallow hardcoded value fallback on `process.env.<ANY>` — read and fail-fast instead.',
66
+ recommended: true,
67
+ },
68
+ schema: [],
69
+ messages: {
70
+ envFallback:
71
+ "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.",
72
+ },
73
+ },
74
+ create(context) {
75
+ function report(opNode, nameSourceNode) {
76
+ const varName = leftmostEnvVarName(nameSourceNode)
77
+ if (!varName) return
78
+ context.report({ node: opNode, messageId: 'envFallback', data: { varName } })
79
+ }
80
+
81
+ return {
82
+ // process.env.X ?? 'lit' | process.env.X || 'lit' | A ?? B ?? 'lit'
83
+ 'LogicalExpression[operator="??"]'(node) {
84
+ if (leftRootIsProcessEnv(node.left) && isValueLiteralFallback(node.right)) {
85
+ report(node, node.left)
86
+ }
87
+ },
88
+ 'LogicalExpression[operator="||"]'(node) {
89
+ if (leftRootIsProcessEnv(node.left) && isValueLiteralFallback(node.right)) {
90
+ report(node, node.left)
91
+ }
92
+ },
93
+ // process.env.X ??= 'lit' | process.env.X ||= 'lit'
94
+ 'AssignmentExpression[operator="??="]'(node) {
95
+ if (isProcessEnvAccess(node.left) && isValueLiteralFallback(node.right)) {
96
+ report(node, node.left)
97
+ }
98
+ },
99
+ 'AssignmentExpression[operator="||="]'(node) {
100
+ if (isProcessEnvAccess(node.left) && isValueLiteralFallback(node.right)) {
101
+ report(node, node.left)
102
+ }
103
+ },
104
+ }
105
+ },
106
+ }
@@ -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
+ // Why a custom rule and not just the native `linterOptions.noInlineConfig`:
5
+ // noInlineConfig neutralizes the directives but only reports a WARNING (not
6
+ // configurable as an error), so it does not fail a lint run without
7
+ // `--max-warnings 0`. This rule reports an ERROR (hard fail). `noInlineConfig`
8
+ // stays on alongside it as a backstop: it makes the directive inert, so this
9
+ // rule cannot be silenced with `// 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
+ }