@kirill.konshin/lint 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib.js ADDED
@@ -0,0 +1,250 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
4
+ import { includeIgnoreFile as includeIgnoreFileCompat } from '@eslint/compat';
5
+ import { globSync } from 'glob';
6
+
7
+ export const tsExtsRaw = 'js,jsx,ts,tsx,cjs,cts,mjs,mts'; // TODO mdx, needs loader
8
+ export const eslintExtsRaw = `${tsExtsRaw},md,mdx,htm,html,vue`;
9
+ export const prettierExtsRaw = 'css,scss,sass,less,yml,yaml,json,json5,jsonc,graphql,graphqls,xml';
10
+
11
+ export const tsExts = `{${tsExtsRaw}}`;
12
+ export const eslintExts = `*.{${eslintExtsRaw}}`;
13
+ export const prettierExts = `*.{${prettierExtsRaw}}`;
14
+
15
+ //TODO coverage, dist, out, build?
16
+ export const GLOBAL_IGNORES = [
17
+ '**/next-env.d.ts',
18
+ '**/viteEnv.d.ts',
19
+ '**/node_modules',
20
+ '**/.cache',
21
+ '**/.nx',
22
+ '**/.turbo',
23
+ '**/.yarn',
24
+ ];
25
+
26
+ /**
27
+ * Capability gate: is a package installed in the consumer's project?
28
+ *
29
+ * @param {string} specifier e.g. `'next/package.json'` - probe package.json, importing the real entry could have side effects
30
+ * @returns {boolean}
31
+ */
32
+ export function isPackageResolvable(specifier) {
33
+ try {
34
+ import.meta.resolve(specifier);
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ // lockfiles & workspace manifests only ever live at the workspace root
42
+ const ROOT_MARKERS = [
43
+ 'yarn.lock',
44
+ 'package-lock.json',
45
+ 'pnpm-lock.yaml',
46
+ 'pnpm-workspace.yaml',
47
+ 'bun.lock',
48
+ 'bun.lockb',
49
+ ];
50
+
51
+ /**
52
+ * Run a shell command, returning trimmed stdout or null on any failure.
53
+ *
54
+ * @param {string} command
55
+ * @param {string} cwd
56
+ * @returns {string | null}
57
+ */
58
+ function tryExec(command, cwd) {
59
+ try {
60
+ return (
61
+ execSync(command, {
62
+ cwd,
63
+ stdio: ['ignore', 'pipe', 'ignore'],
64
+ encoding: 'utf-8',
65
+ timeout: 15_000,
66
+ }).trim() || null
67
+ );
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * A workspace-root candidate is only plausible when it is an absolute existing directory that
75
+ * contains (or is) `cwd` - guards against stale env / CLI answers leaking into unrelated
76
+ * directories AND against non-path CLI noise: Yarn 1 has no real `yarn node` command, its
77
+ * run-fallback executes it anyway and prints `yarn node v1.22.22\n...\nDone in 0.06s.` to stdout
78
+ * (verified) - a banner must never be mistaken for a root.
79
+ *
80
+ * @param {string | undefined} root
81
+ * @param {string} cwd
82
+ * @returns {boolean}
83
+ */
84
+ function isRootOf(root, cwd) {
85
+ if (!root || root.includes('\n') || !isAbsolute(root) || !existsSync(root)) return false;
86
+ const rel = relative(root, cwd);
87
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
88
+ }
89
+
90
+ /**
91
+ * Last-resort walk: nearest ancestor with a lockfile / workspace manifest, bounded by `.git`
92
+ * (a marker above the repo boundary belongs to another project; `.git` is a directory in a normal
93
+ * clone but a FILE in worktrees and submodules - existsSync covers both).
94
+ *
95
+ * @param {string} cwd
96
+ * @returns {string}
97
+ */
98
+ function walkToRootMarker(cwd) {
99
+ let dir = cwd;
100
+ for (;;) {
101
+ if (ROOT_MARKERS.some((marker) => existsSync(resolve(dir, marker)))) return dir;
102
+ if (existsSync(resolve(dir, '.git'))) return dir;
103
+ const parent = dirname(dir);
104
+ if (parent === dir) return cwd;
105
+ dir = parent;
106
+ }
107
+ }
108
+
109
+ const workspaceRoots = new Map();
110
+
111
+ /**
112
+ * Workspace root of the consumer project - the anchor for every config-file scan (Tailwind entry,
113
+ * `next.config.*`) and root-file detection (`nx.json`): `process.cwd()` alone is unreliable
114
+ * because lint often runs from INSIDE a package (lint-staged, IDE, `yarn workspace x lint`) while
115
+ * the shared config must see the whole repo.
116
+ *
117
+ * Resolution order, cheapest first - every candidate must contain `cwd` or it is rejected:
118
+ * 1. env the package manager sets for its child processes: `PROJECT_CWD` (Yarn Berry),
119
+ * `npm_config_local_prefix` (npm >= 7, workspace-aware)
120
+ * 2. the package managers' own CLIs (subprocess, slow - hit when e.g. the IDE spawns eslint
121
+ * directly): `pnpm root -w` (dirname of the printed node_modules), Yarn Berry via `yarn node`,
122
+ * and `npm prefix` LAST - it walks up honoring package.json `workspaces` membership, but with
123
+ * no package.json around it echoes cwd back, so anything more specific must win first
124
+ * 3. walking up from `cwd` to the nearest lockfile / workspace manifest, bounded by `.git`
125
+ *
126
+ * TODO verify the whole package end-to-end per manager - Yarn Berry, Yarn Berry PnP, Yarn 1,
127
+ * pnpm, npm - see README "Issues"; so far only root detection was exercised outside this repo.
128
+ *
129
+ * Per-manager reality (all verified empirically):
130
+ * - Yarn Berry: env when spawned by yarn, `yarn node` probe otherwise - both give the root
131
+ * - npm: env when spawned by npm/npx, `npm prefix` otherwise
132
+ * - pnpm: sets NO usable env at all (not even in scripts) - always the `pnpm root -w` probe
133
+ * - Yarn 1 (classic): sets NO root env (only `INIT_CWD` = invocation dir) and has no root
134
+ * command; its `yarn node` banner output is rejected by {@link isRootOf}; classic workspaces
135
+ * resolve via `npm prefix` (same package.json `workspaces` field) or the yarn.lock walk
136
+ *
137
+ * Cached per `cwd` - the CLI probes are expensive and the config is rebuilt on every lint run.
138
+ *
139
+ * @param {string} [cwd]
140
+ * @returns {string} absolute path; `cwd` itself when nothing better was found
141
+ */
142
+ export function findWorkspaceRoot(cwd = process.cwd()) {
143
+ if (workspaceRoots.has(cwd)) return workspaceRoots.get(cwd);
144
+
145
+ const candidates = [
146
+ () => process.env.PROJECT_CWD,
147
+ () => process.env.npm_config_local_prefix,
148
+ () => {
149
+ const nodeModules = tryExec('pnpm root -w', cwd);
150
+ return nodeModules && dirname(nodeModules);
151
+ },
152
+ () => tryExec(`yarn node -p "process.env.PROJECT_CWD||''"`, cwd),
153
+ () => tryExec('npm prefix', cwd),
154
+ ];
155
+
156
+ let root = null;
157
+ for (const candidate of candidates) {
158
+ const value = candidate();
159
+ if (isRootOf(value, cwd)) {
160
+ root = resolve(value);
161
+ break;
162
+ }
163
+ }
164
+ root ??= walkToRootMarker(cwd);
165
+
166
+ workspaceRoots.set(cwd, root);
167
+ return root;
168
+ }
169
+
170
+ /*
171
+ * Build outputs regularly contain COPIES of the scanned files (compiled css, a next.config.js in a
172
+ * 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
+ */
175
+ const SCAN_IGNORES = ['**/dist', '**/build', '**/out', '**/coverage', '**/.next', '**/.expo', '**/storybook-static'];
176
+
177
+ // glob's maxDepth counts path segments INCLUDING the filename (verified empirically): 6 → files up
178
+ // to five directory levels below the root, covering packages/<x>/src/styles and apps/<group>/<app>
179
+ const SCAN_DEPTH = 6;
180
+
181
+ /**
182
+ * Glob for config-file candidates below the workspace root (up to five directory levels deep),
183
+ * skipping dot dirs, build outputs, the given ignore patterns and everything in the root
184
+ * `.gitignore`. Anchored to {@link findWorkspaceRoot}, NOT cwd.
185
+ *
186
+ * Public - useful for building consumer file lists (e.g. `typeAware.allowDefaultProject`, see README "Type-aware rules").
187
+ *
188
+ * @param {string} fileGlob e.g. `'*.css'`, `'next.config.*'`
189
+ * @param {string[]} [ignores] extra glob patterns to skip
190
+ * @returns {string[]} absolute paths
191
+ */
192
+ export function scanWorkspace(fileGlob, ignores = []) {
193
+ const root = findWorkspaceRoot();
194
+
195
+ let gitignored = [];
196
+ try {
197
+ // Reuse ESLint's gitignore->minimatch conversion; glob's `ignore` speaks the same language.
198
+ // Negations dropped: glob's ignore cannot un-ignore.
199
+ gitignored = includeIgnoreFileCompat(resolve(root, '.gitignore')).ignores.filter(
200
+ (pattern) => !pattern.startsWith('!'),
201
+ );
202
+ } catch {
203
+ // no .gitignore - the scan is just less filtered
204
+ }
205
+
206
+ // `<dir-pattern>/**` variants prune the CONTENTS of ignored directories, not just the dir itself
207
+ const ignore = [...ignores, ...SCAN_IGNORES, ...gitignored].flatMap((pattern) => [
208
+ pattern,
209
+ pattern.endsWith('/') ? `${pattern}**` : `${pattern}/**`,
210
+ ]);
211
+
212
+ return globSync(`**/${fileGlob}`, {
213
+ cwd: root,
214
+ maxDepth: SCAN_DEPTH,
215
+ ignore,
216
+ absolute: true,
217
+ });
218
+ }
219
+
220
+ /*
221
+ * Capability detection, exported for debugging. Package probes resolve from THIS package's install
222
+ * location, so in a monorepo where a tool lives only in leaf packages (not in the root
223
+ * package.json) detection can miss it - that's what the per-tool force-on flags of
224
+ * defineLintConfig are for. `nx.json` is checked at the workspace root, not via cwd.
225
+ */
226
+ export const hasNext = isPackageResolvable('next/package.json');
227
+ export const hasStorybook = isPackageResolvable('storybook/package.json');
228
+ export const hasVite = isPackageResolvable('vite/package.json');
229
+ export const hasJest = isPackageResolvable('jest/package.json');
230
+ export const hasVitest = isPackageResolvable('vitest/package.json');
231
+ export const hasTurbo = isPackageResolvable('turbo/package.json');
232
+ export const hasNx = existsSync(resolve(findWorkspaceRoot(), 'nx.json'));
233
+ export const hasTailwind = isPackageResolvable('tailwindcss/package.json');
234
+
235
+ /**
236
+ * Normalize a defineLintConfig flag into its options object with a canonical `enabled`:
237
+ * - `true` / `false` → `{ enabled: true | false }`
238
+ * - an options object counts as enabled unless it explicitly says otherwise - `enabled` defaults
239
+ * to `true`, so providing options (even `{}`) implies turning the tool on
240
+ * - `undefined` (flag not passed) → `{}` - `enabled` stays undefined and the caller falls back to
241
+ * detection: `const { enabled = hasX, ...options } = asOptions(option)`
242
+ *
243
+ * @param {boolean | { enabled?: boolean } | undefined} option user-supplied flag from `LintOptions`
244
+ * @returns {{ enabled?: boolean } & object}
245
+ */
246
+ export function asOptions(option) {
247
+ if (typeof option === 'boolean') return { enabled: option };
248
+ if (typeof option === 'object' && option !== null) return { enabled: true, ...option };
249
+ return {};
250
+ }
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.1.1",
4
+ "version": "0.3.0",
5
5
  "type": "module",
6
6
  "skipGenerate": true,
7
7
  "bin": {
@@ -9,18 +9,22 @@
9
9
  },
10
10
  "main": "index.js",
11
11
  "module": "index.js",
12
+ "types": "index.d.ts",
12
13
  "scripts": {
13
14
  "----- BUILD -----": "",
14
15
  "clean": "rm -rf dist .tscache tsconfig.tsbuildinfo",
15
16
  "build": "echo 'No build required'",
16
17
  "start": "echo 'No start required'",
17
18
  "----- TEST -----": "",
18
- "test": "echo 'No tests yet'"
19
+ "test": "vitest run"
19
20
  },
20
21
  "files": [
21
22
  "index.js",
23
+ "index.d.ts",
24
+ "configs",
25
+ "!configs/*.test.js",
26
+ "lib.js",
22
27
  "lintPrepare.js",
23
- "ruleTestColocation.js",
24
28
  "rules",
25
29
  "skills"
26
30
  ],
@@ -43,19 +47,26 @@
43
47
  "eslint-plugin-react-hooks": "^7.0.1",
44
48
  "eslint-plugin-simple-import-sort": "^14.0.0",
45
49
  "eslint-plugin-storybook": "^10.5.2",
50
+ "eslint-plugin-tailwindcss": "^4.2.0",
46
51
  "eslint-plugin-turbo": "^2.10.5",
47
52
  "eslint-plugin-unicorn": "^72.0.0",
48
53
  "eslint-plugin-unused-imports": "^4.4.1",
54
+ "glob": "^13.0.6",
49
55
  "globals": "^16.4.0",
50
56
  "jsonc-eslint-parser": "^2.4.2"
51
57
  },
58
+ "devDependencies": {
59
+ "vitest": "*"
60
+ },
52
61
  "peerDependencies": {
53
62
  "eslint": "^10",
54
63
  "husky": "^9",
55
64
  "jest": "*",
56
65
  "lint-staged": "^16",
57
66
  "next": "^16",
67
+ "prettier": "^3",
58
68
  "storybook": "^10.5.2",
69
+ "tailwindcss": "*",
59
70
  "vite": "*",
60
71
  "vitest": "*"
61
72
  },
@@ -69,6 +80,9 @@
69
80
  "storybook": {
70
81
  "optional": true
71
82
  },
83
+ "tailwindcss": {
84
+ "optional": true
85
+ },
72
86
  "vite": {
73
87
  "optional": true
74
88
  },
package/rules/tailwind.md CHANGED
@@ -7,6 +7,23 @@ description: Set of rules for projects which use Tailwind
7
7
  - Default UI library for use with Tailwind is Hero UI v3+
8
8
  - Use the smallest possible configuration of Tailwind and Hero UI, adhere to their best practices (for Vite, Next.js integration, etc.)
9
9
 
10
+ # ESLint (eslint-plugin-tailwindcss, bundled with @kirill.konshin/lint)
11
+
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
15
+ - ONLY when auto-find finds nothing (or several entries) pass the MANDATORY entry explicitly in `eslint.config.mjs`:
16
+
17
+ ```js
18
+ import { defineLintConfig } from '@kirill.konshin/lint';
19
+
20
+ export default defineLintConfig({
21
+ tailwind: {
22
+ cssConfigPath: './src/styles/tailwind.css', // MANDATORY, relative to the package root
23
+ },
24
+ });
25
+ ```
26
+
10
27
  # Hero UI
11
28
 
12
29
  - Always extract Compound Components as reusable UI kit library of project-specific Components if used more than once, never duplicate boilerplate, except highly custom ones, if in doubt ask confirmation from user
package/rules/testing.md CHANGED
@@ -4,9 +4,10 @@ description: Set of rules for projects with tests
4
4
  paths:
5
5
  - '**/jest.config.{ts,js,mjs,cjs}'
6
6
  - '**/vite.config.{ts,js,mjs,cjs}'
7
- - '**/*.test.ts'
8
- - '**/*.spec.ts'
9
- - '**/*.fixture.ts'
7
+ - '**/vitest.config.{ts,js,mjs,cjs}'
8
+ - '**/*.test.*'
9
+ - '**/*.spec.*'
10
+ - '**/*.fixture.*'
10
11
  ---
11
12
 
12
13
  - If project use `vite` use `vitest`, otherwise `jest`
@@ -16,7 +17,7 @@ paths:
16
17
  - `*.spec.ts` for e2e or integration tests (require running DEV server)
17
18
  - `*.fixture.ts` for test helpers, mocks, worker fixtures
18
19
  - Organization
19
- - Use `describe(...)` to group related tests, nesting allowed and preferred
20
+ - Top-level `test(...)` calls are OK; use `describe(...)` to group related tests when grouping helps, nesting allowed and preferred
20
21
  - Set timeouts on describe blocks or individual tests for slow tests to make them visible
21
22
  - Prefer to use `vi.fn()` or `jest.fn()` to create mock functions
22
23
  - Mock entire test-specific class implementations via `class Testable extend ClassToBeTested {}`
@@ -14,10 +14,10 @@ Full config templates: @README.md
14
14
 
15
15
  ## A. Set up / update tooling
16
16
 
17
- Follow the README, reconciling (never blindly overwriting project-specific overrides):
17
+ Follow @README.md, reconciling (never blindly overwriting project-specific overrides). When **upgrading** `@kirill.konshin/lint` from an older version, first apply the README's "Migration" section (e.g. 0.2.x → 0.3.x: default-exported array → `defineLintConfig()` options):
18
18
 
19
19
  1. **Install** — add `eslint`, `prettier`, `@kirill.konshin/lint`, `husky`, `lint-staged` (+ the PNPM `.npmrc` block if pnpm).
20
- 2. **Config** — create/reconcile `.editorconfig`, `eslint.config.mjs` and `.prettierrc.mjs` (set `next.rootDir`, keep project rule overrides).
20
+ 2. **Config** — create/reconcile `.editorconfig`, `eslint.config.mjs` and `.prettierrc.mjs` (pass `defineLintConfig` options as needed — e.g. `defaultIgnore: { importMetaUrl: import.meta.url }`, `next: { rootDir }` — and keep project rule overrides).
21
21
  3. **Lint-staged** — create/reconcile `.lintstagedrc.mjs`.
22
22
  4. **Husky** — `prepare/postinstall` (`prepare` by default, `postinstall` if Yarn 2+ is used AND root package.json is **private**) script; `.husky/pre-commit`, plus `eslint`/`prettier`/`lint`/`lint:staged` scripts. Drop a legacy `lint:all` if it duplicates `lint`.
23
23
  5. **IDEA** — apply the file-scope glob patterns if the repo has a JetBrains `.idea`.
@@ -1,50 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- const SOURCE_EXTS = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.cts', '.cjs'];
5
- const TEST_SUFFIX = new RegExp(`\\.test\\.(${SOURCE_EXTS.map((ext) => ext.slice(1)).join('|')})$`);
6
-
7
- /**
8
- * Only `*.test.*` is checked, not `*.spec.*` - per testing.md, spec files cover e2e/integration
9
- * flows that don't map 1:1 to a single sibling source file, so co-location isn't meaningful there.
10
- */
11
- export const testColocation = {
12
- meta: {
13
- type: 'problem',
14
- docs: {
15
- description: 'require *.test.* files to sit next to the source file they test, not in a separate folder',
16
- },
17
- schema: [],
18
- messages: {
19
- missingSibling:
20
- "No sibling source file found for '{{testFile}}'. Expected e.g. '{{expected}}' in the same directory, not a separate __tests__/ folder.",
21
- },
22
- },
23
- create(context) {
24
- const base = path.basename(context.filename);
25
- const match = base.match(TEST_SUFFIX);
26
-
27
- if (!match) return {};
28
-
29
- const stem = base.slice(0, -match[0].length);
30
-
31
- let siblings;
32
- try {
33
- siblings = fs.readdirSync(path.dirname(context.filename));
34
- } catch {
35
- return {}; // virtual filename (stdin, editor buffer) - no directory to check against
36
- }
37
-
38
- if (SOURCE_EXTS.some((ext) => siblings.includes(`${stem}${ext}`))) return {};
39
-
40
- return {
41
- Program(node) {
42
- context.report({
43
- node,
44
- messageId: 'missingSibling',
45
- data: { testFile: base, expected: `${stem}.ts` },
46
- });
47
- },
48
- };
49
- },
50
- };