stylelint-plugin-rhythmguard 3.19.0 → 3.20.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 (55) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +3 -3
  3. package/SECURITY.md +2 -1
  4. package/agents/claude-code/SKILL.md +1 -1
  5. package/package.json +1 -1
  6. package/src/audit/args.js +30 -8
  7. package/src/audit/baseline.js +38 -4
  8. package/src/audit/codemod.js +4 -2
  9. package/src/audit/config.js +7 -0
  10. package/src/audit/contract.js +124 -14
  11. package/src/audit/next-steps.js +3 -1
  12. package/src/audit/non-authored.js +1 -0
  13. package/src/audit/render-github.js +16 -11
  14. package/src/audit/render-markdown.js +8 -2
  15. package/src/audit/render-text.js +41 -2
  16. package/src/audit/render-utils.js +14 -0
  17. package/src/audit/report.js +230 -10
  18. package/src/audit/scan/files.js +14 -5
  19. package/src/audit/scan/stylesheets.js +48 -53
  20. package/src/audit/scan/templates.js +2 -0
  21. package/src/audit/shared.js +7 -1
  22. package/src/audit/token-chains.js +1 -0
  23. package/src/cli/audit.js +2 -2
  24. package/src/cli/doctor.js +853 -237
  25. package/src/cli/first-run.js +210 -0
  26. package/src/cli/index.js +25 -1
  27. package/src/cli/index.mjs +3 -0
  28. package/src/cli/init.js +42 -13
  29. package/src/cli/quickstart.js +53 -102
  30. package/src/cli/scale.js +223 -0
  31. package/src/configs/recommended.js +3 -1
  32. package/src/configs/strict.js +3 -1
  33. package/src/configs/tailwind.js +15 -0
  34. package/src/core/decisions.js +18 -5
  35. package/src/core/fs-cache.js +1 -0
  36. package/src/core/options.js +2 -1
  37. package/src/core/scale-inference.js +72 -52
  38. package/src/core/tailwind-class-analysis.js +56 -13
  39. package/src/core/token-index.js +55 -14
  40. package/src/core/token-map.js +138 -29
  41. package/src/core/token-sources.js +461 -40
  42. package/src/core/value-nodes.js +4 -2
  43. package/src/eslint/class-context.js +330 -0
  44. package/src/eslint/literal-spans.js +5 -4
  45. package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
  46. package/src/presets/default-scale.js +42 -0
  47. package/src/presets/scales.js +6 -1
  48. package/src/rules/no-offscale-transform/index.js +17 -5
  49. package/src/rules/prefer-token/index.js +51 -15
  50. package/src/rules/use-scale/index.js +7 -4
  51. package/types/__checks__/consumer.ts +17 -0
  52. package/types/__checks__/eslint-config.ts +5 -0
  53. package/types/audit.d.ts +40 -3
  54. package/types/cli.d.ts +77 -1
  55. package/types/shared.d.ts +10 -0
@@ -11,16 +11,20 @@ const {
11
11
  pxOnScale,
12
12
  toPx,
13
13
  } = require('./length');
14
+ const { TAILWIND_SCALE_NAME, TAILWIND_SPACING_UNIT_REM, tailwindSpacingLadder } = require('../presets/default-scale');
14
15
 
15
- // The ESLint rule's and the audit's default scale. It is not the `rhythmic-4`
16
- // preset (which continues to 40, 48, 64); unifying the defaults changes
17
- // reports, so it waits for a major (#246).
18
- const DEFAULT_SCALE = [0, 4, 8, 12, 16, 24, 32];
19
16
  const DEFAULT_UNITS = ['px', 'rem', 'em'];
20
17
  // Tailwind's numeric spacing utilities are multiples of one unit: `--spacing`
21
18
  // (0.25rem) in v4, and the same 0.25rem step in the v3 default scale. In px
22
19
  // that is a quarter of the root font size: 4px at 16px, 2.5px at 10px (#247).
23
- const SPACING_UNIT_REM = 0.25;
20
+ const SPACING_UNIT_REM = TAILWIND_SPACING_UNIT_REM;
21
+
22
+ // Utilities Tailwind has no negative form for: padding, scroll padding and
23
+ // gap (padding and gap cannot be negative in CSS). `-p-3` and `-gap-3` are
24
+ // never generated, and `p-[-13px]` writes an invalid declaration (cs-08).
25
+ // The class regex still accepts the sign on them so a finding that was
26
+ // reported keeps being reported, now without a fix.
27
+ const NO_NEGATIVE_FORM = /^(?:p[trblxy]?|gap(?:-[xy])?|scroll-p[trblxy]?)$/;
24
28
 
