tailwind-canonical 0.7.1 → 0.9.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.
@@ -1,4 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
+ import { validateConfig } from '../core/config.js';
3
+ import { mergeClasses } from '../core/merger.js';
2
4
  import { suggestCanonical, } from '../core/rules.js';
3
5
  const _require = createRequire(import.meta.url);
4
6
  /**
@@ -13,31 +15,97 @@ function quasiTextRange(quasi) {
13
15
  const start = quasi.range[0] + 1;
14
16
  return [start, start + quasi.value.raw.length];
15
17
  }
16
- /**
17
- * Builds the shared ESLint visitor that runs `checkLiteral` on every string
18
- * `Literal` and on each quasi of a `TemplateLiteral`. Both rules walk class
19
- * strings identically, so the traversal lives here once. Quasi nodes carry the
20
- * real `range`/`loc` so `context.report` and the fixer operate on actual source
21
- * positions instead of a detached synthetic node.
22
- */
23
- function makeStringRuleVisitor(checkLiteral) {
18
+ /** Only inspect strings whose syntax establishes that they contain classes. */
19
+ function isClassContext(node, config) {
20
+ const attributes = config.attributeNames?.length
21
+ ? config.attributeNames
22
+ : ['className'];
23
+ const functions = config.functionNames ?? ['cn', 'clsx', 'cva'];
24
+ const properties = [];
25
+ let current = node;
26
+ while (current.parent) {
27
+ const parent = current.parent;
28
+ if (parent.type === 'JSXAttribute') {
29
+ const name = parent.name;
30
+ return (properties.length === 0 &&
31
+ typeof name === 'object' &&
32
+ attributes.includes(name.name ?? ''));
33
+ }
34
+ if (parent.type === 'CallExpression') {
35
+ if (parent.callee?.type !== 'Identifier')
36
+ return false;
37
+ const name = String(parent.callee.name);
38
+ if (!functions.includes(name))
39
+ return false;
40
+ if (properties.length === 0)
41
+ return true;
42
+ if (name === 'cva') {
43
+ if (properties.some((property) => property.isKey))
44
+ return false;
45
+ return ((properties.length === 3 && properties[2].key === 'variants') ||
46
+ (properties.length === 2 &&
47
+ properties[1].key === 'compoundVariants' &&
48
+ ['class', 'className'].includes(properties[0].key)));
49
+ }
50
+ // clsx-style object arguments emit their keys; values are predicates.
51
+ return properties.every((property) => property.isKey);
52
+ }
53
+ if (parent.type === 'Property') {
54
+ properties.push({
55
+ key: String(parent.key?.name ?? parent.key?.value ?? ''),
56
+ isKey: current === parent.key,
57
+ });
58
+ }
59
+ if (parent.type === 'LogicalExpression' &&
60
+ parent.operator === '&&' &&
61
+ current === parent.left)
62
+ return false;
63
+ if (parent.type === 'ConditionalExpression' &&
64
+ current !== parent.consequent &&
65
+ current !== parent.alternate)
66
+ return false;
67
+ if (![
68
+ 'JSXExpressionContainer',
69
+ 'ArrayExpression',
70
+ 'ObjectExpression',
71
+ 'Property',
72
+ 'ConditionalExpression',
73
+ 'LogicalExpression',
74
+ ].includes(parent.type))
75
+ return false;
76
+ current = parent;
77
+ }
78
+ return false;
79
+ }
80
+ function makeStringRuleVisitor(checkLiteral, config = {}) {
24
81
  return {
25
- Literal: (node) => checkLiteral(node),
82
+ Literal: (node) => {
83
+ if (isClassContext(node, config)) {
84
+ checkLiteral(node);
85
+ }
86
+ },
26
87
  TemplateLiteral(node) {
27
- const isTagged = node.parent
28
- ?.type === 'TaggedTemplateExpression';
29
- for (const quasi of node.quasis) {
30
- const value = isTagged
31
- ? quasi.value.raw
32
- : (quasi.value.cooked ?? quasi.value.raw);
88
+ if (!isClassContext(node, config))
89
+ return;
90
+ for (const [index, quasi] of node.quasis.entries()) {
91
+ const value = quasi.value.cooked ?? quasi.value.raw;
92
+ // A token touching an interpolation is incomplete: e.g.
93
+ // `text-[12px]${suffix}` must not become `text-xs${suffix}`.
94
+ const start = value.match(index > 0 ? /^\S*\s*/ : /^\s*/)?.[0].length ?? 0;
95
+ const trailing = value.match(index < node.quasis.length - 1 ? /\s*\S*$/ : /\s*$/)?.[0]
96
+ .length ?? 0;
97
+ const end = Math.max(start, value.length - trailing);
98
+ const inner = value.slice(start, end);
33
99
  checkLiteral({
34
100
  type: 'Literal',
35
- value,
101
+ value: inner,
36
102
  raw: quasi.value.raw,
37
103
  range: quasi.range,
38
104
  loc: quasi.loc,
39
105
  quasiRange: quasiTextRange(quasi),
40
- valueIsRaw: isTagged || quasi.value.cooked === null,
106
+ valueIsRaw: quasi.value.cooked === null,
107
+ templatePrefix: value.slice(0, start),
108
+ templateSuffix: value.slice(end),
41
109
  });
42
110
  }
43
111
  },
@@ -70,7 +138,8 @@ function escapeTemplateText(value) {
70
138
  }
71
139
  function replacementText(node, value) {
72
140
  if (node.quasiRange) {
73
- return node.valueIsRaw ? value : escapeTemplateText(value);
141
+ const full = (node.templatePrefix ?? '') + value + (node.templateSuffix ?? '');
142
+ return node.valueIsRaw ? full : escapeTemplateText(full);
74
143
  }
75
144
  return quoteReplacement(node, value);
76
145
  }
@@ -88,8 +157,8 @@ const noArbitraryCanonical = {
88
157
  // config object can be passed as rule options without schema errors (#42).
89
158
  // Honored by this rule (via suggestCanonical): customTextTokens,
90
159
  // customSpacingTokens, ignorePatterns, tailwindVersion.
91
- // Accepted but ignored here (CLI-only): functionNames, attributeNames,
92
- // sortOrder.
160
+ // functionNames and attributeNames restrict class string detection.
161
+ // Other CLI-only keys are accepted for shared config objects.
93
162
  schema: [
94
163
  {
95
164
  type: 'object',
@@ -98,9 +167,18 @@ const noArbitraryCanonical = {
98
167
  customSpacingTokens: { type: 'object' },
99
168
  ignorePatterns: { type: 'array' },
100
169
  tailwindVersion: { enum: [3, 4] },
170
+ useDefaultTheme: { type: 'boolean' },
101
171
  functionNames: { type: 'array', items: { type: 'string' } },
102
172
  attributeNames: { type: 'array', items: { type: 'string' } },
103
173
  sortOrder: { type: 'array', items: { type: 'string' } },
174
+ extraColorFamilies: { type: 'object' },
175
+ extraScaleProperties: { type: 'array', items: { type: 'string' } },
176
+ extraColors: { type: 'array', items: { type: 'string' } },
177
+ analyze: { type: 'object' },
178
+ minRareScalePropertyOccurrences: { type: 'number' },
179
+ rareScaleMaxFiles: { type: 'number' },
180
+ rareScaleMaxCount: { type: 'number' },
181
+ defaultCommand: { type: 'object' },
104
182
  },
105
183
  additionalProperties: false,
106
184
  },
@@ -110,7 +188,7 @@ const noArbitraryCanonical = {
110
188
  },
111
189
  },
112
190
  create(context) {
113
- const config = context.options[0] ?? {};
191
+ const config = validateConfig(context.options[0], 'ESLint rule options');
114
192
  function checkLiteral(node) {
115
193
  if (typeof node.value !== 'string')
116
194
  return;
@@ -133,7 +211,7 @@ const noArbitraryCanonical = {
133
211
  fix: (fixer) => replaceString(fixer, node, corrected),
134
212
  });
135
213
  }
136
- return makeStringRuleVisitor(checkLiteral);
214
+ return makeStringRuleVisitor(checkLiteral, config);
137
215
  },
138
216
  };
139
217
  function loadTwMerge() {
@@ -141,26 +219,25 @@ function loadTwMerge() {
141
219
  return _require('tailwind-merge').twMerge;
142
220
  }
143
221
  catch {
144
- return null;
222
+ throw new Error('The no-conflicting-classes rule requires the optional peer dependency "tailwind-merge". Install it with: pnpm add -D tailwind-merge');
145
223
  }
146
224
  }
147
225
  const noConflictingClasses = {
148
226
  meta: {
149
227
  type: 'suggestion',
150
228
  fixable: 'code',
151
- schema: [],
229
+ schema: noArbitraryCanonical.meta?.schema ?? [],
152
230
  messages: {
153
231
  conflicting: "Conflicting Tailwind classes detected. Use '{{merged}}' instead.",
154
232
  },
155
233
  },
156
234
  create(context) {
157
235
  const twMerge = loadTwMerge();
236
+ const config = validateConfig(context.options[0], 'ESLint rule options');
158
237
  function checkLiteral(node) {
159
- if (!twMerge)
160
- return;
161
238
  if (typeof node.value !== 'string')
162
239
  return;
163
- const merged = twMerge(node.value);
240
+ const merged = mergeClasses(node.value, twMerge, config);
164
241
  if (merged === node.value)
165
242
  return;
166
243
  context.report({
@@ -169,7 +246,7 @@ const noConflictingClasses = {
169
246
  fix: (fixer) => replaceString(fixer, node, merged),
170
247
  });
171
248
  }
172
- return makeStringRuleVisitor(checkLiteral);
249
+ return makeStringRuleVisitor(checkLiteral, config);
173
250
  },
174
251
  };
175
252
  const plugin = {
@@ -8,4 +8,7 @@ import type { Config } from '../core/rules.js';
8
8
  * nothing.
9
9
  */
10
10
  export declare function resolveInitFilename(cwd: string): string;
11
- export declare function loadConfig(cwd: string): Promise<Config>;
11
+ export declare function findConfigPath(cwd: string): string | undefined;
12
+ export declare function loadConfig(cwd: string, options?: {
13
+ reload?: boolean;
14
+ }): Promise<Config>;
package/dist/io/config.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { existsSync, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
2
4
  import { basename, dirname, join } from 'node:path';
3
5
  import { pathToFileURL } from 'node:url';
4
6
  import { CONFIG_FILENAMES, validateConfig } from '../core/config.js';
@@ -51,7 +53,7 @@ export function resolveInitFilename(cwd) {
51
53
  ? 'tailwind-canonical.config.js'
52
54
  : 'tailwind-canonical.config.mjs';
53
55
  }
54
- function findConfigPath(cwd) {
56
+ export function findConfigPath(cwd) {
55
57
  let dir = cwd;
56
58
  while (true) {
57
59
  const filename = CONFIG_FILENAMES.find((name) => existsSync(join(dir, name)));
@@ -65,14 +67,50 @@ function findConfigPath(cwd) {
65
67
  dir = parent;
66
68
  }
67
69
  }
68
- export async function loadConfig(cwd) {
70
+ const reloadCache = new Map();
71
+ export async function loadConfig(cwd, options = {}) {
69
72
  const path = findConfigPath(cwd);
70
73
  if (!path)
71
74
  return {};
72
75
  const filename = basename(path);
73
76
  let mod;
77
+ let hash;
74
78
  try {
75
- mod = await import(pathToFileURL(path).href);
79
+ const url = pathToFileURL(path);
80
+ if (options.reload) {
81
+ hash = createHash('sha256').update(readFileSync(path)).digest('hex');
82
+ const cached = reloadCache.get(path);
83
+ if (cached?.hash === hash)
84
+ return cached.config;
85
+ // Content-based URLs avoid another ESM instance on unchanged source saves.
86
+ url.searchParams.set('version', hash);
87
+ }
88
+ if (options.reload &&
89
+ /\.(?:js|ts)$/.test(filename) &&
90
+ nearestPackageType(dirname(path)) === 'commonjs') {
91
+ // CJS has an additional require cache: query parameters only invalidate
92
+ // its ESM namespace wrapper. Read it via require after clearing that cache.
93
+ const require = createRequire(import.meta.url);
94
+ delete require.cache[require.resolve(path)];
95
+ try {
96
+ const loaded = require(path);
97
+ mod =
98
+ typeof loaded === 'object' &&
99
+ loaded !== null &&
100
+ '__esModule' in loaded &&
101
+ 'default' in loaded
102
+ ? loaded
103
+ : { default: loaded };
104
+ }
105
+ catch (error) {
106
+ if (!['ERR_REQUIRE_ESM', 'ERR_REQUIRE_ASYNC_MODULE'].includes(error.code ?? ''))
107
+ throw error;
108
+ mod = await import(url.href);
109
+ }
110
+ }
111
+ else {
112
+ mod = await import(url.href);
113
+ }
76
114
  }
77
115
  catch (err) {
78
116
  const msg = err instanceof Error ? err.message : String(err);
@@ -95,5 +133,8 @@ export async function loadConfig(cwd) {
95
133
  }
96
134
  throw err;
97
135
  }
98
- return validateConfig(mod.default, filename);
136
+ const config = validateConfig(mod.default, filename);
137
+ if (hash)
138
+ reloadCache.set(path, { hash, config });
139
+ return config;
99
140
  }
@@ -1,15 +1,13 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { toClassStringOpts } from '../core/class-strings.js';
3
- import { analyzeConsistency, collectClasses, } from '../core/consistency.js';
2
+ import { extractClassStrings, SINGLE_CLASS_REGEX, toClassStringOpts, } from '../core/class-strings.js';
3
+ import { analyzeConsistency, } from '../core/consistency.js';
4
4
  export function analyzeConsistencyFiles(filePaths, config = {}, options = {}, onError) {
5
5
  const opts = toClassStringOpts(config);
6
6
  const input = [];
7
7
  for (const file of filePaths) {
8
8
  try {
9
- input.push({
10
- file,
11
- classes: collectClasses(readFileSync(file, 'utf8'), opts),
12
- });
9
+ const classLists = extractClassStrings(readFileSync(file, 'utf8'), opts).map(({ value }) => [...value.matchAll(SINGLE_CLASS_REGEX)].map((match) => match[0]));
10
+ input.push({ file, classes: classLists.flat(), classLists });
13
11
  }
14
12
  catch (err) {
15
13
  if (onError)
@@ -1,7 +1,7 @@
1
- import { readdirSync, statSync } from 'node:fs';
1
+ import { existsSync, lstatSync, readdirSync, statSync, } from 'node:fs';
2
2
  import { glob } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { DEFAULT_EXTENSIONS, DEFAULT_IGNORE, globToRegex, isGlob, } from '../core/scanner.js';
3
+ import { isAbsolute, join, matchesGlob, resolve } from 'node:path';
4
+ import { DEFAULT_EXTENSIONS, DEFAULT_IGNORE, isGlob, } from '../core/scanner.js';
5
5
  export function scanFiles(target, options = {}) {
6
6
  const ignore = options.ignore ?? DEFAULT_IGNORE;
7
7
  const extensions = options.extensions ?? DEFAULT_EXTENSIONS;
@@ -21,7 +21,8 @@ export function scanFiles(target, options = {}) {
21
21
  if (entry.isDirectory()) {
22
22
  walk(full);
23
23
  }
24
- else if (extensions.some((ext) => entry.name.endsWith(ext))) {
24
+ else if (entry.isFile() &&
25
+ extensions.some((ext) => entry.name.endsWith(ext))) {
25
26
  files.push(full);
26
27
  }
27
28
  }
@@ -42,10 +43,10 @@ export async function resolveTargets(patterns, options = {}) {
42
43
  const ignore = options.ignore ?? DEFAULT_IGNORE;
43
44
  const extensions = options.extensions ?? DEFAULT_EXTENSIONS;
44
45
  const positive = [];
45
- const negativeRegexes = [];
46
+ const negativePatterns = [];
46
47
  for (const p of patterns) {
47
48
  if (p.startsWith('!')) {
48
- negativeRegexes.push(globToRegex(p.slice(1)));
49
+ negativePatterns.push(p.slice(1).replace(/\\/g, '/'));
49
50
  }
50
51
  else {
51
52
  positive.push(p);
@@ -53,14 +54,15 @@ export async function resolveTargets(patterns, options = {}) {
53
54
  }
54
55
  const files = new Set();
55
56
  for (const pattern of positive) {
56
- if (isGlob(pattern)) {
57
+ if (isGlob(pattern) && !existsSync(pattern)) {
57
58
  for await (const f of glob(pattern, {
58
59
  exclude: (entry) => entry
59
60
  .replace(/\\/g, '/')
60
61
  .split('/')
61
62
  .some((s) => ignore.includes(s)),
62
63
  })) {
63
- if (extensions.some((ext) => f.endsWith(ext))) {
64
+ if (extensions.some((ext) => f.endsWith(ext)) &&
65
+ lstatSync(f).isFile()) {
64
66
  files.add(f);
65
67
  }
66
68
  }
@@ -71,10 +73,24 @@ export async function resolveTargets(patterns, options = {}) {
71
73
  }
72
74
  }
73
75
  }
74
- if (negativeRegexes.length > 0) {
76
+ if (negativePatterns.length > 0) {
77
+ const exclusions = negativePatterns.map((pattern) => ({
78
+ pattern,
79
+ literal: existsSync(pattern)
80
+ ? resolve(pattern).replace(/\\/g, '/')
81
+ : undefined,
82
+ }));
75
83
  for (const f of [...files]) {
76
84
  const normalized = f.replace(/\\/g, '/');
77
- if (negativeRegexes.some((re) => re.test(normalized))) {
85
+ if (exclusions.some(({ pattern, literal }) => {
86
+ if (literal) {
87
+ const full = resolve(f).replace(/\\/g, '/');
88
+ return (full === literal ||
89
+ full.startsWith(literal.endsWith('/') ? literal : `${literal}/`));
90
+ }
91
+ return (matchesGlob(normalized, pattern) ||
92
+ (!isAbsolute(pattern) && matchesGlob(normalized, `**/${pattern}`)));
93
+ })) {
78
94
  files.delete(f);
79
95
  }
80
96
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tailwind-canonical",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "Lint and auto-fix Tailwind CSS arbitrary values that have canonical equivalents",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -64,8 +64,8 @@
64
64
  "typescript": "^7.0.2"
65
65
  },
66
66
  "peerDependencies": {
67
- "eslint": ">=8.0.0",
68
- "tailwind-merge": ">=2.0.0"
67
+ "eslint": ">=8.57.1 <11",
68
+ "tailwind-merge": ">=2.0.0 <4"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "eslint": {
@@ -80,8 +80,10 @@
80
80
  "dev": "tsc --watch",
81
81
  "test": "node --import=tsx/esm --test \"src/**/*.test.ts\"",
82
82
  "typecheck": "tsc --noEmit",
83
- "lint": "biome check src/",
84
- "lint:fix": "biome check --write src/",
85
- "knip": "knip"
83
+ "lint": "biome check src/ scripts/",
84
+ "lint:fix": "biome check --write src/ scripts/",
85
+ "knip": "knip",
86
+ "benchmark": "pnpm build && node scripts/benchmark.mjs",
87
+ "test:compat": "node scripts/compatibility.mjs"
86
88
  }
87
89
  }