@antebudimir/eslint-plugin-vanilla-extract 1.11.1 → 1.13.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.
Files changed (30) hide show
  1. package/README.md +84 -14
  2. package/dist/css-rules/no-px-unit/_tests_/no-px-unit.test.d.ts +1 -0
  3. package/dist/css-rules/no-px-unit/_tests_/no-px-unit.test.js +163 -0
  4. package/dist/css-rules/no-px-unit/index.d.ts +2 -0
  5. package/dist/css-rules/no-px-unit/index.js +2 -0
  6. package/dist/css-rules/no-px-unit/no-px-unit-visitor-creator.d.ts +2 -0
  7. package/dist/css-rules/no-px-unit/no-px-unit-visitor-creator.js +55 -0
  8. package/dist/css-rules/no-px-unit/processor.d.ts +3 -0
  9. package/dist/css-rules/no-px-unit/processor.js +93 -0
  10. package/dist/css-rules/no-px-unit/px-unit-processor.d.ts +14 -0
  11. package/dist/css-rules/no-px-unit/px-unit-processor.js +104 -0
  12. package/dist/css-rules/no-px-unit/px-unit-visitor-creator.d.ts +11 -0
  13. package/dist/css-rules/no-px-unit/px-unit-visitor-creator.js +64 -0
  14. package/dist/css-rules/no-px-unit/rule-definition.d.ts +3 -0
  15. package/dist/css-rules/no-px-unit/rule-definition.js +37 -0
  16. package/dist/css-rules/no-px-unit/visitor-creator.d.ts +2 -0
  17. package/dist/css-rules/no-px-unit/visitor-creator.js +55 -0
  18. package/dist/css-rules/no-trailing-zero/_tests_/no-trailing-zero.test.d.ts +1 -0
  19. package/dist/css-rules/no-trailing-zero/_tests_/no-trailing-zero.test.js +537 -0
  20. package/dist/css-rules/no-trailing-zero/index.d.ts +1 -0
  21. package/dist/css-rules/no-trailing-zero/index.js +1 -0
  22. package/dist/css-rules/no-trailing-zero/rule-definition.d.ts +3 -0
  23. package/dist/css-rules/no-trailing-zero/rule-definition.js +20 -0
  24. package/dist/css-rules/no-trailing-zero/trailing-zero-processor.d.ts +31 -0
  25. package/dist/css-rules/no-trailing-zero/trailing-zero-processor.js +165 -0
  26. package/dist/css-rules/no-trailing-zero/trailing-zero-visitor-creator.d.ts +9 -0
  27. package/dist/css-rules/no-trailing-zero/trailing-zero-visitor-creator.js +85 -0
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +6 -1
  30. package/package.json +2 -2
package/README.md CHANGED
@@ -15,11 +15,7 @@
15
15
 
16
16
  ---
17
17
 
