@antebudimir/eslint-plugin-vanilla-extract 1.14.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/README.md +111 -3
  2. package/dist/css-rules/no-empty-blocks/empty-style-visitor-creator.js +8 -2
  3. package/dist/css-rules/no-empty-blocks/recipe-processor.js +23 -3
  4. package/dist/css-rules/prefer-theme-tokens/index.d.ts +2 -0
  5. package/dist/css-rules/prefer-theme-tokens/index.js +2 -0
  6. package/dist/css-rules/prefer-theme-tokens/rule-definition.d.ts +3 -0
  7. package/dist/css-rules/prefer-theme-tokens/rule-definition.js +119 -0
  8. package/dist/css-rules/prefer-theme-tokens/theme-contract-analyzer.d.ts +60 -0
  9. package/dist/css-rules/prefer-theme-tokens/theme-contract-analyzer.js +322 -0
  10. package/dist/css-rules/prefer-theme-tokens/theme-token-processor.d.ts +26 -0
  11. package/dist/css-rules/prefer-theme-tokens/theme-token-processor.js +562 -0
  12. package/dist/css-rules/prefer-theme-tokens/theme-token-visitor-creator.d.ts +6 -0
  13. package/dist/css-rules/{no-px-unit/visitor-creator.js → prefer-theme-tokens/theme-token-visitor-creator.js} +36 -10
  14. package/dist/css-rules/prefer-theme-tokens/value-evaluator.d.ts +43 -0
  15. package/dist/css-rules/prefer-theme-tokens/value-evaluator.js +190 -0
  16. package/dist/css-rules/shared-utils/empty-object-processor.d.ts +5 -0
  17. package/dist/css-rules/shared-utils/empty-object-processor.js +11 -0
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +3 -1
  20. package/package.json +6 -1
  21. package/dist/css-rules/no-px-unit/no-px-unit-visitor-creator.d.ts +0 -2
  22. package/dist/css-rules/no-px-unit/no-px-unit-visitor-creator.js +0 -55
  23. package/dist/css-rules/no-px-unit/processor.d.ts +0 -3
  24. package/dist/css-rules/no-px-unit/processor.js +0 -93
  25. package/dist/css-rules/no-px-unit/visitor-creator.d.ts +0 -2
  26. package/dist/sample.css.d.ts +0 -75
  27. package/dist/sample.css.js +0 -540
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
- - TBA
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
@@ -1,5 +1,5 @@
1
1
  import { TSESTree } from '@typescript-eslint/utils';
2
- import { isEmptyObject } from '../shared-utils/empty-object-processor.js';
2
+ import { isCallExpressionWithEmptyObject, isEmptyObject } from '../shared-utils/empty-object-processor.js';
3
3
  import { ReferenceTracker, createReferenceTrackingVisitor } from '../shared-utils/reference-tracker.js';
4
4
  import { processConditionalExpression } from './conditional-processor.js';
5
5
  import { processEmptyNestedStyles } from './empty-nested-style-processor.js';
@@ -48,7 +48,13 @@ export const isEffectivelyEmptyStylesObject = (stylesObject) => {
48
48
  }
49
49
  if (propertyName === 'base') {
50
50
  hasBaseProperty = true;
51
- if (property.value.type === 'ObjectExpression' && !isEmptyObject(property.value)) {
51
+ // CallExpression (e.g., sprinkles(), style()) is considered non-empty unless it has an empty object argument, e.g. sprinkles({})
52
+ if (property.value.type === 'CallExpression') {
53
+ if (!isCallExpressionWithEmptyObject(property.value)) {
54
+ isBaseEmpty = false;
55
+ }
56
+ }
57
+ else if (property.value.type === 'ObjectExpression' && !isEmptyObject(property.value)) {
52
58
  isBaseEmpty = false;
53
59
  }
54
60
  }
@@ -1,5 +1,5 @@
1
1
  import { TSESTree } from '@typescript-eslint/utils';
2
- import { isEmptyObject } from '../shared-utils/empty-object-processor.js';
2
+ import { isCallExpressionWithEmptyObject, isEmptyObject } from '../shared-utils/empty-object-processor.js';
3
3
  import { processEmptyNestedStyles } from './empty-nested-style-processor.js';
4
4
  import { removeNodeWithComma } from './node-remover.js';
5
5
  import { areAllChildrenEmpty, getStyleKeyName } from './property-utils.js';
@@ -71,8 +71,28 @@ export const processRecipeProperties = (ruleContext, recipeNode, reportedNodes)
71
71
  if (variantValueProperty.type !== 'Property') {
72
72
  return;
73
73
  }
74
- // Check for non-object variant values
75
- if (variantValueProperty.value.type !== 'ObjectExpression') {
74
+ const valueType = variantValueProperty.value.type;
75
+ // Allow CallExpression (e.g., sprinkles(), style()) as valid variant values unless it has an empty object argument, e.g. sprinkles({})
76
+ if (valueType === 'CallExpression') {
77
+ const callExpression = variantValueProperty.value;
78
+ if (isCallExpressionWithEmptyObject(callExpression)) {
79
+ // Treat sprinkles({}) or style({}) as empty
80
+ if (!reportedNodes.has(variantValueProperty)) {
81
+ reportedNodes.add(variantValueProperty);
82
+ ruleContext.report({
83
+ node: variantValueProperty,
84
+ messageId: 'emptyVariantValue',
85
+ fix(fixer) {
86
+ return removeNodeWithComma(ruleContext, variantValueProperty, fixer);
87
+ },
88
+ });
89
+ }
90
+ }
91
+ // Valid CallExpressions with arguments are fine
92
+ return;
93
+ }
94
+ // Check for non-object variant values (excluding CallExpression)
95
+ if (valueType !== 'ObjectExpression') {
76
96
  if (!reportedNodes.has(variantValueProperty)) {
77
97
  reportedNodes.add(variantValueProperty);
78
98
  // Get a user-friendly type description as a string
@@ -0,0 +1,2 @@
1
+ import preferThemeTokensRule from './rule-definition.js';
2
+ export default preferThemeTokensRule;
@@ -0,0 +1,2 @@
1
+ import preferThemeTokensRule from './rule-definition.js';
2
+ export default preferThemeTokensRule;
@@ -0,0 +1,3 @@
1
+ import type { Rule } from 'eslint';
2
+ declare const rule: Rule.RuleModule;
3
+ export default rule;
@@ -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
+ }