25
29
  const ARBITRARY_SPACING_CLASS = /^(?<utility>-?(?:m(?:[trblxy])?|p(?:[trblxy])?|gap(?:-[xy])?|space-[xy]|inset(?:-[xy])?|top|right|bottom|left|translate-[xy]|scroll-(?:m|p)(?:[trblxy])?))-\[(?<rawValue>[^\]]+)\]$/;
26
30
 
@@ -31,16 +35,22 @@ function normalizeTailwindClassOptions(option = {}) {
31
35
  option.baseFontSize > 0
32
36
  ? option.baseFontSize
33
37
  : 16;
38
+ const spacingUnit = option.spacingUnit === false
39
+ ? null
40
+ : typeof option.spacingUnit === 'number' && Number.isFinite(option.spacingUnit) && option.spacingUnit > 0
41
+ ? option.spacingUnit
42
+ : baseFontSize * SPACING_UNIT_REM;
43
+ // No `scale`: Tailwind's default ladder on the spacing unit, so a standard
44
+ // step such as p-5 (20px) is on the scale (cs-01). Before 3.20 the default
45
+ // was 0 to 32px.
46
+ const defaultScale = !Array.isArray(option.scale);
34
47
  return {
35
48
  allowHairlines: option.allowHairlines !== false,
36
49
  allowNegative: option.allowNegative !== false,
37
50
  baseFontSize,
38
- scale: Array.isArray(option.scale) ? option.scale : DEFAULT_SCALE,
39
- spacingUnit: option.spacingUnit === false
40
- ? null
41
- : typeof option.spacingUnit === 'number' && Number.isFinite(option.spacingUnit) && option.spacingUnit > 0
42
- ? option.spacingUnit
43
- : baseFontSize * SPACING_UNIT_REM,
51
+ scale: defaultScale ? tailwindSpacingLadder(spacingUnit || baseFontSize * SPACING_UNIT_REM) : option.scale,
52
+ scaleName: defaultScale ? TAILWIND_SCALE_NAME : null,
53
+ spacingUnit,
44
54
  units: Array.isArray(option.units)
45
55
  ? option.units.map((unit) => String(unit).toLowerCase())
46
56
  : DEFAULT_UNITS,
@@ -154,6 +164,9 @@ function utilityClassFor(utility, px, negative, spacingUnit) {
154
164
  return null;
155
165
  }
156
166
  const name = utility.startsWith('-') ? utility.slice(1) : utility;
167
+ if (negative && steps !== 0 && NO_NEGATIVE_FORM.test(name)) {
168
+ return null;
169
+ }
157
170
  const sign = negative && steps !== 0 ? '-' : '';
158
171
  return `${sign}${name}-${formatNumber(Math.round(quarters) / 4)}`;
159
172
  }
@@ -213,6 +226,26 @@ function analyzeClassToken(token, options, scalePx) {
213
226
  if (!nearest) {
214
227
  return null;
215
228
  }
229
+ // Past the top step the nearest step is not a fix: 64px snapped to a 32px
230
+ // top step halves the padding (cs-01). Reported, with no fix.
231
+ const beyondScale = pxValue > scalePx[scalePx.length - 1];
232
+
233
+ // `-p-[13px]`, `p-[-13px]`, `-gap-[13px]`: still reported, as before, but
234
+ // with no fix and no suggested class, since `-p-3` and `-gap-3` do not
235
+ // exist. A double negative (`-p-[-13px]`) is no better: Tailwind has no
236
+ // `-p-*` utility at all. On-scale values were never reported and are not now.
237
+ const bareUtility = match.groups.utility.replace(/^-/, '');
238
+ if (NO_NEGATIVE_FORM.test(bareUtility) && (match.groups.utility.startsWith('-') || parsedLength.number < 0)) {
239
+ return {
240
+ fixedToken: null,
241
+ nearest,
242
+ nearestUtilities: null,
243
+ parsedLength,
244
+ reason: 'no-negative-form',
245
+ rawValue: match.groups.rawValue,
246
+ utility: match.groups.utility,
247
+ };
248
+ }
216
249
 
217
250
  const signedNearest = parsedLength.number < 0
218
251
  ? -Math.abs(nearest.nearest)
@@ -235,7 +268,7 @@ function analyzeClassToken(token, options, scalePx) {
235
268
  const fixedCandidate = utilityFix || parsedToken.candidate.replace(match.groups.rawValue, replacementValue);
236
269
 
237
270
  return {
238
- fixedToken: wrap(fixedCandidate),
271
+ fixedToken: beyondScale ? null : wrap(fixedCandidate),
239
272
  nearest,
240
273
  // The utility classes for the two nearest steps, when both are quarter
241
274
  // steps of the spacing unit; messages name these instead of px values.
@@ -276,10 +309,20 @@ function createTailwindClassAnalyzer(option = {}) {
276
309
  * The message text for an off-scale class: the two nearest utility classes
277
310
  * with their px values when the unit makes them, the px steps otherwise.
278
311
  */
279
- function offScaleClassMessage(token, analysis) {
312
+ function offScaleClassMessage(token, analysis, scaleName = null) {
313
+ const message = offScaleClassText(token, analysis);
314
+ // The ESLint rule names the scale it fell back to, so a reader knows the
315
+ // verdict is Tailwind's default ladder and not the project's tokens.
316
+ return scaleName && analysis.reason === 'off-scale' ? `${message} Scale: ${scaleName}.` : message;
317
+ }
318
+
319
+ function offScaleClassText(token, analysis) {
280
320
  if (analysis.reason === 'negative') {
281
321
  return `Unexpected Tailwind arbitrary spacing value "${token}". Negative values are disabled for this rule.`;
282
322
  }
323
+ if (analysis.reason === 'no-negative-form') {
324
+ return `Unexpected Tailwind arbitrary spacing value "${token}". Padding and gap cannot be negative, so this class has no effect.`;
325
+ }
283
326
  const lowerPx = analysis.nearest ? formatLength(analysis.nearest.lower, 'px') : 'n/a';
284
327
  const upperPx = analysis.nearest ? formatLength(analysis.nearest.upper, 'px') : 'n/a';
285
328
  if (analysis.nearestUtilities) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { propertyKindOf } = require('./css-vocabulary');
4
4
  const { fixedLengthValue, numbersEqual, toPx } = require('./length');
5
- const { createTokenKindMatcher, parseTokenValueLength } = require('./token-sources');
5
+ const { conditionsOfNode, createTokenKindMatcher, parseTokenValueLength } = require('./token-sources');
6
6
 
7
7
  // Dedicated kinds first: a name like --radius-space-1 is a radius token.
8
8
  const TOKEN_KINDS = ['radius', 'typography', 'motion', 'size', 'spacing'].map((kind) => [kind, createTokenKindMatcher(kind)]);
@@ -70,26 +70,65 @@ function tokenIndexFromDefinitions(definitions, baseFontSize = 16) {
70
70
  for (const { px, raw, unit } of lengths || []) {
71
71
  if (px === 0) continue;
72
72
  const file = definition.files ? [...definition.files][0] : null;
73
- index.push({ file: file && file !== 'stylesheet' ? file : null, px, raw, token: definition.token, unit });
73
+ // A definition built without scopes (an older caller) counts as declared at the root.
74
+ const fixScopes = definition.fixScopes || [{ global: true }];
75
+ index.push({ file: file && file !== 'stylesheet' ? file : null, fixScopes, px, raw, token: definition.token, unit });
74
76
  }
75
77
  }
76
78
  return index;
77
79
  }
78
80
 
81
+ /** The conditions and ancestors of a declaration being fixed, computed once per declaration. */
82
+ const placeCache = new WeakMap();
83
+ function placeOf(decl) {
84
+ if (!placeCache.has(decl)) {
85
+ const ancestors = new Set();
86
+ for (let node = decl.parent; node; node = node.parent) ancestors.add(node);
87
+ placeCache.set(decl, { ancestors, conditions: new Set(conditionsOfNode(decl)) });
88
+ }
89
+ return placeCache.get(decl);
90
+ }
91
+
92
+ /**
93
+ * Whether a token is defined where a declaration sits (fix-02). A token
94
+ * declared at the root outside every conditional at-rule is defined
95
+ * everywhere. One declared at the root under `@media`, `@supports` or
96
+ * `@container` is defined only under the same conditions, and one declared in
97
+ * a component block only inside that block. Anywhere else the property would
98
+ * be invalid at computed-value time, so the token is never offered there.
99
+ * Without a declaration (`at` undefined) every token counts.
100
+ */
101
+ function tokenDefinedAt(entry, at) {
102
+ if (!at || !entry.fixScopes) {
103
+ return true;
104
+ }
105
+ return entry.fixScopes.some((scope) => {
106
+ if (scope.global) return true;
107
+ if (scope.anchor) return placeOf(at).ancestors.has(scope.anchor);
108
+ if (scope.conditions) {
109
+ const { conditions } = placeOf(at);
110
+ return scope.conditions.every((condition) => conditions.has(condition));
111
+ }
112
+ return false;
113
+ });
114
+ }
115
+
79
116
  /**
80
117
  * Every custom property that holds a length, for one property. The shared
81
118
  * resolver behind use-scale's `fixWith: "token"` and prefer-token, so the two
82
119
  * rules always know the same tokens. The px value is signed: 8 finds the
83
120
  * tokens that hold 8px, -8 the tokens that hold -8px. Same unit first; with
84
121
  * `anyUnit`, a token in another unit that holds the same px value counts when
85
- * none matches the unit. Sorted, so messages are stable.
122
+ * none matches the unit. With `at`, the declaration being fixed, only the
123
+ * tokens defined where it sits count (see tokenDefinedAt). Sorted, so
124
+ * messages are stable.
86
125
  */
87
- function tokensForLength(index, px, unit, { anyUnit = false, prop = null } = {}) {
126
+ function tokensForLength(index, px, unit, { anyUnit = false, at = null, prop = null } = {}) {
88
127
  const wanted = unit || 'px';
89
128
  const sameUnit = new Set();
90
129
  const otherUnit = new Set();
91
130
  for (const entry of index) {
92
- if (!entry.token.startsWith('--') || !numbersEqual(entry.px, px) || !tokenFitsProperty(entry.token, prop)) {
131
+ if (!entry.token.startsWith('--') || !numbersEqual(entry.px, px) || !tokenFitsProperty(entry.token, prop) || !tokenDefinedAt(entry, at)) {
93
132
  continue;
94
133
  }
95
134
  (entry.unit === wanted ? sameUnit : otherUnit).add(entry.token);
@@ -114,8 +153,8 @@ function signedTokensForLength(index, px, unit, options = {}) {
114
153
  return { negate: px < 0, tokens: tokensForLength(index, Math.abs(px), unit, options) };
115
154
  }
116
155
 
117
- function tokenForLength(index, px, unit, prop = null) {
118
- const candidates = tokensForLength(index, px, unit, { prop });
156
+ function tokenForLength(index, px, unit, prop = null, at = null) {
157
+ const candidates = tokensForLength(index, px, unit, { at, prop });
119
158
  return candidates.length === 1 ? `var(${candidates[0]})` : null;
120
159
  }
121
160
 
@@ -135,18 +174,19 @@ function negateReplacement(replacement) {
135
174
  * options ask for one and exactly one qualifies, otherwise the literal. The
136
175
  * nearest value is in px, or in the literal's unit with `unitStrategy:
137
176
  * "exact"`; tokens are indexed in px, so the lookup converts it (issue #223).
138
- * `avoidTokens` are the var() names a fallback literal falls back from; one
139
- * of them is never written, the literal is.
177
+ * `avoidTokens` are the var() names a fallback literal falls back from. A
178
+ * fallback is what renders when tokens are missing, so no token is written
179
+ * into one, the literal is (fix-02; issue #240). `at` is the declaration being
180
+ * fixed: a token not defined there is never written (see tokenDefinedAt).
140
181
  */
141
- function replacementFor(parsedLength, nearest, options, prop = null, avoidTokens = []) {
142
- if (options.fixWith === 'token' && options.tokenIndex) {
182
+ function replacementFor(parsedLength, nearest, options, prop = null, avoidTokens = [], at = null) {
183
+ if (options.fixWith === 'token' && options.tokenIndex && avoidTokens.length === 0) {
143
184
  const unit = parsedLength.unit || 'px';
144
185
  const nearestPx = options.unitStrategy === 'exact' ? toPx(Math.abs(nearest), unit, options.baseFontSize) : Math.abs(nearest);
145
186
  if (nearestPx !== null) {
146
187
  const signedPx = parsedLength.number < 0 ? -nearestPx : nearestPx;
147
- const { negate, tokens } = signedTokensForLength(options.tokenIndex, signedPx, unit, { prop });
148
- // A var() fallback never falls back to the token it is the fallback of (issue #240).
149
- if (tokens.length === 1 && !avoidTokens.includes(tokens[0])) {
188
+ const { negate, tokens } = signedTokensForLength(options.tokenIndex, signedPx, unit, { at, prop });
189
+ if (tokens.length === 1) {
150
190
  const token = `var(${tokens[0]})`;
151
191
  return negate ? negateReplacement(token) : token;
152
192
  }
@@ -173,6 +213,7 @@ module.exports = {
173
213
  negateReplacement,
174
214
  replacementFor,
175
215
  signedTokensForLength,
216
+ tokenDefinedAt,
176
217
  tokenFitsProperty,
177
218
  tokenHoldsNote,
178
219
  tokenForLength,
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { readJsonFile } = require('./json');
4
- const { parseTokenValueLength } = require('./token-sources');
4
+ const { conditionsOfNode, parseTokenValueLength, scopeOfNode } = require('./token-sources');
5
5
 
6
6
  const fs = require('node:fs');
7
7
  const path = require('node:path');
@@ -48,11 +48,32 @@ function displayOrigin(file) {
48
48
  if (!file) {
49
49
  return null;
50
50
  }
51
+ // Named with / on every platform, as the audit names files (#174).
51
52
  const relative = path.relative(process.cwd(), file);
52
- return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : file;
53
+ return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative.split(path.sep).join('/') : file;
53
54
  }
54
55
 
55
- function addLengthValueMapping(map, rawLength, tokenReference, baseFontSize, origins = null, origin = null) {
56
+ /**
57
+ * The tokens one map source offers for each key, before they reach the map.
58
+ * A key collects the tokens whose value is written that way (`exact`) apart
59
+ * from the tokens that only convert to it (`converted`: a 1rem token under the
60
+ * 16px key), so a token in the literal's own unit is preferred, as the token
61
+ * index does.
62
+ */
63
+ function createCollector() {
64
+ return new Map();
65
+ }
66
+
67
+ function collect(collector, key, token, exact) {
68
+ if (!collector.has(key)) {
69
+ collector.set(key, { converted: new Set(), exact: new Set(), last: token });
70
+ }
71
+ const entry = collector.get(key);
72
+ (exact ? entry.exact : entry.converted).add(token);
73
+ entry.last = token;
74
+ }
75
+
76
+ function addLengthValueMapping(collector, rawLength, tokenReference, baseFontSize, origins = null, origin = null) {
56
77
  if (typeof rawLength !== 'string') {
57
78
  return;
58
79
  }
@@ -74,15 +95,49 @@ function addLengthValueMapping(map, rawLength, tokenReference, baseFontSize, ori
74
95
  // Keyed by the signed value: a -8px token stands for -8px, never for 8px
75
96
  // (issue #221). prefer-token negates a positive token for a negative literal.
76
97
  const normalizedRaw = formatLength(parsed.number, parsed.unit || 'px');
77
- map[normalizedRaw] = token;
98
+ collect(collector, normalizedRaw, token, true);
78
99
 
79
100
  const px = toPx(parsed.number, parsed.unit, baseFontSize);
80
101
  if (px !== null) {
81
- map[`${px}px`] = token;
102
+ const pxKey = `${px}px`;
103
+ collect(collector, pxKey, token, pxKey === normalizedRaw);
82
104
  }
83
105
  }
84
106
 
85
- function mergeExplicitTokenMap(target, source) {
107
+ /**
108
+ * The tokens a collected key stands for: the ones written in its unit when
109
+ * there are any, the converted ones otherwise. Sorted, so messages are stable.
110
+ */
111
+ function candidatesOf(entry) {
112
+ const chosen = entry.exact.size > 0 ? entry.exact : entry.converted;
113
+ return [...chosen].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
114
+ }
115
+
116
+ /**
117
+ * Write one source's keys into the map. A key one token holds maps to that
118
+ * token. A key several tokens hold is a guess either way, so it is recorded
119
+ * in `ambiguous` with every candidate and no fix writes it (fix-06); the map
120
+ * keeps a token under the key only so the set of keys (which scale inference
121
+ * reads) is unchanged. A later source replaces an earlier one key by key.
122
+ * `accept` may skip a key entirely, leaving earlier sources in charge of it.
123
+ */
124
+ function applyCollector(map, ambiguous, collector, accept = () => true) {
125
+ for (const [key, entry] of collector) {
126
+ const candidates = candidatesOf(entry);
127
+ if (!accept(candidates)) {
128
+ continue;
129
+ }
130
+ if (candidates.length === 1) {
131
+ map[key] = candidates[0];
132
+ delete ambiguous[key];
133
+ } else {
134
+ map[key] = entry.last;
135
+ ambiguous[key] = candidates;
136
+ }
137
+ }
138
+ }
139
+
140
+ function mergeExplicitTokenMap(target, source, ambiguous = {}) {
86
141
  if (!isPlainObject(source)) {
87
142
  return target;
88
143
  }
@@ -93,12 +148,13 @@ function mergeExplicitTokenMap(target, source) {
93
148
  }
94
149
 
95
150
  target[raw] = tokenReference;
151
+ delete ambiguous[raw];
96
152
  }
97
153
 
98
154
  return target;
99
155
  }
100
156
 
101
- function walkTokenGroup(map, group, prefix, baseFontSize, origins, origin) {
157
+ function walkTokenGroup(collector, group, prefix, baseFontSize, origins, origin) {
102
158
  for (const [key, value] of Object.entries(group)) {
103
159
  const tokenName = `${prefix}-${key}`;
104
160
 
@@ -108,26 +164,28 @@ function walkTokenGroup(map, group, prefix, baseFontSize, origins, origin) {
108
164
 
109
165
  // Leaf node with $value (DTCG)
110
166
  if (typeof value.$value === 'string') {
111
- addLengthValueMapping(map, value.$value, tokenName, baseFontSize, origins, origin);
167
+ addLengthValueMapping(collector, value.$value, tokenName, baseFontSize, origins, origin);
112
168
  continue;
113
169
  }
114
170
 
115
171
  // Leaf node with value (Style Dictionary)
116
172
  if (typeof value.value === 'string') {
117
- addLengthValueMapping(map, value.value, tokenName, baseFontSize, origins, origin);
173
+ addLengthValueMapping(collector, value.value, tokenName, baseFontSize, origins, origin);
118
174
  continue;
119
175
  }
120
176
 
121
177
  // Nested group: recurse deeper
122
- walkTokenGroup(map, value, tokenName, baseFontSize, origins, origin);
178
+ walkTokenGroup(collector, value, tokenName, baseFontSize, origins, origin);
123
179
  }
124
180
  }
125
181
 
126
182
  function mergeTokenMapFromFile({
183
+ ambiguous = {},
127
184
  baseFontSize,
128
185
  currentMap,
129
186
  origins = null,
130
187
  tokenMapFile,
188
+ warnings = [],
131
189
  }) {
132
190
  if (!tokenMapFile) {
133
191
  return currentMap;
@@ -135,13 +193,15 @@ function mergeTokenMapFromFile({
135
193
 
136
194
  const resolvedPath = path.resolve(process.cwd(), tokenMapFile);
137
195
  if (!fs.existsSync(resolvedPath)) {
196
+ warnings.push(`Token map file not found: ${tokenMapFile}`);
138
197
  return currentMap;
139
198
  }
140
199
 
141
200
  let parsed;
142
201
  try {
143
202
  parsed = readJsonFile(resolvedPath);
144
- } catch {
203
+ } catch (error) {
204
+ warnings.push(`Unable to parse token map file ${tokenMapFile}: ${error.message}`);
145
205
  return currentMap;
146
206
  }
147
207
 
@@ -152,6 +212,7 @@ function mergeTokenMapFromFile({
152
212
  const nextMap = {
153
213
  ...currentMap,
154
214
  };
215
+ const collector = createCollector();
155
216
  const origin = displayOrigin(resolvedPath);
156
217
 
157
218
  for (const [entryKey, entryValue] of Object.entries(parsed)) {
@@ -160,7 +221,7 @@ function mergeTokenMapFromFile({
160
221
  const valueAsLength = parseLengthToken(entryValue);
161
222
 
162
223
  if (keyAsLength) {
163
- nextMap[entryKey] = entryValue;
224
+ collect(collector, entryKey, entryValue, true);
164
225
  if (origins && !origins[entryValue]) {
165
226
  origins[entryValue] = origin;
166
227
  }
@@ -168,38 +229,48 @@ function mergeTokenMapFromFile({
168
229
  }
169
230
 
170
231
  if (valueAsLength) {
171
- addLengthValueMapping(nextMap, entryValue, entryKey, baseFontSize, origins, origin);
232
+ addLengthValueMapping(collector, entryValue, entryKey, baseFontSize, origins, origin);
172
233
  }
173
234
 
174
235
  continue;
175
236
  }
176
237
 
177
238
  if (typeof entryValue === 'number') {
178
- addLengthValueMapping(nextMap, `${entryValue}px`, entryKey, baseFontSize, origins, origin);
239
+ addLengthValueMapping(collector, `${entryValue}px`, entryKey, baseFontSize, origins, origin);
179
240
  continue;
180
241
  }
181
242
 
182
243
  if (isPlainObject(entryValue)) {
183
244
  // Style Dictionary format: { value: "16px" }
184
245
  if (typeof entryValue.value === 'string') {
185
- addLengthValueMapping(nextMap, entryValue.value, entryKey, baseFontSize, origins, origin);
246
+ addLengthValueMapping(collector, entryValue.value, entryKey, baseFontSize, origins, origin);
186
247
  continue;
187
248
  }
188
249
 
189
250
  // W3C DTCG format: { $value: "16px", $type: "dimension" }
190
251
  if (typeof entryValue.$value === 'string') {
191
- addLengthValueMapping(nextMap, entryValue.$value, entryKey, baseFontSize, origins, origin);
252
+ addLengthValueMapping(collector, entryValue.$value, entryKey, baseFontSize, origins, origin);
192
253
  continue;
193
254
  }
194
255
 
195
256
  // Nested group: recurse (e.g. { spacing: { 4: { $value: "16px" } } })
196
- walkTokenGroup(nextMap, entryValue, entryKey, baseFontSize, origins, origin);
257
+ walkTokenGroup(collector, entryValue, entryKey, baseFontSize, origins, origin);
197
258
  }
198
259
  }
199
260
 
261
+ applyCollector(nextMap, ambiguous, collector);
200
262
  return nextMap;
201
263
  }
202
264
 
265
+ /**
266
+ * Whether a custom property declaration is defined everywhere: at the root
267
+ * (`:root`, `html`, `@theme`) and outside every `@media`, `@supports` and
268
+ * `@container` block.
269
+ */
270
+ function declaredEverywhere(decl) {
271
+ return scopeOfNode(decl) === 'root' && conditionsOfNode(decl).length === 0;
272
+ }
273
+
203
274
  function mergeTokenMapFromCssCustomProperties({
204
275
  baseFontSize,
205
276
  currentMap,
@@ -225,24 +296,39 @@ function mergeTokenMapFromCssCustomProperties({
225
296
  const px = parsed ? toPx(parsed.number, parsed.unit, baseFontSize) : null;
226
297
  const key = px === null ? `raw:${decl.value.trim()}` : `px:${formatLength(px, 'px')}`;
227
298
  if (!valuesByProp.has(decl.prop)) {
228
- valuesByProp.set(decl.prop, { decl, keys: new Set() });
299
+ valuesByProp.set(decl.prop, { decl, everywhere: false, keys: new Set() });
229
300
  }
230
- valuesByProp.get(decl.prop).keys.add(key);
301
+ const entry = valuesByProp.get(decl.prop);
302
+ entry.keys.add(key);
303
+ entry.everywhere = entry.everywhere || declaredEverywhere(decl);
231
304
  });
232
305
 
233
- for (const { decl, keys } of valuesByProp.values()) {
234
- if (keys.size > 1) {
306
+ const collector = createCollector();
307
+ const everywhere = new Set();
308
+ for (const entry of valuesByProp.values()) {
309
+ if (entry.keys.size > 1) {
235
310
  continue;
236
311
  }
237
312
 
238
- const parsed = parseTokenValueLength(decl.value);
313
+ const parsed = parseTokenValueLength(entry.decl.value);
239
314
  if (!parsed || parsed.number === 0) {
240
315
  continue;
241
316
  }
242
317
 
243
- addLengthValueMapping(nextMap, decl.value, `var(${decl.prop})`, baseFontSize, origins, origin);
318
+ const token = `var(${entry.decl.prop})`;
319
+ if (entry.everywhere) {
320
+ everywhere.add(token);
321
+ }
322
+ addLengthValueMapping(collector, entry.decl.value, token, baseFontSize, origins, origin);
244
323
  }
245
324
 
325
+ // A value two tokens hold, or one held by a token that is not defined
326
+ // everywhere (a `.card` token, a token under `@media`), is left out of the
327
+ // map. prefer-token's token index then names every candidate defined where
328
+ // the value sits and writes one only when it is the only one (css-08,
329
+ // fix-02).
330
+ applyCollector(nextMap, {}, collector, (candidates) => candidates.length === 1 && everywhere.has(candidates[0]));
331
+
246
332
  return nextMap;
247
333
  }
248
334
 
@@ -274,6 +360,9 @@ function extractTailwindSpacing(config) {
274
360
  };
275
361
  }
276
362
 
363
+ // Why a Tailwind config could not be loaded, by resolved path (cq-05).
364
+ const tailwindLoadErrors = new Map();
365
+
277
366
  function loadTailwindSpacingFromRequire(resolvedPath) {
278
367
  try {
279
368
  const loaded = require(resolvedPath);
@@ -282,7 +371,8 @@ function loadTailwindSpacingFromRequire(resolvedPath) {
282
371
  : loaded;
283
372
 
284
373
  return extractTailwindSpacing(config);
285
- } catch {
374
+ } catch (error) {
375
+ tailwindLoadErrors.set(resolvedPath, error && error.message ? error.message.split('\n')[0] : String(error));
286
376
  return null;
287
377
  }
288
378
  }
@@ -302,9 +392,11 @@ function loadTailwindSpacing(resolvedPath) {
302
392
  }
303
393
 
304
394
  function mergeTokenMapFromTailwindSpacing({
395
+ ambiguous = {},
305
396
  currentMap,
306
397
  origins = null,
307
398
  tailwindConfigPath,
399
+ warnings = [],
308
400
  }) {
309
401
  if (!tailwindConfigPath) {
310
402
  return currentMap;
@@ -312,10 +404,16 @@ function mergeTokenMapFromTailwindSpacing({
312
404
 
313
405
  const resolvedPath = path.resolve(process.cwd(), tailwindConfigPath);
314
406
  if (!fs.existsSync(resolvedPath)) {
407
+ warnings.push(`Tailwind config not found: ${tailwindConfigPath}`);
315
408
  return currentMap;
316
409
  }
317
410
 
318
411
  const spacing = loadTailwindSpacing(resolvedPath);
412
+ if (tailwindLoadErrors.has(resolvedPath)) {
413
+ // A config that throws used to read as "no known token" (cq-05).
414
+ warnings.push(`Tailwind config ${tailwindConfigPath} could not be loaded: ${tailwindLoadErrors.get(resolvedPath)}`);
415
+ return currentMap;
416
+ }
319
417
  if (!isPlainObject(spacing) || Object.keys(spacing).length === 0) {
320
418
  return currentMap;
321
419
  }
@@ -323,6 +421,7 @@ function mergeTokenMapFromTailwindSpacing({
323
421
  const nextMap = {
324
422
  ...currentMap,
325
423
  };
424
+ const collector = createCollector();
326
425
 
327
426
  for (const [key, value] of Object.entries(spacing)) {
328
427
  if (typeof value !== 'string') {
@@ -335,12 +434,14 @@ function mergeTokenMapFromTailwindSpacing({
335
434
  }
336
435
 
337
436
  const normalizedRaw = formatLength(parsed.number, parsed.unit || 'px');
338
- nextMap[normalizedRaw] = `theme(spacing.${key})`;
339
- if (origins && !origins[nextMap[normalizedRaw]]) {
340
- origins[nextMap[normalizedRaw]] = displayOrigin(resolvedPath);
437
+ const token = `theme(spacing.${key})`;
438
+ collect(collector, normalizedRaw, token, true);
439
+ if (origins && !origins[token]) {
440
+ origins[token] = displayOrigin(resolvedPath);
341
441
  }
342
442
  }
343
443
 
444
+ applyCollector(nextMap, ambiguous, collector);
344
445
  return nextMap;
345
446
  }
346
447
 
@@ -348,18 +449,24 @@ function mergeTokenMapFromTailwindSpacing({
348
449
  * The raw-length to token-reference map a rule fixes with. Pass `origins` to
349
450
  * also learn where each token reference came from (the token map file, the
350
451
  * stylesheet, the Tailwind config), keyed by the reference; an explicit
351
- * `tokenMap` entry has no origin.
452
+ * `tokenMap` entry has no origin. Pass `ambiguous` to learn the keys several
453
+ * tokens of one source hold, each with its candidates: those keys are never a
454
+ * fix (fix-06).
352
455
  */
353
456
  function buildEffectiveTokenMap({
457
+ ambiguous = {},
354
458
  options,
355
459
  origins = null,
356
460
  root,
357
461
  tokenRegex,
462
+ warnings = [],
358
463
  }) {
359
464
  let tokenMap = {};
360
465
 
361
466
  if (options.tokenMapFile) {
362
467
  tokenMap = mergeTokenMapFromFile({
468
+ ambiguous,
469
+ warnings,
363
470
  baseFontSize: options.baseFontSize,
364
471
  currentMap: tokenMap,
365
472
  origins,
@@ -379,6 +486,8 @@ function buildEffectiveTokenMap({
379
486
 
380
487
  if (options.tokenMapFromTailwindSpacing && options.tailwindConfigPath) {
381
488
  tokenMap = mergeTokenMapFromTailwindSpacing({
489
+ ambiguous,
490
+ warnings,
382
491
  currentMap: tokenMap,
383
492
  origins,
384
493
  tailwindConfigPath: options.tailwindConfigPath,
@@ -386,7 +495,7 @@ function buildEffectiveTokenMap({
386
495
  }
387
496
 
388
497
  // Explicit tokenMap applied last so it takes precedence over auto-derived tokens
389
- tokenMap = mergeExplicitTokenMap(tokenMap, options.tokenMap);
498
+ tokenMap = mergeExplicitTokenMap(tokenMap, options.tokenMap, ambiguous);
390
499
 
391
500
  return tokenMap;
392
501
  }