@kirill.konshin/lint 0.3.0 → 0.3.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/README.md CHANGED
@@ -17,43 +17,22 @@ auto-install-peers=true
17
17
  node-linker=hoisted
18
18
  ```
19
19
 
20
- ## ESLint / Prettier / lint-staged / Husky
21
-
22
- ### Settings
20
+ ## ESLint
23
21
 
24
22
  `eslint.config.mjs`:
25
23
 
26
- ```js
27
- import { defineLintConfig } from '@kirill.konshin/lint';
28
-
29
- export default defineLintConfig(); // every tool integration auto-detected
30
- ```
31
-
32
24
  Every tool integration — Next.js, Nx, Turborepo, Storybook, Jest, Vitest, Tailwind — is auto-detected (the detection results are exported as `has*` booleans for debugging). Pass options (JSDoc-typed, see `LintOptions` in `index.js`) to force any of them on/off or to supply tool-specific settings:
33
25
 
34
26
  ```js
27
+ import { defineLintConfig } from '@kirill.konshin/lint';
28
+
29
+ // every tool integration auto-detected
35
30
  export default defineLintConfig({
36
31
  defaultIgnore: { importMetaUrl: import.meta.url }, // .gitignore + .prettierignore as ESLint ignores
37
- next: { rootDir: 'path/to/next-app' }, // an options object means ON + settings; auto-detected when omitted
38
- tailwind: true, // force ON when detection misses it
39
- turbo: false, // force OFF
40
32
  });
41
33
  ```
42
34
 
43
- - `undefined` (default) — auto-detect
44
- - `true` or an options object — force ON. Detection probes resolve from this package's install location, so in a monorepo where a tool lives only in **leaf** packages (not the root `package.json`) detection can miss it — force the flag in that case
45
- - `false` — force OFF
46
- - in the object form `enabled` defaults to `true` — providing options implies turning the tool on; set `enabled: false` to force OFF while keeping the other options in place (e.g. `tailwind: { enabled: false, cssConfigPath: '...' }`)
47
-
48
- `defaultIgnore` and `typeAware` have nothing to auto-detect, so they are OFF unless set. `defaultIgnore` converts the `.gitignore` and `.prettierignore` sitting next to your config file (both must exist) into ESLint ignores — it needs your `import.meta.url`, so `defaultIgnore: true` alone is a hard error.
49
-
50
- `next.rootDir` is auto-detected when omitted: the directories containing a `next.config.*`. None found → the setting is simply left out (it's optional); several apps → all of them as an array.
51
-
52
- All file scans (Tailwind entry, `next.config.*`) and `nx.json` detection are anchored to the **workspace root**, not cwd — linting from inside a package (lint-staged, IDE, `yarn workspace x lint`) still sees the whole repo. The root is detected by asking the package manager (env: Yarn Berry `PROJECT_CWD`, npm `npm_config_local_prefix`; CLIs: `pnpm root -w`, Yarn Berry via `yarn node`, `npm prefix`), falling back to a lockfile walk bounded by `.git`; `findWorkspaceRoot` is exported for debugging alongside the `has*` flags. Yarn 1 (classic) provides neither a root env nor a root command — classic workspaces resolve via `npm prefix` (same package.json `workspaces` field) or the yarn.lock walk.
53
-
54
- Options can also be produced by a (possibly async) function: `defineLintConfig(() => ({ tailwind: true }))`.
55
-
56
- `defineLintConfig` returns a `Promise` — ESLint natively awaits a Promise default export, so the plain form above just works. To compose with your own blocks, `await` it:
35
+ Config can be extended, `defineLintConfig` returns a `Promise` (natively awaited by ESLint), to compose with your own blocks, `await` it:
57
36
 
58
37
  ```js
59
38
  import { defineLintConfig, includeIgnoreFile } from '@kirill.konshin/lint';
@@ -70,13 +49,82 @@ export default [
70
49
  ];
71
50
  ```
72
51
 
73
- **Every** block lives in a themed `configs/*.js` file and is exported as a standalone function for manual composition (and easy testing/mocking), in the order `defineLintConfig` applies them — blocks from the same file stay consecutive, which matters inside a family (Next: base config → the TS wiring stemming from it → overrides → settings): `baseConfig` (JS recommended + global ignores + globals + core-rule overrides), `defaultIgnoreConfig`, `nextConfig`, `typescriptOverridesConfig`, `nextOverridesConfig`, `reactSettingsConfig`, `prettierConfig`, `storybookConfig`, `typeAwareConfig` (off by default — see [Type-aware rules](#type-aware-rules); ordered before the import blocks so its naming-convention rule loses to the default-export relaxation), `importXConfig` (includes the default-export relaxation for conventional files), `importSortConfig`, `unusedImportsConfig`, `promiseConfig`, `unicornConfig`, `turboConfig`, `tailwindConfig`, `nxConfig`, `jestConfig`, `vitestConfig`, `testConfig`.
52
+ ### Full Config Example
74
53
 
75
- Tool-gated functions take the same value as their `defineLintConfig` flag and gate themselves (`tailwindConfig(true)`, `nxConfig(false)` → `[]`, `tailwindConfig({ cssConfigPath })`). `nextConfig` is a composite: `nextBaseConfig` (the pure Next blocks, also exported) when Next is enabled, the `reactConfig` fallback otherwise — both are exported for direct use too.
54
+ Default behavior in the comments, all tools are optional (see [Detection](#detection)). Enable/disable tools using:
76
55
 
77
- The package ships hand-written types (`index.d.ts`) that pull real types from the underlying packages — `Linter.Config` from `eslint`, `PluginSettings` from `eslint-plugin-tailwindcss`, `prettier`'s `Config`, `lint-staged`'s `Configuration` — so `defineLintConfig` options and all exports are fully typed in `eslint.config.mjs` (via editor inference) and `eslint.config.ts`.
56
+ - `undefined` (default) — auto-detect, see [Detection](#detection)
57
+ - `true` — force ON (use when detection misses a tool, can be useful to see the error why tool is missing)
58
+ - `false` — force OFF
59
+ - `{ /* tool options *./ }` — object configuration implies `enabled: true` even if omitted; set `enabled: false` to force OFF while keeping the other options in place, see example
60
+
61
+ ```js
62
+ import { defineLintConfig, scanWorkspace } from '@kirill.konshin/lint';
63
+
64
+ // function form shown
65
+ export default defineLintConfig(() => ({
66
+ // enabled (default true) = tools are ON unless said otherwise;
67
+ // strict (default false) = same-scope package probes only, no workspace scans and no symlink bridges
68
+ // `{ enabled: false, strict: true }` is ideal for per-package configs
69
+ detection: { enabled: true, strict: false }, // default
70
+
71
+ // ON by default; app roots auto-detected (next.config.*, package.json depending on next, src/{app,pages}/);
72
+ // can be force OFF; several apps auto-detect as array; pass the package root, not src
73
+ next: { rootDir: 'apps/web' }, // string or array
74
+
75
+ storybook: true, // force ON if detection failed
76
+ turbo: false, // force OFF
77
+ nx: true,
78
+ jest: false,
79
+ vitest: { enabled: true }, // object form implies ON; { enabled: false, ... } turns OFF keeping options
80
+
81
+ // ON by default; auto-detected single entry CSS; explicit path always wins over the scan
82
+ tailwind: { cssConfigPath: 'apps/web/src/app/index.css' },
83
+
84
+ // OFF by default
85
+ defaultIgnore: {
86
+ importMetaUrl: import.meta.url, // required, error if turned on via `defaultIgnore: true`
87
+ },
78
88
 
79
- `.prettierrc.mjs`:
89
+ // OFF by default (slow) - see "Type-aware rules"
90
+ typeAware: {
91
+ allowDefaultProject: scanWorkspace('{vite,vitest}.config.ts'), // no default; absolute paths are relativized; ** globs are not supported
92
+ maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING: 50, // defaults to the list length, (default 8), set it explicitly only when supplying multi-match globs
93
+ tsconfigRootDir: process.cwd(), // defaults to the detected workspace root
94
+ },
95
+ }));
96
+ ```
97
+
98
+ ### Per-package configs (monorepo)
99
+
100
+ ESLint 10 resolves the config **per linted file**: the nearest `eslint.config.mjs` up the tree wins **entirely** (no cascading/inheritance of rules). For full per-app Next/Tailwind linting in a multi-app monorepo, give each app its own config — either inherit the root and add overrides:
101
+
102
+ ```js
103
+ // apps/web/eslint.config.mjs
104
+ import rootConfig from '../../eslint.config.mjs';
105
+
106
+ export default [...(await rootConfig), { rules: { 'tailwindcss/no-custom-classname': 'off' } }];
107
+ ```
108
+
109
+ …or simply call `defineLintConfig` again with the options this app needs:
110
+
111
+ ```js
112
+ // apps/web/eslint.config.mjs
113
+ import { fileURLToPath } from 'node:url';
114
+ import { defineLintConfig } from '@kirill.konshin/lint';
115
+
116
+ export default defineLintConfig({
117
+ detection: { enabled: false, strict: true }, // fully explicit: this config only sees its own scope
118
+ // do not use workspace-wide auto-scan, provide exactly ONE from THIS leaf package
119
+ tailwind: { cssConfigPath: fileURLToPath(new URL('src/app/index.css', import.meta.url)) },
120
+ });
121
+ ```
122
+
123
+ ⚠️ Nearest-wins means root-only blocks (e.g. `defaultIgnore`, custom rules) do NOT apply to the subtree unless inherited or re-declared.
124
+
125
+ [Detection](#detection) runs against the **workspace root** even from a nested config, so per-app tool settings (`cssConfigPath`) should be explicit absolute paths — relative ones depend on the lint cwd.
126
+
127
+ ## Prettier `.prettierrc.mjs`:
80
128
 
81
129
  ```js
82
130
  import { prettier } from '@kirill.konshin/lint';
@@ -94,7 +142,7 @@ export default {
94
142
  };
95
143
  ```
96
144
 
97
- `.editorconfig`
145
+ ## Editor Config `.editorconfig`
98
146
 
99
147
  ```editorconfig
100
148
  root = true
@@ -129,42 +177,6 @@ indent_style = tab
129
177
  }
130
178
  ```
131
179
 
132
- ### Tailwind CSS rules
133
-
134
- When Tailwind is enabled — auto-detected via `tailwindcss` (v4+) being installed, or forced with `tailwind: true` — the config enables [`eslint-plugin-tailwindcss`](https://github.com/francoismassart/eslint-plugin-tailwindcss) recommended rules. The plugin **must** be able to resolve the Tailwind entry CSS — it hard-crashes lint (ENOENT) otherwise — so the entry is auto-detected: the workspace is scanned for `*.css` files containing `@import "tailwindcss"` (up to five directory levels below the workspace root — covers `packages/<x>/src/styles` — skipping dot dirs, `node_modules`, build outputs like `dist`/`.next`, and everything in `.gitignore`).
135
-
136
- - Exactly **one** entry found → rules enable automatically with it (added as a standalone config block, easy to override).
137
- - **Zero or several** entries:
138
- - auto-detected → nothing is added (inert); pass the entry explicitly (below)
139
- - forced (`tailwind: true`) → **hard error** — you explicitly asked for Tailwind linting, so a silent skip would be a lie
140
- - An explicit entry always wins over the scan:
141
-
142
- ```js
143
- export default defineLintConfig({
144
- tailwind: {
145
- cssConfigPath: './src/styles/tailwind.css', // relative to the package root
146
- },
147
- });
148
- ```
149
-
150
- ### Type-aware rules (optional, disabled by default for performance)
151
-
152
- Off by default (typed linting is slow); enable with `typeAware: true` or an options object.
153
-
154
- Config files living outside any tsconfig `include` (`vite.config.ts`, `.storybook/main.ts`, …) need typescript-eslint's `allowDefaultProject` — it has **no default** here, and upstream forbids `**` in its patterns, so either spell out each directory level or generate the exact file list with the exported `scanWorkspace` (workspace-root-anchored, `.gitignore`- and build-output-aware; its absolute paths are relativized against `tsconfigRootDir` automatically):
155
-
156
- ```js
157
- import { defineLintConfig, scanWorkspace } from '@kirill.konshin/lint';
158
-
159
- export default defineLintConfig({
160
- typeAware: {
161
- allowDefaultProject: scanWorkspace('{vite,vitest}.config.ts'),
162
- maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING: 50, // defaults to allowDefaultProject.length when the list is given (typescript-eslint's own default is 8) - set it explicitly only when supplying multi-match globs
163
- tsconfigRootDir: '...', // defaults to the detected workspace root
164
- },
165
- });
166
- ```
167
-
168
180
  ### IDEA settings
169
181
 
170
182
  - Eslint: `**/*.{js,jsx,ts,tsx,cjs,cts,mjs,mts,md,mdx,htm,html,vue}`
@@ -235,17 +247,6 @@ In the project root, `lint-prepare`:
235
247
 
236
248
  `init`/`update` refuse to run if `.claude/rules`, a skill target dir, or `CLAUDE.md` contains anything that isn't a symlink — this avoids silently overwriting files you created by hand. If `AGENTS.md` exists and wasn't generated by this tool, `init` skips it; use `update` to force regeneration.
237
249
 
238
- ### Rule file format
239
-
240
- ```yaml
241
- ---
242
- type: always_apply # or agent_requested
243
- description: Set of rules for projects which use Xxx # Required for agent_requested
244
- paths:
245
- - '**/*.xxx'
246
- ---
247
- ```
248
-
249
250
  ## Migration
250
251
 
251
252
  ### 0.2.x → 0.3.x
@@ -286,9 +287,9 @@ export default [
286
287
  ```
