@kirill.konshin/lint 0.3.0 → 0.3.2

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,84 @@ 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 evidence scans
68
+ // `{ enabled: false, strict: true }` is ideal for per-package configs
69
+ detection: { enabled: true, strict: false }, // default
78
70
 
79
- `.prettierrc.mjs`:
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
+ },
88
+
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
+ The Tailwind block auto-scopes to the **workspace package** owning the entry CSS (emitted as the block's `basePath`), so a single root config doesn't flag class-like strings in non-Tailwind packages; pass `tailwind: { scoped: false }` to apply it workspace-wide (no-op when the entry is owned by the workspace root itself).
128
+
129
+ ## Prettier `.prettierrc.mjs`:
80
130
 
81
131
  ```js
82
132
  import { prettier } from '@kirill.konshin/lint';
@@ -94,7 +144,7 @@ export default {
94
144
  };
95
145
  ```
96
146
 
97
- `.editorconfig`
147
+ ## Editor Config `.editorconfig`
98
148
 
99
149
  ```editorconfig
100
150
  root = true
@@ -129,42 +179,6 @@ indent_style = tab
129
179
  }
130
180
  ```
131
181
 
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
182
  ### IDEA settings
169
183
 
170
184
  - Eslint: `**/*.{js,jsx,ts,tsx,cjs,cts,mjs,mts,md,mdx,htm,html,vue}`
@@ -235,17 +249,6 @@ In the project root, `lint-prepare`:
235
249
 
236
250
  `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
251
 
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
252
  ## Migration
250
253
 
251
254
  ### 0.2.x → 0.3.x
@@ -286,30 +289,89 @@ export default [
286
289
  ```
287
290
 
288
291
  - **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)
292
+ - **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
293
  - **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
294
+ - **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
295
  - **`includeIgnoreFile(import.meta.url, '.gitignore' / '.prettierignore')` pair** → `defaultIgnore: { importMetaUrl: import.meta.url }` (`includeIgnoreFile` stays exported for extra ignore files)
293
296
  - **`tailwindEntry` const removed** → call the exported `findTailwindEntry(ignores)` when needed
294
297
  - **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
295
298
  - **`prettier` is now a declared (required) peer dependency** — it was always required by the setup, so no action needed in practice
296
299
  - **TypeScript consumers get real types** — `index.d.ts` ships with the package (`LintOptions` and friends)
300
+ - **Hoisting** if tools can't find packages, fix it once in the package manager config: keep default hoisting (drop `installConfig.hoistingLimits`/`nohoist`), on pnpm add `public-hoist-pattern[]=<pkg>` to `.npmrc`, or add the tool to root `devDependencies`. Run eslint with `LINT_DEBUG=1` to trace detection.
301
+ - **Scans follow the declared workspace.** `scanWorkspace` (also used by all evidence scans) now covers the root directory plus the real `workspaces`/`pnpm-workspace.yaml` packages via `@manypkg/get-packages` instead of a blind ≤5-level glob — config files in directories that are not declared workspace members are only found via the root scan, and the depth limit is gone.
302
+ - `has*` probes are anchored at the **workspace root** (via `local-pkg`) instead of this package's install location — identical for standard root installs.
297
303
 
298
304
  Everything else — `prettier`, `listStaged`, extension lists (`tsExts`, …), `has*` detection exports, plugin re-exports (`nxPlugin`, …) — is unchanged.
299
305
 
300
- ## Why raw JS (no build)
306
+ ## Development
307
+
308
+ ### Why raw JS (no build)
301
309
 
302
310
  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
311
 
