@antebudimir/eslint-plugin-vanilla-extract 1.14.0 → 1.15.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/README.md +111 -3
- package/dist/css-rules/prefer-theme-tokens/index.d.ts +2 -0
- package/dist/css-rules/prefer-theme-tokens/index.js +2 -0
- package/dist/css-rules/prefer-theme-tokens/rule-definition.d.ts +3 -0
- package/dist/css-rules/prefer-theme-tokens/rule-definition.js +119 -0
- package/dist/css-rules/prefer-theme-tokens/theme-contract-analyzer.d.ts +60 -0
- package/dist/css-rules/prefer-theme-tokens/theme-contract-analyzer.js +322 -0
- package/dist/css-rules/prefer-theme-tokens/theme-token-processor.d.ts +26 -0
- package/dist/css-rules/prefer-theme-tokens/theme-token-processor.js +562 -0
- package/dist/css-rules/prefer-theme-tokens/theme-token-visitor-creator.d.ts +6 -0
- package/dist/css-rules/prefer-theme-tokens/theme-token-visitor-creator.js +81 -0
- package/dist/css-rules/prefer-theme-tokens/value-evaluator.d.ts +43 -0
- package/dist/css-rules/prefer-theme-tokens/value-evaluator.js +190 -0
- package/dist/demo-bad-example.css.d.ts +4 -0
- package/dist/demo-bad-example.css.js +45 -0
- package/dist/demo-good-example.css.d.ts +5 -0
- package/dist/demo-good-example.css.js +48 -0
- package/dist/demo-theme.css.d.ts +37 -0
- package/dist/demo-theme.css.js +39 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -1
- package/dist/sample-bad.css.d.ts +26 -0
- package/dist/sample-bad.css.js +85 -0
- package/dist/sample-good.css.d.ts +27 -0
- package/dist/sample-good.css.js +94 -0
- package/dist/sample-theme.css.d.ts +37 -0
- package/dist/sample-theme.css.js +38 -0
- package/dist/sample.css.d.ts +18 -18
- package/dist/sample.css.js +90 -100
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -265,6 +265,7 @@ The recommended configuration enables the following rules with error severity:
|
|
|
265
265
|
- `vanilla-extract/custom-order`: Alternative ordering rule (custom group-based sorting)
|
|
266
266
|
- `vanilla-extract/no-px-unit`: Disallows px units with an optional allowlist
|
|
267
267
|
- `vanilla-extract/prefer-logical-properties`: Enforces logical CSS properties over physical directional properties
|
|
268
|
+
- `vanilla-extract/prefer-theme-tokens`: Enforces theme tokens instead of hard-coded values for colors, spacing, font sizes, border radius, border widths, shadows, z-index, opacity, font weights, and transitions/animations (optionally evaluates helper functions and template literals)
|
|
268
269
|
|
|
269
270
|
You can use the recommended configuration as a starting point and override rules as needed for your project. See the configuration examples above for how to switch between ordering rules.
|
|
270
271
|
|
|
@@ -639,6 +640,113 @@ export const box = style({
|
|
|
639
640
|
borderInlineEnd: '1px solid',
|
|
640
641
|
textAlign: 'start',
|
|
641
642
|
});
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
### vanilla-extract/prefer-theme-tokens
|
|
646
|
+
|
|
647
|
+
Enforces theme tokens instead of hard-coded CSS values. Analyzes your theme contract files and suggests **specific tokens** when matches are found.
|
|
648
|
+
|
|
649
|
+
**Options:**
|
|
650
|
+
|
|
651
|
+
| Option | Type | Default | Description |
|
|
652
|
+
|--------|------|---------|-------------|
|
|
653
|
+
| `themeContracts` | `string[]` | `[]` | Theme contract file paths (relative to project root or absolute) |
|
|
654
|
+
| `checkColors` | `boolean` | `true` | Check colors (hex, rgb, hsl, named) |
|
|
655
|
+
| `checkSpacing` | `boolean` | `true` | Check spacing (margin, padding, gap, width, height) |
|
|
656
|
+
| `checkFontSizes` | `boolean` | `true` | Check font sizes (fontSize, lineHeight) |
|
|
657
|
+
| `checkBorderRadius` | `boolean` | `true` | Check border radius values |
|
|
658
|
+
| `checkBorderWidths` | `boolean` | `true` | Check border widths (including `border` shorthand) |
|
|
659
|
+
| `checkShadows` | `boolean` | `true` | Check shadows (boxShadow, textShadow, filter) |
|
|
660
|
+
| `checkZIndex` | `boolean` | `true` | Check z-index values |
|
|
661
|
+
| `checkOpacity` | `boolean` | `true` | Check opacity values |
|
|
662
|
+
| `checkFontWeights` | `boolean` | `true` | Check font weights (numeric and named) |
|
|
663
|
+
| `checkTransitions` | `boolean` | `true` | Check transitions and animations |
|
|
664
|
+
| `allowedValues` | `string[]` | `[]` | Whitelist specific values (e.g., `["0", "auto", "100vh"]`) |
|
|
665
|
+
| `allowedProperties` | `string[]` | `[]` | Skip checking specific properties |
|
|
666
|
+
| `autoFix` | `boolean` | `false` | Auto-fix when exactly one token matches |
|
|
667
|
+
| `remBase` | `number` | `16` | Base font size for `rem()` calculations |
|
|
668
|
+
| `checkHelperFunctions` | `boolean` | `false` | Check helper calls like `rem(48)`, `` `${rem(4)}` `` |
|
|
669
|
+
|
|
670
|
+
#### Dependency note
|
|
671
|
+
|
|
672
|
+
This rule uses a safe expression evaluator to optionally analyze helper calls when `checkHelperFunctions` is enabled. For this, the plugin internally relies on `@babel/parser` and `@babel/types` to parse small expression snippets (e.g., template literals, `rem()` calls). These are shipped as plugin dependencies, so users don't need to install them manually. They're only exercised when `checkHelperFunctions` is turned on.
|
|
673
|
+
|
|
674
|
+
**Example:**
|
|
675
|
+
|
|
676
|
+
```json
|
|
677
|
+
{
|
|
678
|
+
"rules": {
|
|
679
|
+
"vanilla-extract/prefer-theme-tokens": ["error", {
|
|
680
|
+
"themeContracts": ["./src/theme.css.ts"],
|
|
681
|
+
"checkColors": true,
|
|
682
|
+
"checkSpacing": true,
|
|
683
|
+
"allowedValues": ["0", "auto", "100%"],
|
|
684
|
+
"allowedProperties": ["borderWidth"],
|
|
685
|
+
"autoFix": false,
|
|
686
|
+
"checkHelperFunctions": false
|
|
687
|
+
}]
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
**How it works:**
|
|
693
|
+
|
|
694
|
+
1. **Analyzes theme contracts** - Reads your theme files and evaluates computed values:
|
|
695
|
+
- `rem(16)` → `"1rem"`
|
|
696
|
+
- `` `${rem(4)} ${rem(8)}` `` → `"0.25rem 0.5rem"`
|
|
697
|
+
- Arithmetic expressions
|
|
698
|
+
|
|
699
|
+
2. **Detects hard-coded values** - Checks literals, numbers, and (optionally) helper functions:
|
|
700
|
+
|
|
701
|
+
```typescript
|
|
702
|
+
color: '#0055FF' // ❌ Always flagged
|
|
703
|
+
padding: '16px' // ❌ Always flagged
|
|
704
|
+
opacity: 0.5 // ❌ Always flagged (numeric literal)
|
|
705
|
+
margin: rem(48) // ❌ Only with checkHelperFunctions: true
|
|
706
|
+
boxShadow: `${rem(4)}...` // ❌ Only with checkHelperFunctions: true
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
3. **Suggests specific tokens** - Matches values to theme tokens:
|
|
710
|
+
|
|
711
|
+
```text
|
|
712
|
+
❌ Hard-coded color '#0055FF'. Use theme token: vars.colors.brand
|
|
713
|
+
❌ Hard-coded padding '16px'. Use theme token: vars.spacing.md
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
- **Single match**: Shows one suggestion + auto-fix (if enabled)
|
|
717
|
+
- **Multiple matches**: Shows all as quick-fix options
|
|
718
|
+
|
|
719
|
+
**Theme contract example:**
|
|
720
|
+
|
|
721
|
+
```typescript
|
|
722
|
+
// theme.css.ts
|
|
723
|
+
export const [themeClass, vars] = createTheme({
|
|
724
|
+
colors: { brand: '#0055FF', text: '#1f2937' },
|
|
725
|
+
spacing: { sm: '8px', md: '16px' },
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
// styles.css.ts
|
|
729
|
+
export const button = style({
|
|
730
|
+
backgroundColor: '#0055FF', // ❌ Use vars.colors.brand
|
|
731
|
+
padding: '8px', // ❌ Use vars.spacing.sm
|
|
732
|
+
});
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
**Helper function detection:**
|
|
736
|
+
|
|
737
|
+
By default, only checks **literals**. Enable `checkHelperFunctions: true` to also check computed values:
|
|
738
|
+
|
|
739
|
+
```typescript
|
|
740
|
+
// checkHelperFunctions: false (default)
|
|
741
|
+
padding: rem(48) // ✅ Not flagged
|
|
742
|
+
padding: '3rem' // ❌ Flagged
|
|
743
|
+
|
|
744
|
+
// checkHelperFunctions: true
|
|
745
|
+
padding: rem(48) // ❌ Flagged if theme has matching token
|
|
746
|
+
padding: '3rem' // ❌ Flagged if theme has matching token
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
**Note:** Opt-in rule (not in recommended config). Enable when ready to enforce design tokens.
|
|
642
750
|
|
|
643
751
|
## Font Face Declarations
|
|
644
752
|
|
|
@@ -725,15 +833,15 @@ The roadmap outlines the project's current status and future plans:
|
|
|
725
833
|
[issue #3](https://github.com/antebudimir/eslint-plugin-vanilla-extract/issues/3))
|
|
726
834
|
- Comprehensive rule testing.
|
|
727
835
|
- `no-px-unit` rule to disallow use of `px` units with configurable whitelist.
|
|
836
|
+
- `prefer-logical-properties` rule to enforce use of logical properties.
|
|
837
|
+
- `prefer-theme-tokens` rule to enforce theme tokens instead of hard-coded values for colors, spacing, font sizes, border radius, border widths, shadows, z-index, opacity, font weights, and transitions/animations (optionally evaluates helper functions and template literals).
|
|
728
838
|
|
|
729
839
|
### Current Work
|
|
730
840
|
|
|
731
|
-
-
|
|
841
|
+
- `no-unitless-values` rule that disallows numeric literals for CSS properties that are not unitless in CSS.
|
|
732
842
|
|
|
733
843
|
### Upcoming Features
|
|
734
844
|
|
|
735
|
-
- `prefer-theme-tokens` rule to enforce use of theme tokens instead of hard-coded values when available.
|
|
736
|
-
- `no-global-style` rule to disallow use of `globalStyle` function.
|
|
737
845
|
- `property-unit-match` rule to enforce valid units per CSS property specs. **Note**: This feature will only be
|
|
738
846
|
implemented if there's sufficient interest from the community.
|
|
739
847
|
- Option to sort properties within user-defined concentric groups alphabetically instead of following the concentric
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createThemeTokenVisitors } from './theme-token-visitor-creator.js';
|
|
2
|
+
const rule = {
|
|
3
|
+
meta: {
|
|
4
|
+
type: 'suggestion',
|
|
5
|
+
docs: {
|
|
6
|
+
description: 'require theme tokens instead of hard-coded values for colors, spacing, font sizes, and border radius',
|
|
7
|
+
recommended: false,
|
|
8
|
+
},
|
|
9
|
+
fixable: 'code',
|
|
10
|
+
// Suggestions are reported from helper modules, so static analysis in this file can’t detect them; disable the false positive.
|
|
11
|
+
// eslint-disable-next-line eslint-plugin/require-meta-has-suggestions
|
|
12
|
+
hasSuggestions: true,
|
|
13
|
+
schema: [
|
|
14
|
+
{
|
|
15
|
+
type: 'object',
|
|
16
|
+
properties: {
|
|
17
|
+
themeContracts: {
|
|
18
|
+
type: 'array',
|
|
19
|
+
items: {
|
|
20
|
+
type: 'string',
|
|
21
|
+
},
|
|
22
|
+
description: 'Array of theme contract file paths to analyze for intelligent token suggestions',
|
|
23
|
+
},
|
|
24
|
+
checkColors: {
|
|
25
|
+
type: 'boolean',
|
|
26
|
+
description: 'Check for hard-coded color values',
|
|
27
|
+
default: true,
|
|
28
|
+
},
|
|
29
|
+
checkSpacing: {
|
|
30
|
+
type: 'boolean',
|
|
31
|
+
description: 'Check for hard-coded spacing values',
|
|
32
|
+
default: true,
|
|
33
|
+
},
|
|
34
|
+
checkFontSizes: {
|
|
35
|
+
type: 'boolean',
|
|
36
|
+
description: 'Check for hard-coded font size values',
|
|
37
|
+
default: true,
|
|
38
|
+
},
|
|
39
|
+
checkBorderRadius: {
|
|
40
|
+
type: 'boolean',
|
|
41
|
+
description: 'Check for hard-coded border radius values',
|
|
42
|
+
default: true,
|
|
43
|
+
},
|
|
44
|
+
checkBorderWidths: {
|
|
45
|
+
type: 'boolean',
|
|
46
|
+
description: 'Check for hard-coded border width values',
|
|
47
|
+
default: true,
|
|
48
|
+
},
|
|
49
|
+
checkShadows: {
|
|
50
|
+
type: 'boolean',
|
|
51
|
+
description: 'Check for hard-coded shadow values',
|
|
52
|
+
default: true,
|
|
53
|
+
},
|
|
54
|
+
checkZIndex: {
|
|
55
|
+
type: 'boolean',
|
|
56
|
+
description: 'Check for hard-coded z-index values',
|
|
57
|
+
default: true,
|
|
58
|
+
},
|
|
59
|
+
checkOpacity: {
|
|
60
|
+
type: 'boolean',
|
|
61
|
+
description: 'Check for hard-coded opacity values',
|
|
62
|
+
default: true,
|
|
63
|
+
},
|
|
64
|
+
checkFontWeights: {
|
|
65
|
+
type: 'boolean',
|
|
66
|
+
description: 'Check for hard-coded font weight values',
|
|
67
|
+
default: true,
|
|
68
|
+
},
|
|
69
|
+
checkTransitions: {
|
|
70
|
+
type: 'boolean',
|
|
71
|
+
description: 'Check for hard-coded transition and animation values',
|
|
72
|
+
default: true,
|
|
73
|
+
},
|
|
74
|
+
allowedValues: {
|
|
75
|
+
type: 'array',
|
|
76
|
+
items: {
|
|
77
|
+
type: 'string',
|
|
78
|
+
},
|
|
79
|
+
description: 'Array of values that are allowed (e.g., "0", "auto", "100%")',
|
|
80
|
+
},
|
|
81
|
+
allowedProperties: {
|
|
82
|
+
type: 'array',
|
|
83
|
+
items: {
|
|
84
|
+
type: 'string',
|
|
85
|
+
},
|
|
86
|
+
description: 'Array of CSS properties to skip checking (supports both camelCase and kebab-case)',
|
|
87
|
+
},
|
|
88
|
+
autoFix: {
|
|
89
|
+
type: 'boolean',
|
|
90
|
+
description: 'Enable auto-fix for unambiguous token replacements',
|
|
91
|
+
default: false,
|
|
92
|
+
},
|
|
93
|
+
remBase: {
|
|
94
|
+
type: 'number',
|
|
95
|
+
description: 'Base font size for rem() calculations (default: 16)',
|
|
96
|
+
default: 16,
|
|
97
|
+
},
|
|
98
|
+
checkHelperFunctions: {
|
|
99
|
+
type: 'boolean',
|
|
100
|
+
description: 'Check helper function calls like rem(48) and suggest theme tokens (default: false)',
|
|
101
|
+
default: false,
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
additionalProperties: false,
|
|
105
|
+
},
|
|
106
|
+
],
|
|
107
|
+
messages: {
|
|
108
|
+
hardCodedValueWithToken: "Hard-coded {{property}} value '{{value}}' detected. Use theme token: {{tokenPath}}",
|
|
109
|
+
hardCodedValueGeneric: "Hard-coded {{property}} value '{{value}}' detected. Consider using a theme token from {{categoryHint}}",
|
|
110
|
+
hardCodedValueNoContract: "Hard-coded {{property}} value '{{value}}' detected. Consider using theme tokens for {{category}} values",
|
|
111
|
+
replaceWithToken: 'Replace with {{tokenPath}}',
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
create(context) {
|
|
115
|
+
const options = context.options[0] || {};
|
|
116
|
+
return createThemeTokenVisitors(context, options);
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
export default rule;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export interface TokenInfo {
|
|
2
|
+
value: string;
|
|
3
|
+
tokenPath: string;
|
|
4
|
+
category: 'color' | 'spacing' | 'fontSize' | 'borderRadius' | 'borderWidth' | 'shadow' | 'zIndex' | 'opacity' | 'fontWeight' | 'transition' | 'other';
|
|
5
|
+
}
|
|
6
|
+
export interface ThemeContract {
|
|
7
|
+
tokens: Map<string, TokenInfo[]>;
|
|
8
|
+
variableName: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Analyzes theme contract files to extract token values and their paths
|
|
12
|
+
*/
|
|
13
|
+
export declare class ThemeContractAnalyzer {
|
|
14
|
+
private contracts;
|
|
15
|
+
private evaluator;
|
|
16
|
+
/**
|
|
17
|
+
* Set rem base for evaluation (default: 16)
|
|
18
|
+
*/
|
|
19
|
+
setRemBase(base: number): void;
|
|
20
|
+
/**
|
|
21
|
+
* Load and analyze a theme contract file
|
|
22
|
+
*/
|
|
23
|
+
loadThemeContract(filePath: string, baseDir: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* Parse theme contract from source code
|
|
26
|
+
*/
|
|
27
|
+
private parseThemeContract;
|
|
28
|
+
/**
|
|
29
|
+
* Parse theme object and extract token values
|
|
30
|
+
*/
|
|
31
|
+
private parseThemeObject;
|
|
32
|
+
/**
|
|
33
|
+
* Categorize a token based on its path and value
|
|
34
|
+
*/
|
|
35
|
+
private categorizeToken;
|
|
36
|
+
/**
|
|
37
|
+
* Check if a value is a color
|
|
38
|
+
*/
|
|
39
|
+
private isColor;
|
|
40
|
+
/**
|
|
41
|
+
* Normalize a value for comparison
|
|
42
|
+
*/
|
|
43
|
+
private normalizeValue;
|
|
44
|
+
/**
|
|
45
|
+
* Find matching tokens for a given value and category
|
|
46
|
+
*/
|
|
47
|
+
findMatchingTokens(value: string, category?: TokenInfo['category']): TokenInfo[];
|
|
48
|
+
/**
|
|
49
|
+
* Get the primary variable name from loaded contracts
|
|
50
|
+
*/
|
|
51
|
+
getVariableName(): string;
|
|
52
|
+
/**
|
|
53
|
+
* Check if any contracts are loaded
|
|
54
|
+
*/
|
|
55
|
+
hasContracts(): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Clear all loaded contracts
|
|
58
|
+
*/
|
|
59
|
+
clear(): void;
|
|
60
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { ValueEvaluator } from './value-evaluator.js';
|
|
4
|
+
/**
|
|
5
|
+
* Analyzes theme contract files to extract token values and their paths
|
|
6
|
+
*/
|
|
7
|
+
export class ThemeContractAnalyzer {
|
|
8
|
+
constructor() {
|
|
9
|
+
this.contracts = new Map();
|
|
10
|
+
this.evaluator = new ValueEvaluator();
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Set rem base for evaluation (default: 16)
|
|
14
|
+
*/
|
|
15
|
+
setRemBase(base) {
|
|
16
|
+
this.evaluator.setRemBase(base);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Load and analyze a theme contract file
|
|
20
|
+
*/
|
|
21
|
+
loadThemeContract(filePath, baseDir) {
|
|
22
|
+
const absolutePath = path.resolve(baseDir, filePath);
|
|
23
|
+
if (!fs.existsSync(absolutePath)) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const content = fs.readFileSync(absolutePath, 'utf-8');
|
|
28
|
+
const contract = this.parseThemeContract(content);
|
|
29
|
+
if (contract) {
|
|
30
|
+
this.contracts.set(filePath, contract);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Silently fail - theme file might not be available during linting
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parse theme contract from source code
|
|
39
|
+
*/
|
|
40
|
+
parseThemeContract(content) {
|
|
41
|
+
const tokens = new Map();
|
|
42
|
+
let variableName = 'theme';
|
|
43
|
+
// Try to extract theme variable name from exports
|
|
44
|
+
// Prefer the second identifier in destructuring like: export const [themeClass, vars] = createTheme(...)
|
|
45
|
+
const destructureMatch = content.match(/export\s+(?:const|let)\s*\[\s*(\w+)\s*,\s*(\w+)\s*\]\s*=/);
|
|
46
|
+
if (destructureMatch?.[2]) {
|
|
47
|
+
variableName = destructureMatch[2];
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
// Fallback: capture single identifier export
|
|
51
|
+
const exportMatch = content.match(/export\s+(?:const|let)\s+(\w+)\s*=|export\s+(?:const|let)\s*\[\s*(\w+)\s*\]/);
|
|
52
|
+
const candidate = exportMatch?.[1] || exportMatch?.[2];
|
|
53
|
+
if (candidate) {
|
|
54
|
+
variableName = candidate;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// Parse createTheme (one-arg), createTheme(contract, values), createGlobalTheme, or contract definitions
|
|
58
|
+
const createThemeTwoArg = content.match(/createTheme\s*\(\s*([A-Za-z_$][\w$]*)\s*,\s*({[\s\S]*?})\s*\)/);
|
|
59
|
+
const themeObjectMatch = content.match(/createTheme\s*\(\s*({[\s\S]*?})\s*\)/);
|
|
60
|
+
const globalThemeMatch = content.match(/createGlobalTheme\s*\([^,]+,\s*({[\s\S]*?})\s*\)/);
|
|
61
|
+
const contractMatch = content.match(/createThemeContract\s*\(\s*({[\s\S]*?})\s*\)/);
|
|
62
|
+
const themeContent = createThemeTwoArg?.[2] || themeObjectMatch?.[1] || globalThemeMatch?.[1] || contractMatch?.[1];
|
|
63
|
+
if (!themeContent) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
// If using createTheme(contractIdentifier, values), prefer the contract identifier for variable name (e.g., 'theme')
|
|
67
|
+
if (createThemeTwoArg?.[1]) {
|
|
68
|
+
variableName = createThemeTwoArg[1];
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
// Try to extract theme variable name from exports
|
|
72
|
+
// Prefer the second identifier in destructuring like: export const [themeClass, vars] = createTheme(...)
|
|
73
|
+
const destructureMatch = content.match(/export\s+(?:const|let)\s*\[\s*(\w+)\s*,\s*(\w+)\s*\]\s*=/);
|
|
74
|
+
if (destructureMatch?.[2]) {
|
|
75
|
+
variableName = destructureMatch[2];
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
// Fallback: capture single identifier export
|
|
79
|
+
const exportMatch = content.match(/export\s+(?:const|let)\s+(\w+)\s*=|export\s+(?:const|let)\s*\[\s*(\w+)\s*\]/);
|
|
80
|
+
const candidate = exportMatch?.[1] || exportMatch?.[2];
|
|
81
|
+
if (candidate) {
|
|
82
|
+
variableName = candidate;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Parse the theme object structure
|
|
87
|
+
this.parseThemeObject(themeContent, variableName, tokens);
|
|
88
|
+
return { tokens, variableName };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Parse theme object and extract token values
|
|
92
|
+
*/
|
|
93
|
+
parseThemeObject(content, variableName, tokens, pathPrefix = '') {
|
|
94
|
+
// Remove comments
|
|
95
|
+
const cleaned = content.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
96
|
+
// First, extract and process nested objects to avoid matching their contents
|
|
97
|
+
const objectRegex = /['"]?(\w+)['"]?\s*:\s*{([^{}]*(?:{[^{}]*}[^{}]*)*?)}/g;
|
|
98
|
+
const nestedObjects = [];
|
|
99
|
+
let objectMatch;
|
|
100
|
+
while ((objectMatch = objectRegex.exec(cleaned)) !== null) {
|
|
101
|
+
const key = objectMatch[1];
|
|
102
|
+
const nestedContent = objectMatch[2];
|
|
103
|
+
if (key && nestedContent) {
|
|
104
|
+
nestedObjects.push({ key, content: nestedContent });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
// Remove nested objects from content to avoid double-matching
|
|
108
|
+
let contentWithoutNested = cleaned;
|
|
109
|
+
nestedObjects.forEach(({ content }) => {
|
|
110
|
+
contentWithoutNested = contentWithoutNested.replace(content, '');
|
|
111
|
+
});
|
|
112
|
+
// Match key-value pairs - both string literals and expressions
|
|
113
|
+
// String literals: key: 'value' or key: "value" or key: `value`
|
|
114
|
+
const stringLiteralRegex = /['"]?(\w+)['"]?\s*:\s*(['"`])(.*?)\2/g;
|
|
115
|
+
// Expressions: key: rem(16) or key: clsx(...)
|
|
116
|
+
const expressionRegex = /['"]?(\w+)['"]?\s*:\s*([^,}\n]+?)(?=[,}\n])/g;
|
|
117
|
+
let match;
|
|
118
|
+
// First pass: extract string literals (only from content without nested objects)
|
|
119
|
+
while ((match = stringLiteralRegex.exec(contentWithoutNested)) !== null) {
|
|
120
|
+
const key = match[1];
|
|
121
|
+
const value = match[3];
|
|
122
|
+
if (!key || !value)
|
|
123
|
+
continue;
|
|
124
|
+
const tokenPath = pathPrefix ? `${pathPrefix}.${key}` : key;
|
|
125
|
+
const fullPath = `${variableName}.${tokenPath}`;
|
|
126
|
+
// Determine category based on key name and value
|
|
127
|
+
const category = this.categorizeToken(tokenPath, value);
|
|
128
|
+
// Normalize the value
|
|
129
|
+
const normalizedValue = this.normalizeValue(value);
|
|
130
|
+
if (normalizedValue) {
|
|
131
|
+
const existing = tokens.get(normalizedValue) || [];
|
|
132
|
+
existing.push({ value: normalizedValue, tokenPath: fullPath, category });
|
|
133
|
+
tokens.set(normalizedValue, existing);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// Second pass: extract and evaluate expressions (only from content without nested objects)
|
|
137
|
+
let exprMatch;
|
|
138
|
+
while ((exprMatch = expressionRegex.exec(contentWithoutNested)) !== null) {
|
|
139
|
+
const key = exprMatch[1];
|
|
140
|
+
let value = exprMatch[2];
|
|
141
|
+
if (!key || !value)
|
|
142
|
+
continue;
|
|
143
|
+
value = value.trim();
|
|
144
|
+
// Skip if it's a string literal (already processed)
|
|
145
|
+
if (value.startsWith('"') || value.startsWith("'") || value.startsWith('`')) {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
// Skip nested objects
|
|
149
|
+
if (value.startsWith('{')) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const tokenPath = pathPrefix ? `${pathPrefix}.${key}` : key;
|
|
153
|
+
const fullPath = `${variableName}.${tokenPath}`;
|
|
154
|
+
// Try to evaluate the expression
|
|
155
|
+
const evaluatedValue = this.evaluator.evaluate(value);
|
|
156
|
+
if (!evaluatedValue)
|
|
157
|
+
continue;
|
|
158
|
+
// Determine category based on key name and evaluated value
|
|
159
|
+
const category = this.categorizeToken(tokenPath, evaluatedValue);
|
|
160
|
+
// Normalize the evaluated value
|
|
161
|
+
const normalizedValue = this.normalizeValue(evaluatedValue);
|
|
162
|
+
if (normalizedValue) {
|
|
163
|
+
const existing = tokens.get(normalizedValue) || [];
|
|
164
|
+
existing.push({ value: normalizedValue, tokenPath: fullPath, category });
|
|
165
|
+
tokens.set(normalizedValue, existing);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// Process nested objects (already extracted earlier)
|
|
169
|
+
nestedObjects.forEach(({ key, content }) => {
|
|
170
|
+
const newPrefix = pathPrefix ? `${pathPrefix}.${key}` : key;
|
|
171
|
+
this.parseThemeObject(content, variableName, tokens, newPrefix);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Categorize a token based on its path and value
|
|
176
|
+
*/
|
|
177
|
+
categorizeToken(tokenPath, value) {
|
|
178
|
+
const lowerPath = tokenPath.toLowerCase();
|
|
179
|
+
// Check by path
|
|
180
|
+
if (lowerPath.includes('color') || lowerPath.includes('bg') || lowerPath.includes('background')) {
|
|
181
|
+
return 'color';
|
|
182
|
+
}
|
|
183
|
+
if (lowerPath.includes('spacing') || lowerPath.includes('space') || lowerPath.includes('gap')) {
|
|
184
|
+
return 'spacing';
|
|
185
|
+
}
|
|
186
|
+
if (lowerPath.includes('fontsize') || lowerPath.includes('font') && lowerPath.includes('size')) {
|
|
187
|
+
return 'fontSize';
|
|
188
|
+
}
|
|
189
|
+
if (lowerPath.includes('radius') || lowerPath.includes('radii')) {
|
|
190
|
+
return 'borderRadius';
|
|
191
|
+
}
|
|
192
|
+
if (lowerPath.includes('borderwidth') || lowerPath.includes('border') && lowerPath.includes('width')) {
|
|
193
|
+
return 'borderWidth';
|
|
194
|
+
}
|
|
195
|
+
if (lowerPath.includes('shadow')) {
|
|
196
|
+
return 'shadow';
|
|
197
|
+
}
|
|
198
|
+
if (lowerPath.includes('zindex') || lowerPath.includes('z-index') || lowerPath.includes('z')) {
|
|
199
|
+
return 'zIndex';
|
|
200
|
+
}
|
|
201
|
+
if (lowerPath.includes('opacity')) {
|
|
202
|
+
return 'opacity';
|
|
203
|
+
}
|
|
204
|
+
if (lowerPath.includes('fontweight') || lowerPath.includes('font') && lowerPath.includes('weight') || lowerPath.includes('weight')) {
|
|
205
|
+
return 'fontWeight';
|
|
206
|
+
}
|
|
207
|
+
if (lowerPath.includes('transition') || lowerPath.includes('animation') || lowerPath.includes('duration') || lowerPath.includes('delay')) {
|
|
208
|
+
return 'transition';
|
|
209
|
+
}
|
|
210
|
+
// Check by value pattern
|
|
211
|
+
if (this.isColor(value)) {
|
|
212
|
+
return 'color';
|
|
213
|
+
}
|
|
214
|
+
if (/^\d+(\.\d+)?(px|rem|em)$/.test(value)) {
|
|
215
|
+
if (/font|size/.test(lowerPath)) {
|
|
216
|
+
return 'fontSize';
|
|
217
|
+
}
|
|
218
|
+
if (/radius/.test(lowerPath)) {
|
|
219
|
+
return 'borderRadius';
|
|
220
|
+
}
|
|
221
|
+
if (/border.*width|width/.test(lowerPath)) {
|
|
222
|
+
return 'borderWidth';
|
|
223
|
+
}
|
|
224
|
+
return 'spacing';
|
|
225
|
+
}
|
|
226
|
+
if (/^-?\d+$/.test(value)) {
|
|
227
|
+
return 'zIndex';
|
|
228
|
+
}
|
|
229
|
+
if (/^(0?\.\d+|1(\.0+)?)$/.test(value)) {
|
|
230
|
+
return 'opacity';
|
|
231
|
+
}
|
|
232
|
+
if (/^[1-9]00$/.test(value) || /^(normal|bold|bolder|lighter)$/i.test(value)) {
|
|
233
|
+
return 'fontWeight';
|
|
234
|
+
}
|
|
235
|
+
if (/^\d+(\.\d+)?(s|ms)$/.test(value) || /(ease|linear|cubic-bezier|steps)/i.test(value)) {
|
|
236
|
+
return 'transition';
|
|
237
|
+
}
|
|
238
|
+
return 'other';
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Check if a value is a color
|
|
242
|
+
*/
|
|
243
|
+
isColor(value) {
|
|
244
|
+
return /^#[0-9a-f]{3,8}$/i.test(value) ||
|
|
245
|
+
/^rgba?\(/.test(value) ||
|
|
246
|
+
/^hsla?\(/.test(value);
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Normalize a value for comparison
|
|
250
|
+
*/
|
|
251
|
+
normalizeValue(value) {
|
|
252
|
+
const trimmed = value.trim();
|
|
253
|
+
// Normalize hex colors
|
|
254
|
+
if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
|
|
255
|
+
// Expand 3-digit hex to 6-digit
|
|
256
|
+
const r = trimmed[1];
|
|
257
|
+
const g = trimmed[2];
|
|
258
|
+
const b = trimmed[3];
|
|
259
|
+
return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();
|
|
260
|
+
}
|
|
261
|
+
if (/^#[0-9a-f]{6}$/i.test(trimmed)) {
|
|
262
|
+
return trimmed.toLowerCase();
|
|
263
|
+
}
|
|
264
|
+
// Normalize RGB/RGBA
|
|
265
|
+
const rgbMatch = trimmed.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)$/i);
|
|
266
|
+
if (rgbMatch?.[1] && rgbMatch[2] && rgbMatch[3]) {
|
|
267
|
+
const r = parseInt(rgbMatch[1]);
|
|
268
|
+
const g = parseInt(rgbMatch[2]);
|
|
269
|
+
const b = parseInt(rgbMatch[3]);
|
|
270
|
+
const a = rgbMatch[4];
|
|
271
|
+
if (a && a !== '1') {
|
|
272
|
+
return `rgba(${r}, ${g}, ${b}, ${a})`;
|
|
273
|
+
}
|
|
274
|
+
return `rgb(${r}, ${g}, ${b})`;
|
|
275
|
+
}
|
|
276
|
+
// Normalize spacing values
|
|
277
|
+
const spacingMatch = trimmed.match(/^(\d+(\.\d+)?)(px|rem|em|%)$/);
|
|
278
|
+
if (spacingMatch) {
|
|
279
|
+
return trimmed;
|
|
280
|
+
}
|
|
281
|
+
// Return as-is for other values
|
|
282
|
+
return trimmed || null;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Find matching tokens for a given value and category
|
|
286
|
+
*/
|
|
287
|
+
findMatchingTokens(value, category) {
|
|
288
|
+
const normalized = this.normalizeValue(value);
|
|
289
|
+
if (!normalized) {
|
|
290
|
+
return [];
|
|
291
|
+
}
|
|
292
|
+
const allMatches = [];
|
|
293
|
+
for (const contract of this.contracts.values()) {
|
|
294
|
+
const matches = contract.tokens.get(normalized) || [];
|
|
295
|
+
allMatches.push(...matches);
|
|
296
|
+
}
|
|
297
|
+
// Filter by category if specified
|
|
298
|
+
if (category) {
|
|
299
|
+
return allMatches.filter((token) => token.category === category);
|
|
300
|
+
}
|
|
301
|
+
return allMatches;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Get the primary variable name from loaded contracts
|
|
305
|
+
*/
|
|
306
|
+
getVariableName() {
|
|
307
|
+
const firstContract = Array.from(this.contracts.values())[0];
|
|
308
|
+
return firstContract?.variableName || 'theme';
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Check if any contracts are loaded
|
|
312
|
+
*/
|
|
313
|
+
hasContracts() {
|
|
314
|
+
return this.contracts.size > 0;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Clear all loaded contracts
|
|
318
|
+
*/
|
|
319
|
+
clear() {
|
|
320
|
+
this.contracts.clear();
|
|
321
|
+
}
|
|
322
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Rule } from 'eslint';
|
|
2
|
+
import { TSESTree } from '@typescript-eslint/utils';
|
|
3
|
+
import type { ThemeContractAnalyzer } from './theme-contract-analyzer.js';
|
|
4
|
+
export interface ThemeTokenOptions {
|
|
5
|
+
themeContracts?: string[];
|
|
6
|
+
checkColors?: boolean;
|
|
7
|
+
checkSpacing?: boolean;
|
|
8
|
+
checkFontSizes?: boolean;
|
|
9
|
+
checkBorderRadius?: boolean;
|
|
10
|
+
checkBorderWidths?: boolean;
|
|
11
|
+
checkShadows?: boolean;
|
|
12
|
+
checkZIndex?: boolean;
|
|
13
|
+
checkOpacity?: boolean;
|
|
14
|
+
checkFontWeights?: boolean;
|
|
15
|
+
checkTransitions?: boolean;
|
|
16
|
+
allowedValues?: string[];
|
|
17
|
+
allowedProperties?: string[];
|
|
18
|
+
autoFix?: boolean;
|
|
19
|
+
remBase?: number;
|
|
20
|
+
checkHelperFunctions?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Recursively processes a vanilla-extract style object and reports hard-coded values
|
|
24
|
+
* that should use theme tokens instead.
|
|
25
|
+
*/
|
|
26
|
+
export declare const processThemeTokensInStyleObject: (context: Rule.RuleContext, node: TSESTree.ObjectExpression, options: ThemeTokenOptions, analyzer: ThemeContractAnalyzer) => void;
|