287
288
 
288
289
  - **Default export removed** — import `defineLintConfig` and call it. ESLint awaits the returned Promise, so a plain `export default defineLintConfig({...})` works when no extra blocks are needed
289
- - **Manual `settings.next.rootDir` block** → `next: { rootDir }` option — or nothing at all: it is auto-detected from `next.config.*` locations (several apps → array)
290
+ - **Manual `settings.next.rootDir` block** → `next: { rootDir }` option — or nothing at all: it is auto-detected from `next.config.*` locations, `package.json`s depending on `next`, and `src/app`/`src/pages` trees (several apps → array)
290
291
  - **Scans are workspace-root-anchored** — the Tailwind entry / `next.config.*` scans and `nx.json` detection resolve the workspace root via the package manager instead of trusting cwd, so linting from inside a package behaves like linting from the root
291
- - **Manual Tailwind block** (`settings.tailwindcss.cssConfigPath`) → `tailwind: { cssConfigPath }` option; `tailwind: true` without a resolvable entry CSS is now a **hard error** instead of a silent skip
292
+ - **Manual Tailwind block** (`settings.tailwindcss.cssConfigPath`) → `tailwind: { cssConfigPath }` option; `tailwind: true` without a resolvable entry CSS is now a **hard error** instead of a silent skip, and several entry CSS candidates are a hard error even in auto mode
292
293
  - **`includeIgnoreFile(import.meta.url, '.gitignore' / '.prettierignore')` pair** → `defaultIgnore: { importMetaUrl: import.meta.url }` (`includeIgnoreFile` stays exported for extra ignore files)
293
294
  - **`tailwindEntry` const removed** → call the exported `findTailwindEntry(ignores)` when needed
294
295
  - **New:** every block is a composable exported `*Config()` function; gated ones accept `true` / `false` / an options object with optional `enabled` (defaults to `true` in the object form); `typeAware: true` enables the (slow) type-aware rules