312
+ ### Eslint
313
+
314
+ 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`.
315
+
316
+ **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`.
317
+
318
+ 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.
319
+
320
+ ### Detection
321
+
322
+ Due to limitations package visibility between leaf and root this package has to be creative to support config-free detection.
323
+
324
+ 1. **Package probe** — `local-pkg`'s `isPackageExists` anchored at the **workspace root**, the same scope the plugins resolve from at lint time (`has<Pkg>` exported for debugging).
325
+ 2. **Evidence scan** — tool config files across the workspace: the root directory plus every **workspace package** (the real `workspaces`/`pnpm-workspace.yaml` globs via `@manypkg/get-packages`, not a depth heuristic), 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 env (`PROJECT_CWD`/`npm_config_local_prefix`) with `@manypkg/find-root` as the fallback (workspace manifest walk, nearest `package.json` for single-package repos; exported as `findWorkspaceRoot`), so linting from inside a package still sees the whole repo.
326
+ 3. **Hoisting, not bridging** — the plugins need the tool's package resolvable from the workspace root; a tool that is evidently in use (2) but not resolvable there (1) is a **hard error** with hoisting guidance (keep default hoisting, pnpm `public-hoist-pattern`, or a root devDependency — see the error text) instead of a silent skip or a cryptic plugin crash. Fix it once in the package manager config; nothing is symlinked at lint time.
327
+ 4. **Yarn Berry PnP** — there is no hoisting to configure; declare 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.
328
+
329
+ | Option | Package | Evidence glob | When zero / many found |
330
+ | ----------- | ---------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
331
+ | `tailwind` | `tailwindcss`¹ | `*.css` with `@import "tailwindcss"` | needs exactly **one**: zero → off (forced → error), several → **always** error; set `cssConfigPath` |
332
+ | `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`) |
333
+ | `storybook` | `storybook`¹ | `.storybook/main.*` | presence is enough |
334
+ | `jest` | `jest`¹ | `jest.config.*` | presence is enough |
335
+ | `vitest` | `vitest`¹ | `{vitest,vite}.config.*` | presence is enough |
336
+ | `nx` | (plugin bundled) | `nx.json` at the workspace root | — |
337
+ | `turbo` | `turbo` | package probe only | — |
338
+
339
+ ¹ 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) — resolvable from the workspace root, or the hard error of step 3 fires.
340
+
341
+ The machinery is controlled by the `detection` option (same toggle notation as the tools):
342
+
343
+ - `detection: false` — tools are OFF unless explicitly enabled; enabled tools still auto-detect their settings (step 2)
344
+ - `detection: { strict: true }` — only step 1 runs: the `has*` package probes **are** the strict detection — no workspace evidence scans (2). Mandatory settings (`cssConfigPath`) must then be explicit, and `nx.json` is checked at **cwd** instead of the workspace root (`hasNx` is the only non-package `has*`)
345
+ - `detection: { enabled: false, strict: true }` — fully explicit: tools on only when set, probes only
346
+
347
+ Set `LINT_DEBUG=1` to trace the machinery: `has*` probe results, every workspace scan (glob, root, files found) and each tool's gate verdict (supplied options, absolutized & scanned evidence files, effective enabled status + reason).
348
+
349
+ > `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.
350
+
351
+ ### Type-aware rules (optional, disabled by default for performance)
352
+
353
+ 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):
354
+
355
+ ### AI Rule file format
356
+
357
+ ```yaml
358
+ ---
359
+ type: always_apply # or agent_requested
360
+ description: Set of rules for projects which use Xxx # Required for agent_requested
361
+ paths:
362
+ - '**/*.xxx'
363
+ ---
364
+ ```
365
+
304
366
  ## Issues
305
367
 
306
368
  - Package managers
307
369
  - [ ] 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
370
  - [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
310
- - [ ] Yarn 1 (classic) — workspace-root detection verified in a scratch workspace (no root env, `npm prefix`/lockfile-walk path); full config unverified
311
- - [ ] pnpm — workspace-root detection verified in a scratch workspace (`pnpm root -w`, no usable env); full config unverified
312
- - [ ] npm — root probes verified (`npm_config_local_prefix`, workspace-aware `npm prefix`); full config unverified
371
+ - [ ] Yarn Berry **PnP** — root-declared `tailwindcss` verified working (see "Detection" step 4); full config run (plugin loading, capability probes) unverified since the switch to `@manypkg/find-root`/`local-pkg`
372
+ - [ ] Yarn 1 (classic) — root detection now delegates to `@manypkg/find-root` (workspace-manifest walk); unverified since the switch
373
+ - [ ] pnpm — root detection via `@manypkg/find-root` (`pnpm-workspace.yaml`); `public-hoist-pattern` guidance unverified in a real pnpm workspace
374
+ - [ ] npm — env fast-path (`npm_config_local_prefix`) verified previously; `@manypkg/find-root` fallback unverified since the switch
313
375
  - ESLint 9
314
376
  - [x] https://github.com/microsoft/rushstack/issues/4635 Failed to patch ESLint because the calling module was not recognized
315
377
  - [x] https://github.com/microsoft/rushstack/issues/4965 Failed to patch ESLint because the calling module was not recognized
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, `next` must be resolvable from the workspace root (hoisted); a leaf-only
110
+ * install is a hard error with hoisting guidance (see `toolGate` in lib.js).
73
111
  *
74
112
  * @param {boolean | NextOptions} [option] the defineLintConfig `next` flag
113
+ * @param {boolean} [strict] same-scope detection only - no `next.config.*` scan (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 evidence probes each entry is
124
+ * expanded against the workspace root into real app dirs; a plain path that exists simply
125
+ * matches itself. An entry matching nothing falls back to the literal path as the probe
126
+ * anchor (harmless - resolution just walks up from there). The probes resolve from each
127
+ * app's 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,27 @@
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, `storybook` must
8
+ * be resolvable from the workspace root (hoisted); a leaf-only install is a hard error with
9
+ * hoisting guidance (see `toolGate` in lib.js). The plugin stays lazily imported so consumers
10
+ * without Storybook never pay for it.
6
11
  *
7
12
  * @param {boolean | import('../index.js').ToggleOptions} [option] the defineLintConfig `storybook` flag; auto-detected when omitted
13
+ * @param {boolean} [strict] same-scope detection only - no `.storybook` scan (defineLintConfig `detection.strict`)
8
14
  * @returns {Promise<import('eslint').Linter.Config[]>}
9
15
  */
10
- export async function storybookConfig(option) {
11
- const { enabled = hasStorybook } = asOptions(option);
16
+ export async function storybookConfig(option, strict = false) {
17
+ const { enabled } = toolGate(option, strict, {
18
+ tool: 'storybook',
19
+ has: hasStorybook,
20
+ packageName: 'storybook',
21
+ scan: () => scanWorkspace('.storybook/main.*', GLOBAL_IGNORES, { dot: true }),
22
+ });
12
23
  if (!enabled) return [];
24
+
13
25
  const storybookPlugin = (await import('eslint-plugin-storybook')).default;
14
26
  return storybookPlugin.configs['flat/recommended'];
15
27
  }