18
- An ESLint plugin for enforcing best practices in
19
- [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract) CSS styles, including CSS property ordering
20
- and additional linting rules. Available presets are for alphabetical and
21
- [concentric](https://rhodesmill.org/brandon/2011/concentric-css/) CSS ordering. The plugin also supports a custom group
22
- ordering option based on groups available in [concentric CSS](src/css-rules/concentric-order/concentric-groups.ts).
18
+ Comprehensive ESLint plugin for vanilla-extract that enforces best practices in [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract) CSS styles. Includes support for CSS property ordering (alphabetical, [concentric](https://rhodesmill.org/brandon/2011/concentric-css/), and custom group ordering), advanced style linting rules, auto-fixing, and validation of style patterns specific to vanilla-extract. Ensures zero-runtime safety and integrates with multiple vanilla-extract APIs to promote maintainable, consistent code across projects
23
19
 
24
20
  ## Demo
25
21
 
@@ -257,8 +253,9 @@ For VS Code users, add these settings to your `.vscode/settings.json`:
257
253
 
258
254
  The recommended configuration enables the following rules with error severity:
259
255
 
260
- - `vanilla-extract/concentric-order`: Enforces concentric CSS property ordering
256
+ - `vanilla-extract/concentric-order`: Enforces [concentric CSS](#concentric-css-model) property ordering
261
257
  - `vanilla-extract/no-empty-style-blocks`: Prevents empty style blocks
258
+ - `vanilla-extract/no-trailing-zero`: Disallows trailing zeros in numeric CSS values
262
259
  - `vanilla-extract/no-unknown-unit`: Prohibits usage of unrecognized CSS units
263
260
  - `vanilla-extract/no-zero-unit`: Removes unnecessary units for zero values
264
261
 
@@ -266,6 +263,7 @@ The recommended configuration enables the following rules with error severity:
266
263
 
267
264
  - `vanilla-extract/alphabetical-order`: Alternative ordering rule (alphabetical sorting)
268
265
  - `vanilla-extract/custom-order`: Alternative ordering rule (custom group-based sorting)
266
+ - `vanilla-extract/no-px-unit`: Disallows px units with an optional allowlist
269
267
 
270
268
  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.
271
269
 
@@ -337,8 +335,7 @@ export const myStyle = style({
337
335
 
338
336
  ### vanilla-extract/concentric-order
339
337
 
340
- This rule enforces that CSS properties in vanilla-extract style objects follow the concentric CSS ordering pattern,
341
- which organizes properties from outside to inside.
338
+ This rule enforces that CSS properties in vanilla-extract style objects follow the [concentric CSS](#concentric-css-model) ordering pattern, which organizes properties from outside to inside.
342
339
 
343
340
  ```typescript
344
341
  // ❌ Incorrect
@@ -368,7 +365,7 @@ export const myStyle = style({
368
365
 
369
366
  The `vanilla-extract/custom-order` rule enables you to enforce a custom ordering of CSS properties in your
370
367
  vanilla-extract styles. You can specify an array of property groups in your preferred order, and the rule will ensure
371
- that properties within these groups are sorted according to their position in the concentric CSS model.
368
+ that properties within these groups are sorted according to their position in the [concentric CSS model](https://rhodesmill.org/brandon/2011/concentric-css/).
372
369
 
373
370
  Key features of this rule include:
374
371
 
@@ -464,7 +461,80 @@ export const recipeWithEmptyVariants = recipe({
464
461
  });
465
462
  ```
466
463
 
467
- ## vanilla-extract/no-unknown-unit
464
+ ### vanilla-extract/no-px-unit
465
+
466
+ This rule disallows the use of hard-coded `px` units in vanilla-extract style declarations. Prefer `rem`, `em`, or theme tokens. A configurable allowlist lets you permit specific properties to use `px` where necessary. Allowlist supports both camelCase and kebab-case property names.
467
+
468
+ Configuration with an allowlist:
469
+
470
+ ```json
471
+ {
472
+ "rules": {
473
+ "vanilla-extract/no-px-unit": ["error", { "allow": ["borderWidth", "outline-offset"] }]
474
+ }
475
+ }
476
+ ```
477
+
478
+ Before:
479
+
480
+ ```typescript
481
+ import { style } from '@vanilla-extract/css';
482
+
483
+ export const box = style({
484
+ marginTop: '8px',
485
+ padding: '16px',
486
+ selectors: {
487
+ '&:hover': { gap: '4px' },
488
+ },
489
+ });
490
+ ```
491
+
492
+ After (suggested fix shown using rem):
493
+
494
+ ```typescript
495
+ import { style } from '@vanilla-extract/css';
496
+
497
+ export const box = style({
498
+ marginTop: '8rem',
499
+ padding: '16rem',
500
+ selectors: {
501
+ '&:hover': { gap: '4rem' },
502
+ },
503
+ });
504
+ ```
505
+
506
+ ### vanilla-extract/no-trailing-zero
507
+
508
+ This rule disallows trailing zeros in numeric CSS values within vanilla-extract style objects. It helps maintain cleaner
509
+ and more consistent CSS by removing unnecessary trailing zeros from decimal numbers.
510
+
511
+ ```typescript
512
+ // ❌ Incorrect
513
+ import { style } from '@vanilla-extract/css';
514
+
515
+ export const myStyle = style({
516
+ margin: '1.0px',
517
+ padding: '2.50rem',
518
+ opacity: 1.0,
519
+ lineHeight: 2.50,
520
+ width: '0.0em',
521
+ transition: 'all 0.30s ease',
522
+ });
523
+
524
+ // ✅ Correct
525
+ import { style } from '@vanilla-extract/css';
526
+
527
+ export const myStyle = style({
528
+ margin: '1px',
529
+ padding: '2.5rem',
530
+ opacity: 1,
531
+ lineHeight: 2.5,
532
+ width: '0',
533
+ transition: 'all 0.3s ease',
534
+ });
535
+ ```
536
+
537
+ ### vanilla-extract/no-unknown-unit
468
538
 
469
539
  This rule enforces the use of valid CSS units in vanilla-extract style objects. It prevents typos and non-standard units
470
540
  that could cause styling issues or browser compatibility problems.
@@ -503,7 +573,7 @@ export const myRecipe = recipe({
503
573
  });
504
574
  ```
505
575
 
506
- ## vanilla-extract/no-zero-unit
576
+ ### vanilla-extract/no-zero-unit
507
577
 
508
578
  This rule enforces the removal of unnecessary units for zero values in vanilla-extract style objects. It helps maintain
509
579
  cleaner and more consistent CSS by eliminating redundant units when the value is zero.
@@ -612,17 +682,17 @@ The roadmap outlines the project's current status and future plans:
612
682
  - Recommended ESLint configuration for the plugin.
613
683
  - `no-zero-unit` rule to disallow units when the value is zero.
614
684
  - `no-unknown-unit` rule to disallow unknown units.
615
- - Support for using the plugin’s recommended config via the extends field (as discussed in
685
+ - `no-trailing-zero` rule to disallow trailing zeros in numbers.
686
+ - Support for using the plugin's recommended config via the extends field (as discussed in
616
687
  [issue #3](https://github.com/antebudimir/eslint-plugin-vanilla-extract/issues/3))
617
688
  - Comprehensive rule testing.
618
689
 
619
690
  ### Current Work
620
691
 
621
- - `no-number-trailing-zero` rule to disallow trailing zeros in numbers.
692
+ - `no-px-unit` rule to disallow use of `px` units with configurable whitelist.
622
693
 
623
694
  ### Upcoming Features
624
695
 
625
- - `no-px-unit` rule to disallow use of `px` units with configurable whitelist.
626
696
  - `prefer-logical-properties` rule to enforce use of logical properties.
627
697
  - `prefer-theme-tokens` rule to enforce use of theme tokens instead of hard-coded values when available.
628
698
  - `no-global-style` rule to disallow use of `globalStyle` function.
@@ -0,0 +1,163 @@
1
+ import tsParser from '@typescript-eslint/parser';
2
+ import { run } from 'eslint-vitest-rule-tester';
3
+ import noPxUnitRule from '../rule-definition.js';
4
+ run({
5
+ name: 'vanilla-extract/no-px-unit',
6
+ rule: noPxUnitRule,
7
+ languageOptions: {
8
+ parser: tsParser,
9
+ parserOptions: {
10
+ ecmaVersion: 2022,
11
+ sourceType: 'module',
12
+ },
13
+ },
14
+ valid: [
15
+ {
16
+ code: `
17
+ import { style } from '@vanilla-extract/css';
18
+ const myStyle = style({
19
+ margin: '1rem',
20
+ padding: 8,
21
+ width: '100%',
22
+ color: vars.color.primary,
23
+ });
24
+ `,
25
+ name: 'allows rem, numbers, and token references',
26
+ },
27
+ {
28
+ code: `
29
+ import { style } from '@vanilla-extract/css';
30
+ const myStyle = style({
31
+ borderWidth: '1px',
32
+ outlineOffset: '2px',
33
+ });
34
+ `,
35
+ options: [{ allow: ['border-width', 'outline-offset', 'borderWidth', 'outlineOffset'] }],
36
+ name: 'respects allowlist for kebab and camelCase',
37
+ },
38
+ {
39
+ code: `
40
+ import { recipe } from '@vanilla-extract/css';
41
+ const myRecipe = recipe({
42
+ base: { margin: '1rem' },
43
+ variants: {
44
+ size: {
45
+ sm: { padding: '0.5rem' },
46
+ },
47
+ },
48
+ });
49
+ `,
50
+ name: 'passes when no px in recipe base/variants',
51
+ },
52
+ {
53
+ code: `
54
+ import { style } from '@vanilla-extract/css';
55
+ const s = style({
56
+ border: '1px solid',
57
+ borderWidth: '2px'
58
+ });
59
+ `,
60
+ options: [{ allow: ['borderWidth', 'border'] }],
61
+ name: 'does not report whitelisted properties',
62
+ },
63
+ ],
64
+ invalid: [
65
+ {
66
+ code: `
67
+ import { style } from '@vanilla-extract/css';
68
+ const myStyle = style({
69
+ margin: '10px',
70
+ padding: '2px',
71
+ });
72
+ `,
73
+ errors: [{ messageId: 'noPxUnit' }, { messageId: 'noPxUnit' }],
74
+ },
75
+ {
76
+ code: `
77
+ import { style } from '@vanilla-extract/css';
78
+ const s = style({
79
+ '@media': {
80
+ '(min-width: 768px)': {
81
+ lineHeight: '12px',
82
+ }
83
+ },
84
+ selectors: {
85
+ '&:hover': { gap: '4px' }
86
+ }
87
+ });
88
+ `,
89
+ errors: [{ messageId: 'noPxUnit' }, { messageId: 'noPxUnit' }],
90
+ name: 'reports within nested @media and selectors',
91
+ },
92
+ {
93
+ code: `
94
+ import { recipe } from '@vanilla-extract/css';
95
+ const r = recipe({
96
+ base: { marginTop: '3px' },
97
+ variants: { size: { md: { paddingBottom: '6px' } } }
98
+ });
99
+ `,
100
+ errors: [{ messageId: 'noPxUnit' }, { messageId: 'noPxUnit' }],
101
+ name: 'reports within recipe base and variants',
102
+ },
103
+ {
104
+ code: `
105
+ import { fontFace } from '@vanilla-extract/css';
106
+ fontFace({ sizeAdjust: '10px' });
107
+ `,
108
+ errors: [{ messageId: 'noPxUnit' }],
109
+ name: 'reports in fontFace() first-arg object (covers fontFace branch)',
110
+ },
111
+ {
112
+ code: `
113
+ import { globalFontFace } from '@vanilla-extract/css';
114
+ globalFontFace('MyFont', { lineGapOverride: '12px' });
115
+ `,
116
+ errors: [{ messageId: 'noPxUnit' }],
117
+ name: 'reports in globalFontFace() second-arg object (covers globalFontFace branch)',
118
+ },
119
+ {
120
+ code: `
121
+ import { globalStyle } from '@vanilla-extract/css';
122
+ globalStyle('html', { boxShadow: '0 1px 2px black' });
123
+ `,
124
+ errors: [{ messageId: 'noPxUnit' }],
125
+ name: 'reports in globalStyle() second-arg object (covers globalStyle branch)',
126
+ },
127
+ {
128
+ code: `
129
+ import { globalKeyframes } from '@vanilla-extract/css';
130
+ globalKeyframes('fade', {
131
+ from: { margin: '5px' },
132
+ to: { padding: '3px' }
133
+ });
134
+ `,
135
+ errors: [{ messageId: 'noPxUnit' }, { messageId: 'noPxUnit' }],
136
+ name: 'reports in globalKeyframes() frames (covers globalKeyframes branch)',
137
+ },
138
+ {
139
+ code: `
140
+ import { style } from '@vanilla-extract/css';
141
+ const s = style({
142
+ margin: ` +
143
+ '`10px`' +
144
+ `,
145
+ });
146
+ `,
147
+ errors: [{ messageId: 'noPxUnit' }],
148
+ name: 'reports for simple template literal with px',
149
+ },
150
+ {
151
+ code: `
152
+ import { style } from '@vanilla-extract/css';
153
+ const s = style({
154
+ margin: ` +
155
+ '`${token}px`' +
156
+ `,
157
+ });
158
+ `,
159
+ errors: [{ messageId: 'noPxUnit' }],
160
+ name: 'reports for complex template literals with expressions containing px',
161
+ },
162
+ ],
163
+ });
@@ -0,0 +1,2 @@
1
+ import noPxUnitRule from './rule-definition.js';
2
+ export default noPxUnitRule;
@@ -0,0 +1,2 @@
1
+ import noPxUnitRule from './rule-definition.js';
2
+ export default noPxUnitRule;
@@ -0,0 +1,2 @@
1
+ import type { Rule } from 'eslint';
2
+ export declare const createNoPxUnitVisitors: (context: Rule.RuleContext) => Rule.RuleListener;
@@ -0,0 +1,55 @@
1
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ import { processRecipeProperties } from '../shared-utils/recipe-property-processor.js';
3
+ import { ReferenceTracker, createReferenceTrackingVisitor } from '../shared-utils/reference-tracker.js';
4
+ import { processStyleNode } from '../shared-utils/style-node-processor.js';
5
+ import { processNoPxUnitInStyleObject } from './processor.js';
6
+ export const createNoPxUnitVisitors = (context) => {
7
+ const tracker = new ReferenceTracker();
8
+ const trackingVisitor = createReferenceTrackingVisitor(tracker);
9
+ const options = context.options?.[0] || {};
10
+ const allowSet = new Set((options.allow ?? []).map((s) => s));
11
+ const process = (ctx, obj) => processNoPxUnitInStyleObject(ctx, obj, allowSet);
12
+ return {
13
+ ...trackingVisitor,
14
+ CallExpression(node) {
15
+ if (node.callee.type !== AST_NODE_TYPES.Identifier)
16
+ return;
17
+ const functionName = node.callee.name;
18
+ if (!tracker.isTrackedFunction(functionName))
19
+ return;
20
+ const originalName = tracker.getOriginalName(functionName);
21
+ if (!originalName)
22
+ return;
23
+ switch (originalName) {
24
+ case 'fontFace':
25
+ if (node.arguments.length > 0 && node.arguments[0]?.type === AST_NODE_TYPES.ObjectExpression) {
26
+ process(context, node.arguments[0]);
27
+ }
28
+ break;
29
+ case 'globalFontFace':
30
+ if (node.arguments.length > 1 && node.arguments[1]?.type === AST_NODE_TYPES.ObjectExpression) {
31
+ process(context, node.arguments[1]);
32
+ }
33
+ break;
34
+ case 'style':
35
+ case 'styleVariants':
36
+ case 'keyframes':
37
+ if (node.arguments.length > 0) {
38
+ processStyleNode(context, node.arguments[0], (ctx, obj) => process(ctx, obj));
39
+ }
40
+ break;
41
+ case 'globalStyle':
42
+ case 'globalKeyframes':
43
+ if (node.arguments.length >= 2) {
44
+ processStyleNode(context, node.arguments[1], (ctx, obj) => process(ctx, obj));
45
+ }
46
+ break;
47
+ case 'recipe':
48
+ if (node.arguments.length > 0 && node.arguments[0]?.type === AST_NODE_TYPES.ObjectExpression) {
49
+ processRecipeProperties(context, node.arguments[0], (ctx, obj) => process(ctx, obj));
50
+ }
51
+ break;
52
+ }
53
+ },
54
+ };
55
+ };
@@ -0,0 +1,3 @@
1
+ import type { Rule } from 'eslint';
2
+ import { TSESTree } from '@typescript-eslint/utils';
3
+ export declare const processNoPxUnitInStyleObject: (context: Rule.RuleContext, node: TSESTree.ObjectExpression, allowSet: Set<string>) => void;
@@ -0,0 +1,93 @@
1
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ const containsPx = (text) => /(^|\W)-?\d*\.?\d*px(?![a-zA-Z])/i.test(text);
3
+ const replacePxWith = (text, replacement) => text.replace(/px(?![a-zA-Z])/g, replacement);
4
+ const toKebab = (name) => name.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
5
+ const getValueText = (node) => {
6
+ if (node.type === AST_NODE_TYPES.Literal && typeof node.value === 'string') {
7
+ return node.value;
8
+ }
9
+ if (node.type === AST_NODE_TYPES.TemplateLiteral) {
10
+ // Join all quasis (ignore expressions content)
11
+ const raw = node.quasis.map((q) => q.value.raw ?? '').join('');
12
+ return raw;
13
+ }
14
+ return null;
15
+ };
16
+ const canSuggestFix = (node) => {
17
+ if (node.type === AST_NODE_TYPES.Literal && typeof node.value === 'string')
18
+ return 'literal';
19
+ if (node.type === AST_NODE_TYPES.TemplateLiteral && node.expressions.length === 0)
20
+ return 'simple-template';
21
+ return null;
22
+ };
23
+ export const processNoPxUnitInStyleObject = (context, node, allowSet) => {
24
+ for (const property of node.properties) {
25
+ if (property.type !== AST_NODE_TYPES.Property)
26
+ continue;
27
+ // Determine property name when possible
28
+ let propertyName = null;
29
+ if (property.key.type === AST_NODE_TYPES.Identifier) {
30
+ propertyName = property.key.name;
31
+ }
32
+ else if (property.key.type === AST_NODE_TYPES.Literal && typeof property.key.value === 'string') {
33
+ propertyName = property.key.value;
34
+ }
35
+ // Recurse into known nested containers
36
+ if (propertyName === '@media' || propertyName === 'selectors') {
37
+ if (property.value.type === AST_NODE_TYPES.ObjectExpression) {
38
+ for (const nested of property.value.properties) {
39
+ if (nested.type === AST_NODE_TYPES.Property && nested.value.type === AST_NODE_TYPES.ObjectExpression) {
40
+ processNoPxUnitInStyleObject(context, nested.value, allowSet);
41
+ }
42
+ }
43
+ }
44
+ continue;
45
+ }
46
+ // Traverse any nested object
47
+ if (property.value.type === AST_NODE_TYPES.ObjectExpression) {
48
+ processNoPxUnitInStyleObject(context, property.value, allowSet);
49
+ continue;
50
+ }
51
+ // Skip if property is whitelisted (supports both camelCase and kebab-case)
52
+ if (propertyName) {
53
+ const kebab = toKebab(propertyName);
54
+ if (allowSet.has(propertyName) || allowSet.has(kebab)) {
55
+ continue;
56
+ }
57
+ }
58
+ // Check string or template literal values
59
+ const text = getValueText(property.value);
60
+ if (text && containsPx(text)) {
61
+ const fixability = canSuggestFix(property.value);
62
+ context.report({
63
+ node: property.value,
64
+ messageId: 'noPxUnit',
65
+ suggest: fixability
66
+ ? [
67
+ {
68
+ messageId: 'removePx',
69
+ fix: (fixer) => {
70
+ const newText = replacePxWith(text, '');
71
+ if (fixability === 'literal') {
72
+ return fixer.replaceText(property.value, `'${newText}'`);
73
+ }
74
+ // simple template with no expressions
75
+ return fixer.replaceText(property.value, `\`${newText}\``);
76
+ },
77
+ },
78
+ {
79
+ messageId: 'replaceWithRem',
80
+ fix: (fixer) => {
81
+ const newText = replacePxWith(text, 'rem');
82
+ if (fixability === 'literal') {
83
+ return fixer.replaceText(property.value, `'${newText}'`);
84
+ }
85
+ return fixer.replaceText(property.value, `\`${newText}\``);
86
+ },
87
+ },
88
+ ]
89
+ : undefined,
90
+ });
91
+ }
92
+ }
93
+ };
@@ -0,0 +1,14 @@
1
+ import type { Rule } from 'eslint';
2
+ import { TSESTree } from '@typescript-eslint/utils';
3
+ /**
4
+ * Recursively processes a vanilla-extract style object and reports occurrences of 'px' units.
5
+ *
6
+ * - Skips properties present in the allow list (supports camelCase and kebab-case).
7
+ * - Traverses nested object values and delegates deeper traversal to callers for arrays/at-rules/selectors.
8
+ * - Provides fix suggestions for string literals and simple template literals (no expressions).
9
+ *
10
+ * @param context ESLint rule context used to report diagnostics and apply suggestions.
11
+ * @param node The ObjectExpression node representing the style object to inspect.
12
+ * @param allowSet Set of property names (camelCase or kebab-case) that are allowed to contain 'px'.
13
+ */
14
+ export declare const processNoPxUnitInStyleObject: (context: Rule.RuleContext, node: TSESTree.ObjectExpression, allowSet: Set<string>) => void;
@@ -0,0 +1,104 @@
1
+ import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
2
+ const containsPx = (text) => /(^|\W)-?\d*\.?\d*px(?![a-zA-Z])/i.test(text);
3
+ const replacePxWith = (text, replacement) => text.replace(/px(?![a-zA-Z])/g, replacement);
4
+ const toKebab = (name) => name.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
5
+ const getValueText = (node) => {
6
+ if (node.type === AST_NODE_TYPES.Literal && typeof node.value === 'string') {
7
+ return node.value;
8
+ }
9
+ if (node.type === AST_NODE_TYPES.TemplateLiteral) {
10
+ // Join all quasis (ignore expressions content)
11
+ const raw = node.quasis.map((quasi) => quasi.value.raw ?? '').join('');
12
+ return raw;
13
+ }
14
+ return null;
15
+ };
16
+ const canSuggestFix = (node) => {
17
+ if (node.type === AST_NODE_TYPES.Literal && typeof node.value === 'string')
18
+ return 'literal';
19
+ if (node.type === AST_NODE_TYPES.TemplateLiteral && node.expressions.length === 0)
20
+ return 'simple-template';
21
+ return null;
22
+ };
23
+ /**
24
+ * Recursively processes a vanilla-extract style object and reports occurrences of 'px' units.
25
+ *
26
+ * - Skips properties present in the allow list (supports camelCase and kebab-case).
27
+ * - Traverses nested object values and delegates deeper traversal to callers for arrays/at-rules/selectors.
28
+ * - Provides fix suggestions for string literals and simple template literals (no expressions).
29
+ *
30
+ * @param context ESLint rule context used to report diagnostics and apply suggestions.
31
+ * @param node The ObjectExpression node representing the style object to inspect.
32
+ * @param allowSet Set of property names (camelCase or kebab-case) that are allowed to contain 'px'.
33
+ */
34
+ export const processNoPxUnitInStyleObject = (context, node, allowSet) => {
35
+ for (const property of node.properties) {
36
+ if (property.type !== AST_NODE_TYPES.Property)
37
+ continue;
38
+ // Determine property name when possible
39
+ let propertyName = null;
40
+ if (property.key.type === AST_NODE_TYPES.Identifier) {
41
+ propertyName = property.key.name;
42
+ }
43
+ else if (property.key.type === AST_NODE_TYPES.Literal && typeof property.key.value === 'string') {
44
+ propertyName = property.key.value;
45
+ }
46
+ // Recurse into known nested containers
47
+ if (propertyName === '@media' || propertyName === 'selectors') {
48
+ if (property.value.type === AST_NODE_TYPES.ObjectExpression) {
49
+ for (const nested of property.value.properties) {
50
+ if (nested.type === AST_NODE_TYPES.Property && nested.value.type === AST_NODE_TYPES.ObjectExpression) {
51
+ processNoPxUnitInStyleObject(context, nested.value, allowSet);
52
+ }
53
+ }
54
+ }
55
+ continue;
56
+ }
57
+ // Traverse any nested object
58
+ if (property.value.type === AST_NODE_TYPES.ObjectExpression) {
59
+ processNoPxUnitInStyleObject(context, property.value, allowSet);
60
+ continue;
61
+ }
62
+ // Skip if property is whitelisted (supports both camelCase and kebab-case)
63
+ if (propertyName) {
64
+ const kebab = toKebab(propertyName);
65
+ if (allowSet.has(propertyName) || allowSet.has(kebab)) {
66
+ continue;
67
+ }
68
+ }
69
+ // Check string or template literal values
70
+ const text = getValueText(property.value);
71
+ if (text && containsPx(text)) {
72
+ const fixability = canSuggestFix(property.value);
73
+ context.report({
74
+ node: property.value,
75
+ messageId: 'noPxUnit',
76
+ suggest: fixability
77
+ ? [
78
+ {
79
+ messageId: 'removePx',
80
+ fix: (fixer) => {
81
+ const newText = replacePxWith(text, '');
82
+ if (fixability === 'literal') {
83
+ return fixer.replaceText(property.value, `'${newText}'`);
84
+ }
85
+ // simple template with no expressions
86
+ return fixer.replaceText(property.value, `\`${newText}\``);
87
+ },
88
+ },
89
+ {
90
+ messageId: 'replaceWithRem',
91
+ fix: (fixer) => {
92
+ const newText = replacePxWith(text, 'rem');
93
+ if (fixability === 'literal') {
94
+ return fixer.replaceText(property.value, `'${newText}'`);
95
+ }
96
+ return fixer.replaceText(property.value, `\`${newText}\``);
97
+ },
98
+ },
99
+ ]
100
+ : undefined,
101
+ });
102
+ }
103
+ }
104
+ };
@@ -0,0 +1,11 @@
1
+ import type { Rule } from 'eslint';
2
+ /**
3
+ * Creates ESLint rule visitors for detecting and reporting 'px' units in vanilla-extract style objects.
4
+ * - Tracks calls to vanilla-extract APIs (style, recipe, keyframes, globalStyle, fontFace, etc.).
5
+ * This visitor only orchestrates traversal; the actual reporting and suggestion logic lives in the processor.
6
+ * - Respects the `allow` option (camelCase or kebab-case) by passing it as a Set to the processor.
7
+ *
8
+ * @param context ESLint rule context used to read options and report diagnostics.
9
+ * @returns Rule listener that inspects vanilla-extract call expressions and processes style objects.
10
+ */
11
+ export declare const createNoPxUnitVisitors: (context: Rule.RuleContext) => Rule.RuleListener;