@@ -297,16 +298,70 @@ export default [
297
298
 
298
299
  Everything else — `prettier`, `listStaged`, extension lists (`tsExts`, …), `has*` detection exports, plugin re-exports (`nxPlugin`, …) — is unchanged.
299
300
 
300
- ## Why raw JS (no build)
301
+ ## Development
302
+
303
+ ### Why raw JS (no build)
301
304
 
302
305
  Deliberately plain ESM, **no TypeScript build**: the config is loaded by `eslint.config.mjs` and pre-commit `lint:staged` before anything is built, so a `dist/` `main` would force a build before the repo could lint — not worth it for a config package.
303
306
 
307
+ ### Eslint
308
+
309
+ The package ships hand-written types (`index.d.ts`) that pull real types from the underlying packages — `Linter.Config` from `eslint`, `PluginSettings` from `eslint-plugin-tailwindcss`, `prettier`'s `Config`, `lint-staged`'s `Configuration` — so `defineLintConfig` options and all exports are fully typed in `eslint.config.mjs` (via editor inference) and `eslint.config.ts`.
310
+
311
+ **Every** block lives in a themed `configs/*.js` file and is exported as a standalone function for manual composition (and easy testing/mocking), in the order `defineLintConfig` applies them: `baseConfig` (JS recommended + global ignores + globals + core-rule overrides), `defaultIgnoreConfig`, `reactConfig` (the whole React family, see below), `prettierConfig`, `storybookConfig`, `typeAwareConfig` (off by default; ordered before the import blocks so its naming-convention rule loses to the default-export relaxation), `importXConfig` (includes the default-export relaxation for conventional files), `importSortConfig`, `unusedImportsConfig`, `promiseConfig`, `unicornConfig`, `turboConfig`, `tailwindConfig`, `nxConfig`, `jestConfig`, `vitestConfig`, `testConfig`.
312
+
313
+ Tool-gated functions take the same value as their `defineLintConfig` flag and gate themselves (`tailwindConfig(true)`, `nxConfig(false)` → `[]`, `tailwindConfig({ cssConfigPath })`). `reactConfig(nextFlag, strict)` is the whole family in its load-bearing order — Next is just a shortcut to an opinionated React/TypeScript setup, so the TS wiring, overrides and settings apply no matter whether Next or plain React won: `nextConfig` (chooser: `nextBaseConfig` when Next is enabled, `reactBaseConfig` fallback otherwise) → `typescriptOverridesConfig` → `nextOverridesConfig` → `reactSettingsConfig` — all exported individually too.
314
+
315
+ ### Detection
316
+
317
+ Due to limitations package visibility between leaf and root this package has to be creative to support config-free detection.
318
+
319
+ 1. **Package probe** — `import.meta.resolve('<pkg>/package.json')` from this package's install location (`has<Pkg>` exported for debugging).
320
+ 2. **Evidence scan** — tool config files below the **workspace root** (≤5 directory levels, skipping dot dirs, build outputs, and `.gitignore`d files; exported as `scanWorkspace`). Catches tools installed only in **leaf** packages, invisible to the probe (1). The workspace root itself comes from the package manager (env `PROJECT_CWD`/`npm_config_local_prefix` → CLIs `pnpm root -w`, Berry `yarn node`, `npm prefix` → lockfile walk bounded by `.git`; exported as `findWorkspaceRoot`), so linting from inside a package still sees the whole repo.
321
+ 3. **Leaf bridge** — when a plugin needs the tool's package itself but it's only installed in a leaf, a symlink `<workspace root>/node_modules/<pkg>` → leaf install is created automatically (the next install prunes it, the next lint recreates it). Forcing a tool whose package resolves nowhere fails with an actionable error instead of a cryptic plugin crash.
322
+ 4. **Yarn Berry PnP quirk** — leaf resolutions point inside the zip cache (virtual paths), so the bridge is skipped and leaf-only tools degrade gracefully (auto → off, forced → actionable error). Under PnP install the tools at the workspace root as well, keeping versions in sync with the leaves (e.g. the `"vitest": "$vitest"` version-alias hack); `next` documents its own monorepo ESLint setup.
323
+
324
+ | Option | Package | Evidence glob | When zero / many found |
325
+ | ----------- | ---------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
326
+ | `tailwind` | `tailwindcss`¹ | `*.css` with `@import "tailwindcss"` | needs exactly **one**: zero → off (forced → error), several → **always** error; set `cssConfigPath` |
327
+ | `next` | `next`¹ | `next.config.*`, `package.json` depending on `next`, `src/{app,pages}/` dir | zero → no `rootDir` (optional); many → all as array; or set `rootDir` (the package root, not `src`) |
328
+ | `storybook` | `storybook`¹ | `.storybook/main.*` | presence is enough |
329
+ | `jest` | `jest`¹ | `jest.config.*` | presence is enough |
330
+ | `vitest` | `vitest`¹ | `{vitest,vite}.config.*` | presence is enough |
331
+ | `nx` | (plugin bundled) | `nx.json` at the workspace root | — |
332
+ | `turbo` | `turbo` | package probe only | — |
333
+
334
+ ¹ the plugins need the tool's package resolvable at lint time (`tailwindcss` for the theme-loading workers, `next` for `eslint-config-next`'s internal `require`s, `storybook` for its plugin's static import, `jest` for version sniffing) — covered by the leaf bridge above.
335
+
336
+ The machinery is controlled by the `detection` option (same toggle notation as the tools):
337
+
338
+ - `detection: false` — tools are OFF unless explicitly enabled; enabled tools still auto-detect their settings (steps 2–3)
339
+ - `detection: { strict: true }` — only step 1 runs: the `has*` package probes **are** the strict detection (same-scope `import.meta.resolve`, no walking) — no workspace scans (2), no symlink bridges (3). Mandatory settings (`cssConfigPath`) must then be explicit, and `nx.json` is checked at **cwd** instead of the workspace root (`hasNx` is the only non-strict `has*`)
340
+ - `detection: { enabled: false, strict: true }` — fully explicit: tools on only when set, probes only
341
+
342
+ > `basePath: 'packages/xxx'` (ESLint ≥ 9.30) can scope a config object to a directory within a single root config, but it won't help with detection — `defineLintConfig` detects once, workspace-wide (e.g. Tailwind still demands exactly one entry CSS), so per-app settings would still have to be spelled out block by block; nested configs are the cleaner tool for this.
343
+
344
+ ### Type-aware rules (optional, disabled by default for performance)
345
+
346
+ Config files living outside any tsconfig `include` (`vite.config.ts`, `.storybook/main.ts`, …) need typescript-eslint's `allowDefaultProject` — it has **no default** here, and upstream forbids `**` in its patterns, so either spell out each directory level or generate the exact file list with the exported `scanWorkspace` (workspace-root-anchored, `.gitignore`- and build-output-aware; its absolute paths are relativized against `tsconfigRootDir` automatically):
347
+
348
+ ### AI Rule file format
349
+
350
+ ```yaml
351
+ ---
352
+ type: always_apply # or agent_requested
353
+ description: Set of rules for projects which use Xxx # Required for agent_requested
354
+ paths:
355
+ - '**/*.xxx'
356
+ ---
357
+ ```
358
+
304
359
  ## Issues
305
360
 
306
361
  - Package managers
307
362
  - [ ] TODO verify the package end-to-end (workspace-root detection, Tailwind / `next.config.*` scans, `has*` capability probes, plugin resolution, `defineLintConfig` under a real lint run) with each manager:
308
363
  - [x] Yarn Berry, node-modules linker — this repo, fully covered
309
- - [ ] Yarn Berry **PnP** — entirely unverified: no `node_modules`, resolution/hoisting differs, `import.meta.resolve` probes and leaf-package detection may behave differently
364
+ - [ ] Yarn Berry **PnP** — partially verified (scratch workspace): Tailwind leaf resolution is PnP-aware but points into the zip cache, so the node_modules symlink bridge is skipped by design (see "Tailwind CSS rules"); root-declared `tailwindcss` verified working; full config run (plugin loading, capability probes) still unverified
310
365
  - [ ] Yarn 1 (classic) — workspace-root detection verified in a scratch workspace (no root env, `npm prefix`/lockfile-walk path); full config unverified
311
366
  - [ ] pnpm — workspace-root detection verified in a scratch workspace (`pnpm root -w`, no usable env); full config unverified
312
367
  - [ ] npm — root probes verified (`npm_config_local_prefix`, workspace-aware `npm prefix`); full config unverified
package/configs/nx.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
1
3
  import jsoncParser from 'jsonc-eslint-parser';
2
4
 
3
- import { asOptions, hasNx } from '../lib.js';
5
+ import { hasNx, toolGate } from '../lib.js';
4
6
 
5
7
  // lazy so consumers without Nx don't pay the load cost (it drags in a large part of nx itself) -
6
8
  // re-exported from index.js
@@ -17,10 +19,16 @@ export const nxPlugin = hasNx ? (await import('@nx/eslint-plugin')).default : nu
17
19
  * @typescript-eslint/recommended that would relitigate rules already configured deliberately here.
18
20
  *
19
21
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `nx` flag; auto-detected (workspace `nx.json`) when omitted
22
+ * @param {boolean} [strict] same-scope detection only: `nx.json` at cwd instead of the workspace root (defineLintConfig `detection.strict`)
20
23
  * @returns {Promise<import('eslint').Linter.Config[]>}
21
24
  */
22
- export async function nxConfig(option) {
23
- const { enabled = hasNx } = asOptions(option);
25
+ export async function nxConfig(option, strict = false) {
26
+ const { enabled } = toolGate(option, strict, {
27
+ tool: 'nx',
28
+ has: hasNx,
29
+ // hasNx is the one non-strict `has*` (a workspace-root file check) - strict stays at cwd
30
+ strictHas: strict && existsSync(resolve(process.cwd(), 'nx.json')),
31
+ });
24
32
  if (!enabled) return [];
25
33
  const nx = (await import('@nx/eslint-plugin')).default;
26
34
  return [
@@ -1,10 +1,12 @@
1
- import { dirname } from 'node:path';
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
2
3
  import nextTs from 'eslint-config-next/typescript';
3
4
  import jsxA11yPlugin from 'eslint-plugin-jsx-a11y';
4
5
  import reactPlugin from 'eslint-plugin-react';
5
6
  import reactHooksPlugin from 'eslint-plugin-react-hooks';
7
+ import { globSync } from 'glob';
6
8
 
7
- import { asOptions, GLOBAL_IGNORES, hasNext, scanWorkspace, tsExts } from '../lib.js';
9
+ import { findWorkspaceRoot, GLOBAL_IGNORES, hasNext, scanWorkspace, toolGate, tsExts } from '../lib.js';
8
10
 
9
11
  // lazy so consumers without Next don't pay the load cost - re-exported from index.js
10
12
  export const nextPlugin = hasNext ? (await import('@next/eslint-plugin-next')).default : null;
@@ -12,16 +14,47 @@ export const nextPlugin = hasNext ? (await import('@next/eslint-plugin-next')).d
12
14
  /** @typedef {import('../index.js').NextOptions} NextOptions Defined in index.d.ts. */
13
15
 
14
16
  /**
15
- * Auto-find Next.js app roots: every directory below the workspace root containing a
16
- * `next.config.*` (scanned like the Tailwind entry - see `scanWorkspace`).
17
+ * Does this `package.json` declare `next` as a dependency? Peer/optional declarations are
18
+ * deliberately ignored - they mark component libraries, not apps.
19
+ *
20
+ * @param {string} file absolute path of a `package.json`
21
+ * @returns {boolean}
22
+ */
23
+ function dependsOnNext(file) {
24
+ try {
25
+ const { dependencies, devDependencies } = JSON.parse(readFileSync(file, 'utf-8'));
26
+ return Boolean(dependencies?.next ?? devDependencies?.next);
27
+ } catch {
28
+ return false; // unreadable / malformed - not evidence
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Auto-find Next.js app roots below the workspace root (scanned like the Tailwind entry - see
34
+ * `scanWorkspace`). `next.config.*` is optional in Next.js, so any of three signals marks an app
35
+ * root:
36
+ * - a `next.config.*` file
37
+ * - a `package.json` depending on `next` (see {@link dependsOnNext})
38
+ * - a `src/app` or `src/pages` directory - the reported root is the directory CONTAINING `src`,
39
+ * because the plugin resolves both layouts (`pages`/`app` and `src/pages`/`src/app`) from the
40
+ * package root itself; the bare root-level dir names are too generic to scan for, but such apps
41
+ * are caught by the other two signals
17
42
  *
18
43
  * @param {string[]} ignores glob patterns to skip
19
- * @returns {string[]} absolute directories
44
+ * @returns {string[]} absolute directories, deduplicated (one app usually shows several signals) and
45
+ * sorted so the emitted settings block is deterministic across filesystems
20
46
  */
21
47
  export function findNextRoots(ignores) {
22
- // Set: a dir can hold several matches (next.config.js + next.config.ts mid-migration);
23
- // sorted so the emitted settings block is deterministic across filesystems
24
- return [...new Set(scanWorkspace('next.config.*', ignores).map((file) => dirname(file)))].sort();
48
+ return [
49
+ ...new Set([
50
+ ...scanWorkspace('next.config.*', ignores).map((file) => dirname(file)),
51
+ ...scanWorkspace('package.json', ignores)
52
+ .filter(dependsOnNext)
53
+ .map((file) => dirname(file)),
54
+ // the trailing slash makes glob match directories only
55
+ ...scanWorkspace('src/{app,pages}/', ignores).map((dir) => dirname(dirname(dir))),
56
+ ]),
57
+ ].sort();
25
58
  }
26
59
 
27
60
  /**
@@ -58,7 +91,7 @@ export async function nextBaseConfig({ rootDir = findNextRoots(GLOBAL_IGNORES) }
58
91
  *
59
92
  * @returns {import('eslint').Linter.Config[]}
60
93
  */
61
- export function reactConfig() {
94
+ export function reactBaseConfig() {
62
95
  return [
63
96
  reactPlugin.configs.flat.recommended,
64
97
  reactPlugin.configs.flat['jsx-runtime'],
@@ -68,15 +101,45 @@ export function reactConfig() {
68
101
  }
69
102
 
70
103
  /**
71
- * Composite: {@link nextBaseConfig} when Next is enabled (auto-detected or forced via the flag),
72
- * the {@link reactConfig} fallback otherwise.
104
+ * Composite: {@link nextBaseConfig} when Next is enabled, the {@link reactBaseConfig} fallback
105
+ * otherwise. Full evidence-based gate (see `toolGate` in lib.js), mirroring Tailwind: app-root
106
+ * evidence (see {@link findNextRoots} - `next.config.*`, a `package.json` depending on `next`, a
107
+ * `src/app`/`src/pages` tree) marks a Next repo even when the `next` package is installed only in
108
+ * a leaf app (invisible to `hasNext`) - and because `eslint-config-next` `require`s files INSIDE
109
+ * the `next` package, leaf-only installs are bridged from each app's own `package.json` (see
110
+ * `ensurePackageResolvable` in lib.js for the mechanism and PnP behavior).
73
111
  *
74
112
  * @param {boolean | NextOptions} [option] the defineLintConfig `next` flag
113
+ * @param {boolean} [strict] same-scope detection only - no `next.config.*` scan, no bridge (defineLintConfig `detection.strict`)
75
114
  * @returns {Promise<import('eslint').Linter.Config[]>}
76
115
  */
77
- export async function nextConfig(option) {
78
- const { enabled = hasNext, ...options } = asOptions(option);
79
- return enabled ? await nextBaseConfig(options) : reactConfig();
116
+ export async function nextConfig(option, strict = false) {
117
+ const { enabled, options, files } = toolGate(option, strict, {
118
+ tool: 'next',
119
+ has: hasNext,
120
+ packageName: 'next',
121
+ /*
122
+ * rootDir entries may be relative or absolute paths OR globs (`apps/*` - the plugin
123
+ * expands them itself for its settings), so for the bridge probes each entry is expanded
124
+ * against the workspace root into real app dirs; a plain path that exists simply matches
125
+ * itself. An entry matching nothing falls back to the literal path as the probe anchor
126
+ * (harmless - resolution just walks up from there). The probes resolve from each app's
127
+ * package.json.
128
+ */
129
+ absolutizeOptions: ({ rootDir }) =>
130
+ (Array.isArray(rootDir) ? rootDir : [rootDir]).filter(Boolean).flatMap((dir) => {
131
+ const pattern = isAbsolute(dir) ? dir : resolve(findWorkspaceRoot(), dir);
132
+ // trailing slash = directories only; backslash normalization mirrors the plugin
133
+ const dirs = globSync(`${pattern.replace(/\\/g, '/').replace(/\/+$/, '')}/`, { absolute: true });
134
+ return (dirs.length > 0 ? dirs : [pattern]).map((appDir) => join(appDir, 'package.json'));
135
+ }),
136
+ scan: () => findNextRoots(GLOBAL_IGNORES).map((dir) => join(dir, 'package.json')),
137
+ });
138
+ if (!enabled) return reactBaseConfig();
139
+
140
+ // explicit rootDir is passed through in the consumer's own notation; auto-detected roots are
141
+ // the evidence dirs (absolute; empty under strict → no settings block, the setting is optional)
142
+ return nextBaseConfig({ ...options, rootDir: options.rootDir ?? files.map((file) => dirname(file)) });
80
143
  }
81
144
 
82
145
  /**
@@ -141,7 +204,7 @@ export function typescriptOverridesConfig() {
141
204
 
142
205
  /**
143
206
  * Overrides of rules set by `eslint-config-next`. Always applied (not gated on Next): the
144
- * jsx-a11y/react entries matter for {@link reactConfig} consumers too, and turning off rules of an
207
+ * jsx-a11y/react entries matter for {@link reactBaseConfig} consumers too, and turning off rules of an
145
208
  * unregistered plugin is harmless.
146
209
  *
147
210
  * @returns {import('eslint').Linter.Config[]}
@@ -177,3 +240,23 @@ export function reactSettingsConfig() {
177
240
  },
178
241
  ];
179
242
  }
243
+
244
+ /**
245
+ * The whole React family in its load-bearing order: {@link nextConfig} (Next when enabled, plain
246
+ * React otherwise - Next is just a shortcut to an opinionated React/TypeScript setup), then
247
+ * {@link typescriptOverridesConfig}, {@link nextOverridesConfig} and {@link reactSettingsConfig} -
248
+ * which apply NO MATTER whether Next or plain React won, so composing them individually risks
249
+ * ordering mistakes; defineLintConfig uses this composite.
250
+ *
251
+ * @param {boolean | NextOptions} [option] the defineLintConfig `next` flag
252
+ * @param {boolean} [strict] same-scope detection only (defineLintConfig `detection.strict`)
253
+ * @returns {Promise<import('eslint').Linter.Config[]>}
254
+ */
255
+ export async function reactConfig(option, strict = false) {
256
+ return [
257
+ ...(await nextConfig(option, strict)),
258
+ ...typescriptOverridesConfig(),
259
+ ...nextOverridesConfig(),
260
+ ...reactSettingsConfig(),
261
+ ];
262
+ }
@@ -1,15 +1,26 @@
1
- import { asOptions, hasStorybook } from '../lib.js';
1
+ import { GLOBAL_IGNORES, hasStorybook, scanWorkspace, toolGate } from '../lib.js';
2
2
 
3
3
  /**
4
- * Storybook recommended rules. `eslint-plugin-storybook` statically imports the `storybook` package
5
- * itself, so it can only be loaded when Storybook is actually installed - hence the lazy import.
4
+ * Storybook recommended rules. Full evidence-based gate (see `toolGate` in lib.js), mirroring
5
+ * Tailwind: a `.storybook/main.*` marks a Storybook repo even when the `storybook` package is
6
+ * installed only in a leaf package (invisible to `hasStorybook`) - and because
7
+ * `eslint-plugin-storybook` statically imports the `storybook` package itself, leaf-only installs
8
+ * are bridged (see `ensurePackageResolvable` in lib.js for the mechanism and PnP behavior); the
9
+ * plugin stays lazily imported so consumers without Storybook never pay for it.
6
10
  *
7
11
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `storybook` flag; auto-detected when omitted
12
+ * @param {boolean} [strict] same-scope detection only - no `.storybook` scan, no bridge (defineLintConfig `detection.strict`)
8
13
  * @returns {Promise<import('eslint').Linter.Config[]>}
9
14
  */
10
- export async function storybookConfig(option) {
11
- const { enabled = hasStorybook } = asOptions(option);
15
+ export async function storybookConfig(option, strict = false) {
16
+ const { enabled } = toolGate(option, strict, {
17
+ tool: 'storybook',
18
+ has: hasStorybook,
19
+ packageName: 'storybook',
20
+ scan: () => scanWorkspace('.storybook/main.*', GLOBAL_IGNORES, { dot: true }),
21
+ });
12
22
  if (!enabled) return [];
23
+
13
24
  const storybookPlugin = (await import('eslint-plugin-storybook')).default;
14
25
  return storybookPlugin.configs['flat/recommended'];
15
26
  }
@@ -1,29 +1,40 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
2
3
 
3
- import { asOptions, GLOBAL_IGNORES, hasTailwind, scanWorkspace } from '../lib.js';
4
+ import { findWorkspaceRoot, GLOBAL_IGNORES, hasTailwind, scanWorkspace, toolGate } from '../lib.js';
4
5
 
5
6
  /**
6
- * Auto-find the Tailwind v4 entry CSS: the single `*.css` below the workspace root (see
7
+ * All Tailwind v4 entry CSS candidates: every `*.css` below the workspace root (see
7
8
  * `scanWorkspace` - up to five directory levels, `.gitignore`- and build-output-aware) containing
8
9
  * the Tailwind v4 marker `@import "tailwindcss"`.
9
10
  *
10
- * eslint-plugin-tailwindcss v4 loads the entry (`settings.tailwindcss.cssConfigPath`) and
11
- * HARD-CRASHES with ENOENT when it can't, so {@link tailwindConfig} only enables the plugin when
12
- * exactly one entry is found; with zero or several the consumer configures `cssConfigPath`
13
- * manually (MANDATORY for the plugin) - see README "Tailwind CSS rules".
14
- *
15
11
  * @param {string[]} ignores glob patterns to skip
16
- * @returns {string | null} absolute path of the single entry, or null when zero or several were found
12
+ * @returns {string[]} absolute paths
17
13
  */
18
- export function findTailwindEntry(ignores) {
19
- const entries = scanWorkspace('*.css', ignores).filter((file) => {
14
+ function findTailwindEntries(ignores) {
15
+ return scanWorkspace('*.css', ignores).filter((file) => {
20
16
  try {
21
17
  return /@import\s+['"]tailwindcss['"]/.test(readFileSync(file, 'utf-8'));
22
18
  } catch {
23
19
  return false;
24
20
  }
25
21
  });
22
+ }
26
23
 
24
+ /**
25
+ * Auto-find THE Tailwind v4 entry CSS ({@link findTailwindEntries} narrowed to exactly one).
26
+ *
27
+ * eslint-plugin-tailwindcss v4 loads the entry (`settings.tailwindcss.cssConfigPath`) and
28
+ * HARD-CRASHES with ENOENT when it can't, so {@link tailwindConfig} only enables the plugin when
29
+ * exactly one entry is found (`allowMultiple: false` in its gate spec); with zero or several the
30
+ * consumer must configure `cssConfigPath` manually (MANDATORY for the plugin; several candidates
31
+ * are a hard error) - see README "Detection".
32
+ *
33
+ * @param {string[]} ignores glob patterns to skip
34
+ * @returns {string | null} absolute path of the single entry, or null when zero or several were found
35
+ */
36
+ export function findTailwindEntry(ignores) {
37
+ const entries = findTailwindEntries(ignores);
27
38
  return entries.length === 1 ? entries[0] : null;
28
39
  }
29
40
 
@@ -33,34 +44,51 @@ export function findTailwindEntry(ignores) {
33
44
  * Tailwind recommended rules (warnings + `no-contradicting-classname` as error) as a standalone
34
45
  * block (simple to override wholesale).
35
46
  *
36
- * Detection alone isn't enough here: the plugin needs a resolvable entry CSS (see
37
- * {@link findTailwindEntry}). Explicit `cssConfigPath` wins; otherwise auto-find. Auto-detected +
38
- * zero-or-several entries stays inert (consumer passes the path manually), but when Tailwind was
39
- * FORCED on (`true` / options object) the consumer explicitly asked for it, so an empty/ambiguous
40
- * scan fails loudly instead of silently skipping.
47
+ * Auto-detection is driven by the entry CSS (see {@link findTailwindEntries}), not by the package
48
+ * probe: explicit `cssConfigPath` wins, otherwise auto-find. Zero entries stays inert in auto mode
49
+ * (nothing marks the repo as Tailwind) but fails loudly when Tailwind was FORCED on (`true` /
50
+ * options object) - and so does an entry whose `tailwindcss` package cannot be resolved at all.
51
+ * SEVERAL entries fail loudly even in auto mode: they prove the repo uses Tailwind, the right one
52
+ * cannot be guessed, and a silent skip would be hard to detect - pass `cssConfigPath` to pick one. Leaf-only installs (tailwindcss next to the entry but invisible from the
53
+ * workspace root, where the plugin's theme-loading workers resolve it) are bridged via
54
+ * `ensurePackageResolvable` in lib.js - see its doc for the full mechanism and PnP behavior.
41
55
  *
42
56
  * @param {boolean | TailwindOptions} [option] the defineLintConfig `tailwind` flag; auto-detected when omitted
57
+ * @param {boolean} [strict] same-scope detection only - no entry scan, no bridge (defineLintConfig `detection.strict`)
43
58
  * @returns {Promise<import('eslint').Linter.Config[]>}
44
59
  */
45
- export async function tailwindConfig(option) {
46
- const { enabled, ...options } = asOptions(option);
47
- if (!(enabled ?? hasTailwind)) return [];
48
-
49
- const { cssConfigPath = findTailwindEntry(GLOBAL_IGNORES) } = options;
60
+ export async function tailwindConfig(option, strict = false) {
61
+ /*
62
+ * Detection is evidence-based: the entry CSS marker, NOT the package probe (`needs` makes the
63
+ * evidence mandatory in the gate) - in a monorepo `tailwindcss` is often installed only in a
64
+ * leaf package and unresolvable from here, while an entry CSS with `@import "tailwindcss"` is
65
+ * unambiguous proof of a Tailwind project (`hasTailwind` stays exported for debugging).
66
+ */
67
+ const { enabled, options, files } = toolGate(option, strict, {
68
+ tool: 'tailwind',
69
+ has: hasTailwind,
70
+ packageName: 'tailwindcss',
71
+ needs: {
72
+ what: 'entry CSS',
73
+ detail:
74
+ 'single Tailwind v4 entry CSS (a *.css containing `@import "tailwindcss"`, scanned up to ' +
75
+ '5 directory levels below the workspace root)',
76
+ hint: '`tailwind: { cssConfigPath }`',
77
+ },
78
+ // the plugin takes exactly ONE entry - several scan candidates are a hard error
79
+ allowMultiple: false,
80
+ // option paths may be relative; the resolution probe needs an absolute file context
81
+ absolutizeOptions: ({ cssConfigPath }) =>
82
+ cssConfigPath
83
+ ? [isAbsolute(cssConfigPath) ? cssConfigPath : resolve(findWorkspaceRoot(), cssConfigPath)]
84
+ : [],
85
+ scan: () => findTailwindEntries(GLOBAL_IGNORES),
86
+ });
87
+ if (!enabled) return [];
50
88
 
51
- if (!cssConfigPath) {
52
- // `enabled` is only defined when the consumer explicitly turned Tailwind on - fail loudly
53
- // then; detection-driven activation (enabled === undefined) stays inert instead.
54
- if (enabled) {
55
- throw new Error(
56
- '[@kirill.konshin/lint] `tailwind` was enabled explicitly, but no single Tailwind v4 entry CSS ' +
57
- '(a *.css containing `@import "tailwindcss"`, scanned up to 5 directory levels below the ' +
58
- 'workspace root) was found - zero or several candidates. ' +
59
- 'Pass `tailwind: { cssConfigPath }` explicitly.',
60
- );
61
- }
62
- return [];
63
- }
89
+ // an explicit path is passed through in the consumer's own notation (the absolutized copy only
90
+ // served the probes); an auto-found entry is the absolute evidence file
91
+ const cssConfigPath = options.cssConfigPath ?? files[0];
64
92
 
65
93
  const tailwindPlugin = (await import('eslint-plugin-tailwindcss')).default;
66
94
  return [
@@ -13,10 +13,19 @@ import path from 'node:path';
13
13
  import vitestPlugin from '@vitest/eslint-plugin';
14
14
  import jestPlugin from 'eslint-plugin-jest';
15
15
 
16
- import { asOptions, hasJest, hasVitest, tsExts, tsExtsRaw } from '../lib.js';
16
+ import { GLOBAL_IGNORES, hasJest, hasVitest, scanWorkspace, toolGate, tsExts, tsExtsRaw } from '../lib.js';
17
17
 
18
18
  export { jestPlugin, vitestPlugin };
19
19
 
20
+ /*
21
+ * Both runners use the evidence-based `toolGate` (see lib.js): a runner config file marks the repo
22
+ * even when the runner is installed only in a leaf package (invisible to the `has*` probe), and
23
+ * the runner package itself must then be resolvable - eslint-plugin-jest sniffs the installed
24
+ * `jest` version (jest/no-deprecated-functions) - so leaf-only installs are bridged. Unlike the
25
+ * plugin-crashing tools (next/storybook/tailwind) the rules are pure AST checks that work without
26
+ * the runner, so forcing a runner on never throws (`requirePackage: false`).
27
+ */
28
+
20
29
  // derived from the shared extension list - one source of truth with the lint file globs
21
30
  const SOURCE_EXTS = tsExtsRaw.split(',').map((ext) => `.${ext}`);
22
31
  const TEST_SUFFIX = new RegExp(`\\.test\\.(${tsExtsRaw.replaceAll(',', '|')})$`);
@@ -73,8 +82,14 @@ const testColocation = {
73
82
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `jest` flag; auto-detected when omitted
74
83
  * @returns {import('eslint').Linter.Config[]}
75
84
  */
76
- export function jestConfig(option) {
77
- const { enabled = hasJest } = asOptions(option);
85
+ export function jestConfig(option, strict = false) {
86
+ const { enabled } = toolGate(option, strict, {
87
+ tool: 'jest',
88
+ has: hasJest,
89
+ packageName: 'jest',
90
+ requirePackage: false,
91
+ scan: () => scanWorkspace('jest.config.*', GLOBAL_IGNORES),
92
+ });
78
93
  if (!enabled) return [];
79
94
  return [
80
95
  {
@@ -91,8 +106,15 @@ export function jestConfig(option) {
91
106
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `vitest` flag; auto-detected when omitted
92
107
  * @returns {import('eslint').Linter.Config[]}
93
108
  */
94
- export function vitestConfig(option) {
95
- const { enabled = hasVitest } = asOptions(option);
109
+ export function vitestConfig(option, strict = false) {
110
+ const { enabled } = toolGate(option, strict, {
111
+ tool: 'vitest',
112
+ has: hasVitest,
113
+ packageName: 'vitest',
114
+ requirePackage: false,
115
+ // vitest is often configured inside vite.config.* - both count as evidence
116
+ scan: () => scanWorkspace('{vitest,vite}.config.*', GLOBAL_IGNORES),
117
+ });
96
118
  if (!enabled) return [];
97
119
  return [
98
120
  {
package/configs/turbo.js CHANGED
@@ -1,16 +1,16 @@
1
- import { asOptions, hasTurbo } from '../lib.js';
1
+ import { hasTurbo, toolGate } from '../lib.js';
2
2
 
3
3
  // lazy so consumers without Turbo don't pay the load cost - re-exported from index.js
4
4
  export const turboPlugin = hasTurbo ? (await import('eslint-plugin-turbo')).default : null;
5
5
 
6
6
  /**
7
- * Turborepo rules.
7
+ * Turborepo rules. Probe-only gate (see `toolGate` in lib.js) - no evidence scan, no bridge.
8
8
  *
9
9
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `turbo` flag; auto-detected when omitted
10
10
  * @returns {Promise<import('eslint').Linter.Config[]>}
11
11
  */
12
12
  export async function turboConfig(option) {
13
- const { enabled = hasTurbo } = asOptions(option);
13
+ const { enabled } = toolGate(option, false, { tool: 'turbo', has: hasTurbo });
14
14
  if (!enabled) return [];
15
15
  const turbo = (await import('eslint-plugin-turbo')).default;
16
16
  return [
@@ -22,14 +22,15 @@ import { asOptions, findWorkspaceRoot } from '../lib.js';
22
22
  * nothing to auto-detect, so only an explicit `true` / options object enables the block
23
23
  * @returns {import('eslint').Linter.Config[]}
24
24
  */
25
- export function typeAwareConfig(option) {
25
+ export function typeAwareConfig(option, strict = false) {
26
26
  let {
27
27
  enabled = false,
28
28
  allowDefaultProject,
29
29
  // matches the list when it's exact files (the scanWorkspace flow); with multi-match globs
30
30
  // set the cap explicitly - typescript-eslint errors loudly when matches exceed it
31
31
  maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING = allowDefaultProject?.length,
32
- tsconfigRootDir = findWorkspaceRoot(),
32
+ // strict detection avoids the workspace walk
33
+ tsconfigRootDir = strict ? process.cwd() : findWorkspaceRoot(),
33
34
  } = asOptions(option);
34
35
  if (!enabled) return [];
35
36
 
package/index.d.ts CHANGED
@@ -25,13 +25,31 @@ export type ToggleOptions = {
25
25
  enabled?: boolean;
26
26
  };
27
27
 
28
+ /**
29
+ * Detection behavior ({@link defineLintConfig} `detection`) - the same toggle notation as the
30
+ * tool flags:
31
+ * - `undefined` / `true` / `{}` - tools default ON via full auto-detection
32
+ * - `false` / `{ enabled: false }` - tools default OFF; explicitly enabled tools still
33
+ * auto-detect their settings
34
+ * - `strict: true` - same-scope package probes only (exactly what the `has*` checks are): no
35
+ * workspace walks, no evidence scans, no symlink bridges; mandatory settings like
36
+ * `cssConfigPath` must be explicit, and `nx.json` is checked at cwd instead of the workspace
37
+ * root. `{ enabled: false, strict: true }` is ideal for per-package monorepo configs.
38
+ */
39
+ export type DetectionOptions = ToggleOptions & {
40
+ /** same-scope package probes only - no workspace walks/scans/bridges */
41
+ strict?: boolean;
42
+ };
43
+
28
44
  /** Options for the Next.js blocks ({@link nextBaseConfig}). */
29
45
  export type NextOptions = ToggleOptions & {
30
46
  /**
31
47
  * Root of the Next.js app(s) for `@next/eslint-plugin-next` (`settings.next.rootDir`) - needed
32
48
  * when the apps don't live at the workspace root, e.g. `path/to/next-app` (globs are supported
33
- * by the plugin). When omitted, auto-detected via {@link findNextRoots}: no `next.config.*`
34
- * found → no settings (the setting is optional), several apps → all of them as an array.
49
+ * by the plugin; pass the package root, not `src` - the plugin resolves both the `pages`/`app`
50
+ * and `src/pages`/`src/app` layouts from it). When omitted, auto-detected via
51
+ * {@link findNextRoots}: no evidence found → no settings (the setting is optional), several
52
+ * apps → all of them as an array.
35
53
  *
36
54
  * @see https://nextjs.org/docs/app/api-reference/config/eslint
37
55
  */
@@ -86,6 +104,8 @@ export type DefaultIgnoreOptions = ToggleOptions & {
86
104
  * The gated `*Config()` block functions accept the same flag value directly.
87
105
  */
88
106
  export type LintOptions = {
107
+ /** Detection behavior: default tool state + strict mode; see {@link DetectionOptions} */
108
+ detection?: boolean | DetectionOptions;
89
109
  /** Next.js (`eslint-config-next`); when off, generic React/JSX rules apply instead */
90
110
  next?: boolean | NextOptions;
91
111
  /** Storybook (`eslint-plugin-storybook`) */
@@ -98,7 +118,7 @@ export type LintOptions = {
98
118
  jest?: boolean | ToggleOptions;
99
119
  /** Vitest recommended rules for `*.{test,spec}.*` */
100
120
  vitest?: boolean | ToggleOptions;
101
- /** Tailwind (`eslint-plugin-tailwindcss`); forcing ON without a resolvable entry CSS is a hard error */
121
+ /** Tailwind (`eslint-plugin-tailwindcss`); forcing ON without a resolvable entry CSS is a hard error, several entry CSS candidates always are */
102
122
  tailwind?: boolean | TailwindOptions;
103
123
  /** Type-aware TypeScript rules; off by default (slow), nothing to auto-detect */
104
124
  typeAware?: boolean | TypeAwareOptions;
@@ -129,9 +149,16 @@ export function defaultIgnoreConfig(option?: boolean | DefaultIgnoreOptions): Li
129
149
  /** The whole `eslint-config-next` flat config, plus `settings.next.rootDir` when given. Next-only, ungated. */
130
150
  export function nextBaseConfig(options?: NextOptions): Promise<Linter.Config[]>;
131
151
  /** React/React Hooks/jsx-a11y rules for non-Next (e.g. Vite) React projects. Ungated. */
132
- export function reactConfig(): Linter.Config[];
133
- /** Composite: {@link nextBaseConfig} when Next is enabled, the {@link reactConfig} fallback otherwise. */
134
- export function nextConfig(option?: boolean | NextOptions): Promise<Linter.Config[]>;
152
+ export function reactBaseConfig(): Linter.Config[];
153
+ /** Chooser: {@link nextBaseConfig} when Next is enabled, the {@link reactBaseConfig} fallback otherwise. */
154
+ export function nextConfig(option?: boolean | NextOptions, strict?: boolean): Promise<Linter.Config[]>;
155
+ /**
156
+ * The whole React family in its load-bearing order - {@link nextConfig} (Next is just a shortcut
157
+ * to an opinionated React/TypeScript setup), then {@link typescriptOverridesConfig},
158
+ * {@link nextOverridesConfig} and {@link reactSettingsConfig}, which apply no matter whether Next
159
+ * or plain React won. Used by {@link defineLintConfig}; `option` is the `next` flag.
160
+ */
161
+ export function reactConfig(option?: boolean | NextOptions, strict?: boolean): Promise<Linter.Config[]>;
135
162
  /** `eslint-config-next/typescript` (typescript-eslint wiring, which stems from Next) + deliberate rule overrides. */
136
163
  export function typescriptOverridesConfig(): Linter.Config[];
137
164
  /** Overrides of rules set by `eslint-config-next` (always applied, harmless without Next). */
@@ -141,7 +168,7 @@ export function reactSettingsConfig(): Linter.Config[];
141
168
  /** Prettier compatibility (`eslint-config-prettier/flat`). */
142
169
  export function prettierConfig(): Linter.Config[];
143
170
  /** Storybook recommended rules. */
144
- export function storybookConfig(option?: boolean | ToggleOptions): Promise<Linter.Config[]>;
171
+ export function storybookConfig(option?: boolean | ToggleOptions, strict?: boolean): Promise<Linter.Config[]>;
145
172
  /** eslint-plugin-import-x recommended rules + overrides + the default-export relaxation for conventional files. */
146
173
  export function importXConfig(): Linter.Config[];
147
174
  /** Deterministic import ordering (eslint-plugin-simple-import-sort). */
@@ -153,21 +180,21 @@ export function promiseConfig(): Linter.Config[];
153
180
  /** Filename casing + node: protocol (two hand-picked unicorn rules). */
154
181
  export function unicornConfig(): Linter.Config[];
155
182
  /** Type-aware rules via typescript-eslint's projectService; off unless the flag is set (nothing to auto-detect). */
156
- export function typeAwareConfig(option?: boolean | TypeAwareOptions): Linter.Config[];
183
+ export function typeAwareConfig(option?: boolean | TypeAwareOptions, strict?: boolean): Linter.Config[];
157
184
  /** Turborepo rules. */
158
185
  export function turboConfig(option?: boolean | ToggleOptions): Promise<Linter.Config[]>;
159
186
  /**
160
187
  * Tailwind recommended rules. Explicit `cssConfigPath` wins; otherwise auto-found via
161
- * {@link findTailwindEntry}. Forced on (`true`/options) + zero-or-ambiguous scan throws;
162
- * auto-detected stays inert.
188
+ * {@link findTailwindEntry}. Zero entries: inert when auto-detected, throws when forced on
189
+ * (`true`/options). Several entries ALWAYS throw - pass `cssConfigPath` to pick one.
163
190
  */
164
- export function tailwindConfig(option?: boolean | TailwindOptions): Promise<Linter.Config[]>;
191
+ export function tailwindConfig(option?: boolean | TailwindOptions, strict?: boolean): Promise<Linter.Config[]>;
165
192
  /** Nx plugin registration + `@nx/dependency-checks`. */
166
- export function nxConfig(option?: boolean | ToggleOptions): Promise<Linter.Config[]>;
193
+ export function nxConfig(option?: boolean | ToggleOptions, strict?: boolean): Promise<Linter.Config[]>;
167
194
  /** Jest recommended rules, scoped to test files. */
168
- export function jestConfig(option?: boolean | ToggleOptions): Linter.Config[];
195
+ export function jestConfig(option?: boolean | ToggleOptions, strict?: boolean): Linter.Config[];
169
196
  /** Vitest recommended rules + globals, scoped to test files. */
170
- export function vitestConfig(option?: boolean | ToggleOptions): Linter.Config[];
197
+ export function vitestConfig(option?: boolean | ToggleOptions, strict?: boolean): Linter.Config[];
171
198
  /** Runner-agnostic test rules (consistent-test-it, test colocation). Always applied. */
172
199
  export function testConfig(): Linter.Config[];
173
200
 
@@ -218,18 +245,21 @@ export const vitestPlugin: typeof import('@vitest/eslint-plugin').default;
218
245
  export function findTailwindEntry(ignores: string[]): string | null;
219
246
 
220
247
  /**
221
- * Auto-find Next.js app roots: every directory below the workspace root (scanned up to 5 levels,
222
- * skipping `.gitignore`d files and build outputs) containing a `next.config.*`; deduplicated and
223
- * sorted.
248
+ * Auto-find Next.js app roots below the workspace root (scanned up to 5 levels, skipping
249
+ * `.gitignore`d files and build outputs). `next.config.*` is optional in Next.js, so any of three
250
+ * signals marks an app root: a `next.config.*`, a `package.json` depending on `next`
251
+ * (dependencies/devDependencies - peer declarations mark libraries, not apps), or a
252
+ * `src/app`/`src/pages` directory (the reported root is the directory containing `src`);
253
+ * deduplicated and sorted.
224
254
  */
225
255
  export function findNextRoots(ignores: string[]): string[];
226
256
 
227
257
  /**
228
258
  * Glob for config-file candidates below the workspace root (up to 5 directory levels, skipping
229
- * dot dirs, build outputs, extra `ignores` and everything in the root `.gitignore`). Returns
230
- * absolute paths - useful for building file lists like `typeAware.allowDefaultProject`.
259
+ * dot dirs unless `dot`, build outputs, extra `ignores` and everything in the root `.gitignore`).
260
+ * Returns absolute paths - useful for building file lists like `typeAware.allowDefaultProject`.
231
261
  */
232
- export function scanWorkspace(fileGlob: string, ignores?: string[]): string[];
262
+ export function scanWorkspace(fileGlob: string, ignores?: string[], options?: { dot?: boolean }): string[];
233
263
 
234
264
  /** Convert an ignore file (`.gitignore`, `.prettierignore`) into an ESLint ignores block. */
235
265
  export function includeIgnoreFile(importMetaUrl: string, ignoreFile: string): Linter.Config;
package/index.js CHANGED
@@ -17,21 +17,21 @@
17
17
  */
18
18
  import { baseConfig, defaultIgnoreConfig } from './configs/base.js';
19
19
  import { importSortConfig, importXConfig, unusedImportsConfig } from './configs/imports.js';
20
- import { nextConfig, nextOverridesConfig, reactSettingsConfig, typescriptOverridesConfig } from './configs/next.js';
21
20
  import { nxConfig } from './configs/nx.js';
22
21
  import { prettierConfig } from './configs/prettier.js';
23
22
  import { promiseConfig } from './configs/promise.js';
23
+ import { reactConfig } from './configs/react.js';
24
24
  import { storybookConfig } from './configs/storybook.js';
25
25
  import { tailwindConfig } from './configs/tailwind.js';
26
26
  import { jestConfig, testConfig, vitestConfig } from './configs/testing.js';
27
27
  import { turboConfig } from './configs/turbo.js';
28
28
  import { typeAwareConfig } from './configs/typescriptTypeAware.js';
29
29
  import { unicornConfig } from './configs/unicorn.js';
30
- import { eslintExts, prettierExts } from './lib.js';
30
+ import { asOptions, eslintExts, prettierExts } from './lib.js';
31
31
 
32
32
  export * from './configs/base.js';
33
33
  export * from './configs/imports.js';
34
- export * from './configs/next.js';
34
+ export * from './configs/react.js';
35
35
  export * from './configs/nx.js';
36
36
  export * from './configs/prettier.js';
37
37
  export * from './configs/promise.js';
@@ -82,23 +82,30 @@ export async function defineLintConfig(options = {}) {
82
82
  if (typeof options === 'function') options = options();
83
83
  options = (await options) ?? {};
84
84
 
85
+ /*
86
+ * `detection` uses the same toggle notation as the tool flags (true <> { enabled: true } <>
87
+ * false <> { enabled: false }): `enabled` = are tools ON unless said otherwise (default true),
88
+ * `strict` = same-scope package probes only, no workspace scans / symlink bridges (default
89
+ * false; ideal for per-package monorepo configs).
90
+ */
91
+ const { enabled: defaultOn = true, strict = false } = asOptions(options.detection);
92
+ // with detection off, tools not mentioned explicitly are OFF instead of auto-detected
93
+ const flag = (option) => (option === undefined && !defaultOn ? false : option);
94
+
85
95
  // blocks from the same configs/* file stay consecutive - ordering inside a family matters
86
96
  // (e.g. next: base config, then the TS wiring stemming from it, then overrides, then settings)
87
97
  return [
88
98
  // base.js
89
99
  ...baseConfig(),
90
100
  ...defaultIgnoreConfig(options.defaultIgnore),
91
- // next.js
92
- ...(await nextConfig(options.next)),
93
- ...typescriptOverridesConfig(),
94
- ...nextOverridesConfig(),
95
- ...reactSettingsConfig(),
101
+ // react.js - the whole family (Next or plain React + TS wiring + overrides + settings)
102
+ ...(await reactConfig(flag(options.next), strict)),
96
103
  // prettier.js
97
104
  ...prettierConfig(),
98
105
  // storybook.js
99
- ...(await storybookConfig(options.storybook)),
106
+ ...(await storybookConfig(flag(options.storybook), strict)),
100
107
  // typescriptTypeAware (should be before imports)
101
- ...typeAwareConfig(options.typeAware),
108
+ ...typeAwareConfig(options.typeAware, strict),
102
109
  // imports.js
103
110
  ...importXConfig(),
104
111
  ...importSortConfig(),
@@ -108,14 +115,14 @@ export async function defineLintConfig(options = {}) {
108
115
  // unicorn.js
109
116
  ...unicornConfig(),
110
117
  // turbo.js
111
- ...(await turboConfig(options.turbo)),
118
+ ...(await turboConfig(flag(options.turbo))),
112
119
  // tailwind.js
113
- ...(await tailwindConfig(options.tailwind)),
120
+ ...(await tailwindConfig(flag(options.tailwind), strict)),
114
121
  // nx.js
115
- ...(await nxConfig(options.nx)),
122
+ ...(await nxConfig(flag(options.nx), strict)),
116
123
  // testing.js
117
- ...jestConfig(options.jest),
118
- ...vitestConfig(options.vitest),
124
+ ...jestConfig(flag(options.jest), strict),
125
+ ...vitestConfig(flag(options.vitest), strict),
119
126
  ...testConfig(),
120
127
  ];
121
128
  }
package/lib.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { execSync } from 'node:child_process';
2
- import { existsSync } from 'node:fs';
3
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
2
+ import { existsSync, lstatSync, mkdirSync, symlinkSync, unlinkSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
5
  import { includeIgnoreFile as includeIgnoreFileCompat } from '@eslint/compat';
5
6
  import { globSync } from 'glob';
6
7
 
@@ -170,9 +171,18 @@ export function findWorkspaceRoot(cwd = process.cwd()) {
170
171
  /*
171
172
  * Build outputs regularly contain COPIES of the scanned files (compiled css, a next.config.js in a
172
173
  * published dist) and would poison the scans even in repos that don't gitignore them. Scan-only -
173
- * GLOBAL_IGNORES stays the deliberate lint-wide list.
174
+ * GLOBAL_IGNORES stays the deliberate lint-wide list. `.git` matters for `dot: true` scans.
174
175
  */
175
- const SCAN_IGNORES = ['**/dist', '**/build', '**/out', '**/coverage', '**/.next', '**/.expo', '**/storybook-static'];
176
+ const SCAN_IGNORES = [
177
+ '**/dist',
178
+ '**/build',
179
+ '**/out',
180
+ '**/coverage',
181
+ '**/.next',
182
+ '**/.expo',
183
+ '**/storybook-static',
184
+ '**/.git',
185
+ ];
176
186
 
177
187
  // glob's maxDepth counts path segments INCLUDING the filename (verified empirically): 6 → files up
178
188
  // to five directory levels below the root, covering packages/<x>/src/styles and apps/<group>/<app>
@@ -187,9 +197,10 @@ const SCAN_DEPTH = 6;
187
197
  *
188
198
  * @param {string} fileGlob e.g. `'*.css'`, `'next.config.*'`
189
199
  * @param {string[]} [ignores] extra glob patterns to skip
200
+ * @param {{ dot?: boolean }} [options] `dot` also scans dot directories (e.g. `.storybook`)
190
201
  * @returns {string[]} absolute paths
191
202
  */
192
- export function scanWorkspace(fileGlob, ignores = []) {
203
+ export function scanWorkspace(fileGlob, ignores = [], { dot = false } = {}) {
193
204
  const root = findWorkspaceRoot();
194
205
 
195
206
  let gitignored = [];
@@ -214,9 +225,81 @@ export function scanWorkspace(fileGlob, ignores = []) {
214
225
  maxDepth: SCAN_DEPTH,
215
226
  ignore,
216
227
  absolute: true,
228
+ dot,
217
229
  });
218
230
  }
219
231
 
232
+ /**
233
+ * Make sure `packageName` will be resolvable for the ESLint plugins that need it at lint time.
234
+ *
235
+ * In a monorepo a tool is often installed only in the LEAF package that uses it - invisible both
236
+ * to the `has*` probes and to the plugins' own resolution: eslint-plugin-tailwindcss's workers
237
+ * call local-pkg's `getPackageInfoSync('tailwindcss')`, whose resolver is anchored at
238
+ * process.cwd() (verified empirically: NOT the module location, and NODE_PATH is ignored);
239
+ * `eslint-config-next` `require`s files INSIDE the `next` package; `eslint-plugin-storybook`
240
+ * statically imports `storybook`; `eslint-plugin-jest` sniffs the installed `jest` version.
241
+ * Bridge: resolve the package from `fromFile`'s own package context (createRequire follows the
242
+ * leaf's dependencies and is PnP-aware) and symlink
243
+ * `<workspace root>/node_modules/<packageName>` to it - every resolution walk inside the repo
244
+ * passes the root node_modules, so one link fixes all cwds. The package manager prunes the link
245
+ * on the next install; it is simply recreated on the next lint. Nothing is touched when the
246
+ * package is already resolvable via the normal chain.
247
+ *
248
+ * Yarn Berry PnP (verified in a scratch PnP workspace): the leaf resolution succeeds but points
249
+ * INSIDE the zip cache - a virtual path a symlink cannot reach - so the bridge is skipped (the
250
+ * target-exists guard) and the function reports `false`; under PnP the tools must be declared at
251
+ * the workspace root instead (verified working - see README).
252
+ *
253
+ * @param {string} packageName e.g. `'tailwindcss'`, `'next'`, `'storybook'`
254
+ * @param {string} fromFile absolute path of a file owned by the leaf package (entry CSS, `next.config.*`, ...)
255
+ * @param {boolean} chainResolvable whether the package already resolves via the normal chain (the `has*` probe)
256
+ * @returns {boolean} the package is resolvable for the plugins (possibly after bridging)
257
+ */
258
+ export function ensurePackageResolvable(packageName, fromFile, chainResolvable) {
259
+ let leafPackageJson = null;
260
+ try {
261
+ leafPackageJson = createRequire(fromFile).resolve(`${packageName}/package.json`);
262
+ } catch {
263
+ // not a dependency of the leaf either
264
+ }
265
+ if (!leafPackageJson) return chainResolvable;
266
+ if (chainResolvable) return true;
267
+
268
+ const leafPackageDir = dirname(leafPackageJson);
269
+ if (!existsSync(leafPackageDir)) return false; // PnP zip cache - virtual path, nothing to symlink to
270
+
271
+ const bridge = join(findWorkspaceRoot(), 'node_modules', ...packageName.split('/'));
272
+
273
+ let existing;
274
+ try {
275
+ existing = lstatSync(bridge);
276
+ } catch {
277
+ // nothing at the bridge path
278
+ }
279
+
280
+ // heal a stale bridge left over from a previous layout (symlink whose target is gone)
281
+ if (existing?.isSymbolicLink() && !existsSync(bridge)) {
282
+ try {
283
+ unlinkSync(bridge);
284
+ existing = undefined;
285
+ } catch {
286
+ // fall through - the existsSync() verdict below stays authoritative
287
+ }
288
+ }
289
+
290
+ if (!existing) {
291
+ try {
292
+ mkdirSync(dirname(bridge), { recursive: true }); // scoped packages need the @scope dir
293
+ // 'junction' for Windows (no admin rights needed); ignored on POSIX
294
+ symlinkSync(leafPackageDir, bridge, 'junction');
295
+ } catch {
296
+ // best effort - verdict below
297
+ }
298
+ }
299
+
300
+ return existsSync(bridge);
301
+ }
302
+
220
303
  /*
221
304
  * Capability detection, exported for debugging. Package probes resolve from THIS package's install
222
305
  * location, so in a monorepo where a tool lives only in leaf packages (not in the root
@@ -248,3 +331,119 @@ export function asOptions(option) {
248
331
  if (typeof option === 'object' && option !== null) return { enabled: true, ...option };
249
332
  return {};
250
333
  }
334
+
335
+ /**
336
+ * Shared activation gate of the tool-scoped config blocks (next, storybook, turbo, nx, jest,
337
+ * vitest, tailwind) - the one decision every block repeats: is the tool ON, and can its plugin
338
+ * actually run. The `configs/*.js` functions keep only their tool-specific parts (which blocks to
339
+ * emit, how the evidence feeds settings) and differ solely in the spec they pass here.
340
+ *
341
+ * Decision flow:
342
+ * - `enabled: false` → off, always.
343
+ * - strict (defineLintConfig `detection.strict`): the same-scope probe gates (`strictHas`,
344
+ * defaulting to `has`); `scan` never runs and nothing is bridged, but `absolutizeOptions` evidence
345
+ * still counts. A tool that is ON while its package is unresolvable (`requirePackage`) or its
346
+ * mandatory evidence is missing (`needs`) throws instead of producing a config that crashes at
347
+ * lint time.
348
+ * - non-strict: evidence-based detection - `absolutizeOptions(options)` wins over the `scan()`
349
+ * auto-discovery; the tool is detected when the package probe hits or evidence exists (`needs`
350
+ * makes evidence mandatory even when the probe hits). Leaf-only installs are bridged from the
351
+ * evidence files via {@link ensurePackageResolvable}; an unresolvable package turns detection
352
+ * off silently but fails loudly when the tool was forced on (and `requirePackage` holds).
353
+ *
354
+ * @param {boolean | { enabled?: boolean } | undefined} option the tool's defineLintConfig flag
355
+ * @param {boolean} strict same-scope detection only (defineLintConfig `detection.strict`)
356
+ * @param {object} spec
357
+ * @param {string} spec.tool flag name, used in error messages
358
+ * @param {boolean} spec.has module-load package probe (chain resolvability, see the `has*` exports)
359
+ * @param {boolean} [spec.strictHas] strict-mode detection gate when it differs from `has` (nx: `nx.json` at cwd)
360
+ * @param {string} [spec.packageName] package the tool's plugin needs resolvable at lint time - enables the leaf bridge from the evidence files
361
+ * @param {boolean} [spec.requirePackage] fail loudly when the tool is ON but `packageName` is unresolvable; defaults to `packageName` being set - pass `false` when the plugin works without the tool installed (jest/vitest)
362
+ * @param {(options: object) => string[]} [spec.absolutizeOptions] evidence files derived from the options (absolute anchor paths for the package probes - the anchor itself need not exist, resolution walks up from its directory; allowed under strict)
363
+ * @param {() => string[]} [spec.scan] evidence auto-discovery below the workspace root (absolute paths; never runs under strict or when `absolutizeOptions` produced files)
364
+ * @param {boolean} [spec.allowMultiple] whether several evidence files are usable (default true - next supports several apps); when `false` several candidates are ALWAYS a hard error, even in auto mode - the right one cannot be guessed (tailwind's single entry CSS) and a silent skip of a tool that is evidently present would be hard to detect; zero candidates keeps the usual `needs` behavior
365
+ * @param {{ what: string, detail: string, hint: string }} [spec.needs] makes evidence MANDATORY (the plugin crashes without it - tailwind's entry CSS): detection without evidence stays inert even when `has` hits, forcing the tool on without it throws
366
+ * @returns {{ enabled: boolean, options: object, files: string[] }} the verdict, the normalized options (without `enabled`) and the evidence files
367
+ */
368
+ export function toolGate(option, strict, spec) {
369
+ const { enabled, ...options } = asOptions(option);
370
+ const off = { enabled: false, options, files: [] };
371
+ if (enabled === false) return off;
372
+
373
+ const {
374
+ tool,
375
+ has,
376
+ strictHas = has,
377
+ packageName,
378
+ requirePackage = Boolean(packageName),
379
+ absolutizeOptions,
380
+ scan,
381
+ allowMultiple = true,
382
+ needs,
383
+ } = spec;
384
+ const prefix = `[@kirill.konshin/lint] \`${tool}\``;
385
+ /*
386
+ * Several candidates with allowMultiple off are a hard error even in auto mode: the evidence
387
+ * proves the tool IS in use, the right candidate is unknowable, and silently skipping a tool
388
+ * that is evidently present would be hard to detect.
389
+ */
390
+ const usable = (candidates) => {
391
+ if (!allowMultiple && candidates.length > 1) {
392
+ const fix = needs ? `pass ${needs.hint} to pick one, or set` : `set`;
393
+ throw new Error(
394
+ `${prefix} found several ${needs?.what ?? 'evidence'} candidates and cannot pick one - ` +
395
+ `${fix} \`${tool}: false\`:\n${candidates.map((file) => ` - ${file}`).join('\n')}`,
396
+ );
397
+ }
398
+ return candidates;
399
+ };
400
+
401
+ if (strict) {
402
+ if (!(enabled ?? strictHas)) return off;
403
+ if (requirePackage && !has) {
404
+ throw new Error(
405
+ `${prefix} is on under strict detection, but the \`${packageName}\` package is not ` +
406
+ `resolvable at this scope - install it here or set \`${tool}: false\`.`,
407
+ );
408
+ }
409
+ const files = usable(absolutizeOptions?.(options) ?? []);
410
+ if (needs && files.length === 0) {
411
+ throw new Error(
412
+ `${prefix} is on under strict detection, which cannot scan for the ${needs.what} - ` +
413
+ `pass ${needs.hint} or set \`${tool}: false\`.`,
414
+ );
415
+ }
416
+ return { enabled: true, options, files };
417
+ }
418
+
419
+ const optionFiles = absolutizeOptions?.(options) ?? [];
420
+ const files = usable(optionFiles.length > 0 ? optionFiles : (scan?.() ?? []));
421
+
422
+ if (needs && files.length === 0) {
423
+ // `enabled` is only defined when the consumer explicitly turned the tool on - fail loudly
424
+ // then; detection-driven activation (enabled === undefined) stays inert instead.
425
+ if (enabled) {
426
+ throw new Error(
427
+ `${prefix} was enabled explicitly, but no ${needs.detail} was found - zero or several ` +
428
+ `candidates. Pass ${needs.hint} explicitly.`,
429
+ );
430
+ }
431
+ return off;
432
+ }
433
+
434
+ if (!(enabled ?? (has || files.length > 0))) return off;
435
+
436
+ const resolvable = !packageName || has || files.some((file) => ensurePackageResolvable(packageName, file, has));
437
+ if (!resolvable) {
438
+ if (enabled && requirePackage) {
439
+ throw new Error(
440
+ `${prefix} is enabled, but the \`${packageName}\` package is resolvable neither from the ` +
441
+ `workspace root nor from the detected evidence locations - install \`${packageName}\` ` +
442
+ `in the package that owns them or at the workspace root.`,
443
+ );
444
+ }
445
+ if (!enabled) return off;
446
+ }
447
+
448
+ return { enabled: true, options, files };
449
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kirill.konshin/lint",
3
3
  "description": "ESLint + Prettier + lint-staged config and AI agent rules/skills for monorepos",
4
- "version": "0.3.0",
4
+ "version": "0.3.1",
5
5
  "type": "module",
6
6
  "skipGenerate": true,
7
7
  "bin": {
package/rules/tailwind.md CHANGED
@@ -10,8 +10,11 @@ description: Set of rules for projects which use Tailwind
10
10
  # ESLint (eslint-plugin-tailwindcss, bundled with @kirill.konshin/lint)
11
11
 
12
12
  - The plugin MUST be able to resolve the Tailwind entry CSS or it hard-crashes lint (ENOENT)
13
- - Zero-config happy path: when `tailwindcss` is installed and the workspace contains exactly ONE `*.css` with `@import "tailwindcss"` (scanned ≤3 dir levels, `.gitignore`-aware), rules auto-enable with that entry
14
- - When detection can't see `tailwindcss` (e.g. it lives only in leaf packages of a monorepo), force it with `tailwind: true` — then a missing/ambiguous entry CSS is a HARD ERROR instead of a silent skip
13
+ - Zero-config happy path: when the workspace contains exactly ONE `*.css` with `@import "tailwindcss"` (scanned ≤5 dir levels, `.gitignore`-aware), rules auto-enable with that entry
14
+ - Several entry CSS candidates are ALWAYS a HARD ERROR (a silent skip is hard to notice)
15
+ - pass `cssConfigPath` to pick one (if others are not useful) OR
16
+ - create multiple leaf `eslint.config.ts` per app (if ALL need to be linted)
17
+ - When detection can't see `tailwindcss` (e.g. it lives only in leaf packages of a monorepo), force it with `tailwind: true` — then a missing entry CSS is a HARD ERROR instead of a silent skip
15
18
  - ONLY when auto-find finds nothing (or several entries) pass the MANDATORY entry explicitly in `eslint.config.mjs`:
16
19
 
17
20
  ```js