oxlint-tailwindcss 1.5.0 → 1.6.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 (3) hide show
  1. package/dist/index.cjs +353 -58
  2. package/dist/index.mjs +353 -58
  3. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -959,6 +959,7 @@ function roundRemValue(className) {
959
959
  //#endregion
960
960
  //#region src/design-system/cache.ts
961
961
  const EMPTY_DECLARATIONS = [];
962
+ const EMPTY_TOKEN_VALUES = [];
962
963
  var DesignSystemCache = class DesignSystemCache {
963
964
  canonicalMap = /* @__PURE__ */ new Map();
964
965
  deprecatedMap = /* @__PURE__ */ new Map();
@@ -970,6 +971,7 @@ var DesignSystemCache = class DesignSystemCache {
970
971
  propsMemo = /* @__PURE__ */ new Map();
971
972
  partialSet = /* @__PURE__ */ new Set();
972
973
  valueIdByText = null;
974
+ nextValueId = 0;
973
975
  variantOrderMap = /* @__PURE__ */ new Map();
974
976
  variantFactsMap = /* @__PURE__ */ new Map();
975
977
  arbitraryEquivMap = /* @__PURE__ */ new Map();
@@ -980,6 +982,8 @@ var DesignSystemCache = class DesignSystemCache {
980
982
  componentSet = /* @__PURE__ */ new Set();
981
983
  themeRefs = /* @__PURE__ */ new Map();
982
984
  definedVarSet = /* @__PURE__ */ new Set();
985
+ tokenValuesMap = /* @__PURE__ */ new Map();
986
+ scaleFacts = null;
983
987
  static fromPrecomputed(data) {
984
988
  const cache = new DesignSystemCache();
985
989
  cache._validClasses = data.validClasses;
@@ -1007,6 +1011,12 @@ var DesignSystemCache = class DesignSystemCache {
1007
1011
  }
1008
1012
  for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
1009
1013
  if (data.themeRefs) for (const [name, refs] of Object.entries(data.themeRefs)) cache.themeRefs.set(name, refs);
1014
+ for (const [prefix, entries] of Object.entries(data.tokenValues ?? {})) cache.tokenValuesMap.set(prefix, entries);
1015
+ if (data.scale) cache.scaleFacts = {
1016
+ unit: data.scale.unit,
1017
+ step: data.scale.step,
1018
+ prefixes: new Set(data.scale.prefixes)
1019
+ };
1010
1020
  cache._prefix = data.prefix ?? "";
1011
1021
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
1012
1022
  return cache;
@@ -1133,6 +1143,27 @@ var DesignSystemCache = class DesignSystemCache {
1133
1143
  variantNames() {
1134
1144
  return [...this.variantOrderMap.keys()];
1135
1145
  }
1146
+ /**
1147
+ * The numeric theme tokens this utility prefix can be written with, as
1148
+ * `[literal value, class]`. Empty when the prefix has none.
1149
+ */
1150
+ tokenValuesFor(prefix) {
1151
+ return this.tokenValuesMap.get(this.stripProjectPrefix(prefix)) ?? EMPTY_TOKEN_VALUES;
1152
+ }
1153
+ /**
1154
+ * The spacing scale as the design system describes it: the resolved value of
1155
+ * `--spacing`, the granularity Tailwind's own enumerated steps use, and whether
1156
+ * a given prefix reads it. `null` when the theme has no `--spacing`.
1157
+ */
1158
+ get scale() {
1159
+ return this.scaleFacts ? {
1160
+ unit: this.scaleFacts.unit,
1161
+ step: this.scaleFacts.step
1162
+ } : null;
1163
+ }
1164
+ readsScale(prefix) {
1165
+ return this.scaleFacts?.prefixes.has(this.stripProjectPrefix(prefix)) ?? false;
1166
+ }
1136
1167
  isValid(className) {
1137
1168
  if (this.validitySet.has(className)) return true;
1138
1169
  const utility = extractUtility(className);
@@ -1277,7 +1308,10 @@ var DesignSystemCache = class DesignSystemCache {
1277
1308
  internDeclarations(className, raws, valueFacts) {
1278
1309
  const index = this.declIndex;
1279
1310
  if (!index) return EMPTY_DECLARATIONS;
1280
- if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1311
+ if (!this.valueIdByText) {
1312
+ this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1313
+ this.nextValueId = index.values.length;
1314
+ }
1281
1315
  const decls = [];
1282
1316
  let hasElement = false;
1283
1317
  let hasDescendant = false;
@@ -1285,8 +1319,7 @@ var DesignSystemCache = class DesignSystemCache {
1285
1319
  for (const [scopeToken, prop, value] of raws) {
1286
1320
  let valueId = this.valueIdByText.get(value);
1287
1321
  if (valueId === void 0) {
1288
- valueId = index.values.length;
1289
- index.values.push(value);
1322
+ valueId = this.nextValueId++;
1290
1323
  this.valueIdByText.set(value, valueId);
1291
1324
  }
1292
1325
  const facts = valueFacts[value];
@@ -1807,7 +1840,12 @@ function resolveImport(specifier, baseDir) {
1807
1840
  return null;
1808
1841
  }
1809
1842
 
1810
- function extractComponentClasses(cssPath, baseDir) {
1843
+ // The entry CSS plus every \`@import\` that resolves, one level deep. Shared by
1844
+ // the component-class scan and the \`definedVars\` scan: a custom property declared
1845
+ // in an imported file is as real to the browser as one in the entry, and treating
1846
+ // it as undefined makes prefer-theme-tokens propose a token that can change the
1847
+ // design (the #78 hazard, in miniature).
1848
+ function collectCssSources(cssPath, baseDir) {
1811
1849
  let css;
1812
1850
  try { css = readFileSync(cssPath, 'utf-8'); } catch { return []; }
1813
1851
  const files = [css];
@@ -1819,6 +1857,11 @@ function extractComponentClasses(cssPath, baseDir) {
1819
1857
  try { files.push(readFileSync(resolved, 'utf-8')); } catch {}
1820
1858
  }
1821
1859
  }
1860
+ return files;
1861
+ }
1862
+
1863
+ function extractComponentClasses(cssPath, baseDir) {
1864
+ const files = collectCssSources(cssPath, baseDir);
1822
1865
  const result = [];
1823
1866
  for (const content of files) {
1824
1867
  // Scan both @layer components AND @layer utilities
@@ -2305,20 +2348,21 @@ async function main() {
2305
2348
  }
2306
2349
  }
2307
2350
 
2308
- // Theme variables that dereference to another custom property. Only the
2309
- // referencing ones are stored (~a handful), and the reference list reuses the
2310
- // same balanced scanner the declaration values go through.
2311
- // Custom properties the project defines. The entry file covers the standard
2312
- // ':root { --x: ... }' pattern; definitions inside @imported files are not
2313
- // scanned, so an unseen definition reads as "undefined" — which only ever makes
2314
- // prefer-theme-tokens more willing to suggest, never less accurate about a
2315
- // definition it can see.
2316
- const definedVars = [...new Set(css.match(/--[\\w-]+(?=\\s*:)/g) || [])];
2351
+ // Custom properties the project defines, across the entry AND its resolved
2352
+ // @imports — splitting the theme across files is the normal shadcn/ui layout,
2353
+ // and a definition we cannot see reads as "undefined", which is what makes
2354
+ // prefer-theme-tokens propose a token that means something else. One level
2355
+ // deep, same as the component-class scan it shares \`collectCssSources\` with.
2356
+ const definedVars = [...new Set(
2357
+ collectCssSources(cssPath, base).flatMap(src => src.match(/--[\\w-]+(?=\\s*:)/g) || [])
2358
+ )];
2317
2359
 
2318
2360
  const themeRefs = {};
2361
+ const themeValues = new Map();
2319
2362
  if (ds.theme && typeof ds.theme.entries === 'function') {
2320
2363
  for (const [name, entry] of ds.theme.entries()) {
2321
2364
  const value = entry && typeof entry.value === 'string' ? entry.value : '';
2365
+ themeValues.set(name, value);
2322
2366
  if (!value.includes('var(')) continue;
2323
2367
  const reads = scanVarReads(value);
2324
2368
  const all = [...new Set([...reads[0], ...reads[1]])];
@@ -2326,7 +2370,77 @@ async function main() {
2326
2370
  }
2327
2371
  }
2328
2372
 
2329
- const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
2373
+ // ── What a literal value could have been written as (for prefer-scale-token) ──
2374
+ //
2375
+ // Two families, both derived. Neither is a name table: the emitted CSS says
2376
+ // which variable a class reads and the theme says what that variable is worth.
2377
+
2378
+ // A single declaration whose whole value is one \`var(--x)\` that the theme
2379
+ // resolves to a NUMBER. Numeric because that is the only thing the rule can
2380
+ // compare — a colour token could never match a literal the user typed — and
2381
+ // SINGLE because a class that declares more than the original is not an
2382
+ // equivalent: \`text-sm\` sets \`line-height\` too, so \`text-[14px]\` is not it.
2383
+ const NUMERIC_LITERAL = /^-?\\d*\\.?\\d+(rem|px|em|%|s|ms|deg)?$/;
2384
+ const tokenValues = {};
2385
+ for (const cls of validClasses) {
2386
+ if (cls.includes('[') || cls.includes('/')) continue;
2387
+ const css = declCss[cls];
2388
+ if (!css) continue;
2389
+ const open = css.indexOf('{');
2390
+ const close = css.indexOf('}');
2391
+ if (open < 0 || close < 0) continue;
2392
+ const body = css.slice(open + 1, close).replace(/\\s+/g, ' ').replace(/;\\s*$/, '').trim();
2393
+ const m = /^([a-z-]+):\\s*var\\((--[\\w-]+)\\)$/.exec(body);
2394
+ if (!m) continue;
2395
+ const value = themeValues.get(m[2]);
2396
+ if (!value || !NUMERIC_LITERAL.test(value)) continue;
2397
+ const dash = cls.lastIndexOf('-');
2398
+ if (dash <= 0) continue;
2399
+ const prefix = unpfx(cls).slice(0, unpfx(cls).lastIndexOf('-'));
2400
+ if (!prefix) continue;
2401
+ if (!tokenValues[prefix]) tokenValues[prefix] = [];
2402
+ tokenValues[prefix].push([value, unpfx(cls)]);
2403
+ }
2404
+
2405
+ // The spacing scale: its unit, which prefixes read it, and the granularity
2406
+ // Tailwind's own enumerated steps use. Every step getClassList() lists is a
2407
+ // multiple of that granularity, so deriving it is how the rule stays inside
2408
+ // what Tailwind does instead of inventing a threshold.
2409
+ const scaleUnit = themeValues.get('--spacing') || '';
2410
+ const scalePrefixes = [];
2411
+ if (scaleUnit) {
2412
+ const probes = [...knownPrefixes];
2413
+ const probeResults = ds.candidatesToCss(probes.map(p => pfx(p + '-1')));
2414
+ for (let i = 0; i < probes.length; i++) {
2415
+ const css = probeResults[i];
2416
+ if (!css) continue;
2417
+ // \`size-1\` emits width AND height, both reading the unit — one match is enough.
2418
+ if (css.includes('var(--spacing)')) scalePrefixes.push(probes[i]);
2419
+ }
2420
+ }
2421
+ let scaleStep = 0;
2422
+ if (scalePrefixes.length > 0) {
2423
+ const steps = new Set();
2424
+ const scaleSet = new Set(scalePrefixes);
2425
+ for (const cls of validClasses) {
2426
+ const dash = cls.lastIndexOf('-');
2427
+ if (dash <= 0) continue;
2428
+ if (!scaleSet.has(cls.slice(0, dash))) continue;
2429
+ const suffix = cls.slice(dash + 1);
2430
+ if (!/^\\d*\\.?\\d+$/.test(suffix)) continue;
2431
+ steps.add(parseFloat(suffix));
2432
+ }
2433
+ const sorted = [...steps].sort((a, b) => a - b);
2434
+ for (let i = 1; i < sorted.length; i++) {
2435
+ const gap = Math.round((sorted[i] - sorted[i - 1]) * 1000) / 1000;
2436
+ if (gap > 0 && (scaleStep === 0 || gap < scaleStep)) scaleStep = gap;
2437
+ }
2438
+ }
2439
+ const scale = scaleUnit && scalePrefixes.length > 0
2440
+ ? { unit: scaleUnit, step: scaleStep || 1, prefixes: scalePrefixes.sort() }
2441
+ : undefined;
2442
+
2443
+ const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, tokenValues, scale, prefix });
2330
2444
  // Atomic write: write to a unique temp path then rename, so a peer isolate
2331
2445
  // busy-waiting on the cache file never observes a half-written JSON.
2332
2446
  writeFileSync(WD_TMP_PATH, json);
@@ -3329,45 +3443,49 @@ function answersFor(cache) {
3329
3443
  * Ask the design system about every class there is no answer for yet, intern the
3330
3444
  * declarations it returns, and record which classes produce no CSS at all.
3331
3445
  *
3332
- * Returns false when the service is unavailable. Callers treat that as "no
3333
- * information" rather than as an answer, so a broken worker degrades to the
3334
- * behaviour that predates it instead of to wrong diagnostics. Real failures still
3335
- * surface through the sticky error the worker records.
3446
+ * **Throws `SortServiceError` when the service is unavailable**, like the sort and
3447
+ * canonicalize services do. It used to swallow the failure and report "no
3448
+ * information", which was defensible when `no-conflicting-classes` was the only
3449
+ * caller — no declarations means no comparison, so the rule just went quiet. It
3450
+ * stopped being defensible once `no-unknown-classes` started asking about
3451
+ * VALIDITY: there, silence sends the rule back to the tolerant heuristic, so a
3452
+ * dead worker quietly reinstates the very false negatives the service exists to
3453
+ * remove, with nothing anywhere to say so.
3454
+ *
3455
+ * The caller decides what to do, and the two postures already exist in the
3456
+ * plugin: a DS-dependent rule surfaces it through `safeGetDS` as
3457
+ * `designSystemUnavailable` (what `enforce-canonical` does with the canonicalize
3458
+ * worker), a DS-OPTIONAL rule catches it and degrades.
3336
3459
  */
3337
3460
  function ask(cssPath, cache, classes) {
3338
3461
  const known = answersFor(cache);
3339
3462
  const pending = [...new Set(classes.filter((cls) => !known.has(cls)))];
3340
- if (pending.length === 0) return true;
3341
- let response;
3342
- try {
3343
- response = declWorker.callSync(cssPath, { classes: pending });
3344
- } catch (error) {
3345
- if (error instanceof SortServiceError) return false;
3346
- throw error;
3347
- }
3463
+ if (pending.length === 0) return;
3464
+ const response = declWorker.callSync(cssPath, { classes: pending });
3348
3465
  const invalid = new Set(response.invalid);
3349
3466
  for (const cls of pending) known.set(cls, !invalid.has(cls));
3350
3467
  for (const [cls, raws] of Object.entries(response.decls)) cache.internDeclarations(cls, raws, response.values);
3351
- return true;
3352
3468
  }
3353
3469
  /**
3354
3470
  * Resolve and intern declarations for `classes` that the precompute doesn't know.
3355
3471
  * They land in the cache, so the caller reads them back through
3356
3472
  * `cache.getCssDeclarations` like any other class.
3473
+ *
3474
+ * Throws `SortServiceError` if the service is unavailable — see `ask`.
3357
3475
  */
3358
3476
  function resolveDeclarationsSync(cssPath, cache, classes) {
3359
3477
  ask(cssPath, cache, classes);
3360
3478
  }
3361
3479
  /**
3362
- * Which of these classes produce CSS. `null` when the service is unavailable, so
3363
- * the caller can fall back instead of reading silence as an answer.
3480
+ * Which of these classes produce CSS.
3364
3481
  *
3365
3482
  * This is what makes validity exact for the classes the precompute cannot
3366
3483
  * enumerate: `w-45` and `bg-red-5000` are shaped identically, and only Tailwind
3367
- * knows that it compiles the first and not the second.
3484
+ * knows that it compiles the first and not the second. Throws
3485
+ * `SortServiceError` if the service is unavailable — see `ask`.
3368
3486
  */
3369
3487
  function validateClassesSync(cssPath, cache, classes) {
3370
- if (!ask(cssPath, cache, classes)) return null;
3488
+ ask(cssPath, cache, classes);
3371
3489
  return answersFor(cache);
3372
3490
  }
3373
3491
  //#endregion
@@ -3447,8 +3565,7 @@ const noUnknownClasses = defineRule({
3447
3565
  const memo = chainAnswers.get(key);
3448
3566
  if (memo !== void 0) return memo;
3449
3567
  const probe = `${chain}${PROBE_UTILITY}`;
3450
- const answers = validateClassesSync(entryPoint, cache, [probe]);
3451
- const verdict = answers ? answers.get(probe) ?? null : null;
3568
+ const verdict = validateClassesSync(entryPoint, cache, [probe]).get(probe) ?? null;
3452
3569
  chainAnswers.set(key, verdict);
3453
3570
  return verdict;
3454
3571
  }
@@ -3476,6 +3593,14 @@ const noUnknownClasses = defineRule({
3476
3593
  const ds = safeGetDS(getDS, context, locations[0].node);
3477
3594
  if (!ds) return;
3478
3595
  const { cache, entryPoint } = ds;
3596
+ try {
3597
+ checkLocations(locations, cache, entryPoint);
3598
+ } catch (error) {
3599
+ if (reportFatalDsError(context, error, locations[0].node)) return;
3600
+ throw error;
3601
+ }
3602
+ }
3603
+ function checkLocations(locations, cache, entryPoint) {
3479
3604
  for (const loc of locations) {
3480
3605
  const split = splitClassesWithSeparators(loc.value);
3481
3606
  const classes = split.classes;
@@ -3946,7 +4071,12 @@ const noConflictingClasses = defineRule({
3946
4071
  for (const [, variantClasses] of byVariant) {
3947
4072
  if (variantClasses.length < 2) continue;
3948
4073
  const unknown = variantClasses.map((cls) => splitImportant(extractUtility(cls)).bare).filter((bare) => cache.getCssDeclarations(bare).length === 0 && isUserValued(bare));
3949
- if (unknown.length > 0) resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4074
+ if (unknown.length > 0) {
4075
+ if (!safeGetDS(() => {
4076
+ resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4077
+ return true;
4078
+ }, context, loc.node)) return;
4079
+ }
3950
4080
  const facts = variantClasses.map((cls) => {
3951
4081
  const utility = extractUtility(cls);
3952
4082
  const bare = splitImportant(utility).bare;
@@ -5686,7 +5816,12 @@ const noDarkWithoutLight = defineRule({
5686
5816
  if (!unresolved) unresolved = [];
5687
5817
  unresolved.push(bare);
5688
5818
  }
5689
- if (unresolved) resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5819
+ if (unresolved) try {
5820
+ resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5821
+ } catch (error) {
5822
+ if (!isFatalError(error)) throw error;
5823
+ debugLog(`declaration service unavailable, grouping by prefix only: ${String(error)}`);
5824
+ }
5690
5825
  }
5691
5826
  const basePrefixes = /* @__PURE__ */ new Set();
5692
5827
  const baseProperties = /* @__PURE__ */ new Set();
@@ -6320,6 +6455,106 @@ function detectRawVariable(utility) {
6320
6455
  };
6321
6456
  return null;
6322
6457
  }
6458
+ const preferThemeTokens = defineRule({
6459
+ meta: {
6460
+ type: "suggestion",
6461
+ docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6462
+ fixable: "code",
6463
+ schema: [{
6464
+ type: "object",
6465
+ properties: { entryPoint: { type: "string" } },
6466
+ additionalProperties: false
6467
+ }],
6468
+ hasSuggestions: true,
6469
+ defaultOptions: [{}],
6470
+ messages: {
6471
+ preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6472
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6473
+ ...DS_UNAVAILABLE_MESSAGE
6474
+ }
6475
+ },
6476
+ createOnce(context) {
6477
+ const getDS = createLazyLoader(context);
6478
+ function check(locations) {
6479
+ if (locations.length === 0) return;
6480
+ const ds = safeGetDS(getDS, context, locations[0].node);
6481
+ if (!ds) return;
6482
+ const { cache } = ds;
6483
+ for (const loc of locations) {
6484
+ const split = splitClassesWithSeparators(loc.value);
6485
+ const offending = split.classes.flatMap((cls) => {
6486
+ const { utility, variant } = splitUtilityAndVariant(cls);
6487
+ const { bare: bareUtility, position } = splitImportant(utility);
6488
+ const match = detectRawVariable(bareUtility);
6489
+ if (!match) return [];
6490
+ const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6491
+ if (!cache.isValid(candidate)) return [];
6492
+ const target = `--${match.varName}`;
6493
+ const baseCandidate = `${match.prefix}-${match.varName}`;
6494
+ if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6495
+ const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6496
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6497
+ return [{
6498
+ cls,
6499
+ replacement: variant + reattachImportant(candidate, position)
6500
+ }];
6501
+ });
6502
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6503
+ }
6504
+ }
6505
+ return createExtractorVisitors(context, check);
6506
+ }
6507
+ });
6508
+ //#endregion
6509
+ //#region src/rules/prefer-scale-token.ts
6510
+ /** A length or plain number. Anything else can't be compared arithmetically. */
6511
+ const LENGTH_RE = /^(-?\d*\.?\d+)(rem|px|em)?$/;
6512
+ /**
6513
+ * Parse a CSS length. `em` is treated as `rem`, which is what it is at the root
6514
+ * and the only interpretation available without a layout.
6515
+ */
6516
+ function measure(value, rootFontSize) {
6517
+ const match = LENGTH_RE.exec(value.trim());
6518
+ if (!match) return null;
6519
+ const n = Number.parseFloat(match[1]);
6520
+ if (!Number.isFinite(n)) return null;
6521
+ switch (match[2]) {
6522
+ case "rem":
6523
+ case "em": return {
6524
+ px: n * rootFontSize,
6525
+ unitless: false
6526
+ };
6527
+ case "px": return {
6528
+ px: n,
6529
+ unitless: false
6530
+ };
6531
+ case void 0: return {
6532
+ px: n,
6533
+ unitless: true
6534
+ };
6535
+ default: return null;
6536
+ }
6537
+ }
6538
+ /**
6539
+ * Same value, allowing for float noise (`0.875rem` × 16 = 13.999999999999998).
6540
+ * A unitless number and a length are never the same value, whatever the digits.
6541
+ */
6542
+ function sameMeasure(a, b) {
6543
+ return a.unitless === b.unitless && Math.abs(a.px - b.px) < 1e-4;
6544
+ }
6545
+ /**
6546
+ * Is `n` a whole number of `step`s? `10 / 0.5` is exact in binary, `0.3 / 0.1`
6547
+ * is not, so the remainder is compared with a tolerance rather than to zero.
6548
+ */
6549
+ function isOnStep(n, step) {
6550
+ if (step <= 0) return false;
6551
+ const steps = n / step;
6552
+ return Math.abs(steps - Math.round(steps)) < 1e-4;
6553
+ }
6554
+ /** Trailing zeros make `p-2.50`, which is not what Tailwind calls the class. */
6555
+ function formatStep(n) {
6556
+ return String(Number.parseFloat(n.toFixed(4)));
6557
+ }
6323
6558
  //#endregion
6324
6559
  //#region src/index.ts
6325
6560
  const plugin = definePlugin({
@@ -6347,26 +6582,77 @@ const plugin = definePlugin({
6347
6582
  "consistent-variant-order": consistentVariantOrder,
6348
6583
  "enforce-consistent-line-wrapping": enforceConsistentLineWrapping,
6349
6584
  "no-unnecessary-arbitrary-value": noUnnecessaryArbitraryValue,
6350
- "prefer-theme-tokens": defineRule({
6585
+ "prefer-theme-tokens": preferThemeTokens,
6586
+ "prefer-scale-token": defineRule({
6351
6587
  meta: {
6352
6588
  type: "suggestion",
6353
- docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6354
- fixable: "code",
6589
+ docs: { description: "Prefer the scale step or theme token a hardcoded value is numerically equal to" },
6590
+ hasSuggestions: true,
6355
6591
  schema: [{
6356
6592
  type: "object",
6357
- properties: { entryPoint: { type: "string" } },
6593
+ properties: {
6594
+ entryPoint: { type: "string" },
6595
+ step: { type: "number" },
6596
+ allow: {
6597
+ type: "array",
6598
+ items: { type: "string" }
6599
+ }
6600
+ },
6358
6601
  additionalProperties: false
6359
6602
  }],
6360
- hasSuggestions: true,
6361
6603
  defaultOptions: [{}],
6362
6604
  messages: {
6363
- preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6605
+ preferToken: "\"{{className}}\" is the same value as \"{{replacement}}\". Use the token — but check it first: the token resolves through a CSS variable, so the two are equal in this theme, not by construction.",
6364
6606
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6365
6607
  ...DS_UNAVAILABLE_MESSAGE
6366
6608
  }
6367
6609
  },
6368
6610
  createOnce(context) {
6369
6611
  const getDS = createLazyLoader(context);
6612
+ const getOptions = createLazyOptions(context, (o) => ({
6613
+ step: typeof o?.step === "number" ? o.step : null,
6614
+ allow: o?.allow ?? []
6615
+ }));
6616
+ let _rem = null;
6617
+ function rootFontSize() {
6618
+ if (_rem === null) _rem = rootFontSizeFromSettings(safeSettings(context));
6619
+ return _rem;
6620
+ }
6621
+ /**
6622
+ * The class this literal could have been written as, or null.
6623
+ *
6624
+ * Two families, in order of preference: a named theme token whose value
6625
+ * matches (`rounded-[0.5rem]` → `rounded-lg`), then a step of the spacing
6626
+ * scale (`p-[10px]` → `p-2.5`). Both come from data the precompute derived
6627
+ * from the design system, so neither is a name table.
6628
+ */
6629
+ function equivalentOf(cache, bare) {
6630
+ const { step: stepOverride, allow } = getOptions();
6631
+ if (allow.some((prefix) => bare.startsWith(prefix))) return null;
6632
+ if (cache.getNamedEquivalent(bare)) return null;
6633
+ const value = getArbitraryValue(bare);
6634
+ if (value === null) return null;
6635
+ const written = measure(value, rootFontSize());
6636
+ if (written === null) return null;
6637
+ const open = bare.indexOf("[");
6638
+ if (open <= 0 || bare[open - 1] !== "-") return null;
6639
+ const prefix = bare.slice(0, open - 1);
6640
+ if (!prefix) return null;
6641
+ for (const [literal, className] of cache.tokenValuesFor(prefix)) {
6642
+ const token = measure(literal, rootFontSize());
6643
+ if (token !== null && sameMeasure(written, token)) return className;
6644
+ }
6645
+ if (!cache.readsScale(prefix)) return null;
6646
+ const scale = cache.scale;
6647
+ if (!scale) return null;
6648
+ const unit = measure(scale.unit, rootFontSize());
6649
+ if (unit === null || unit.px <= 0 || unit.unitless !== written.unitless) return null;
6650
+ const steps = written.px / unit.px;
6651
+ if (steps < 0) return null;
6652
+ if (!isOnStep(steps, stepOverride ?? scale.step)) return null;
6653
+ const candidate = `${prefix}-${formatStep(steps)}`;
6654
+ return cache.isValid(candidate) ? candidate : null;
6655
+ }
6370
6656
  function check(locations) {
6371
6657
  if (locations.length === 0) return;
6372
6658
  const ds = safeGetDS(getDS, context, locations[0].node);
@@ -6374,24 +6660,33 @@ const plugin = definePlugin({
6374
6660
  const { cache } = ds;
6375
6661
  for (const loc of locations) {
6376
6662
  const split = splitClassesWithSeparators(loc.value);
6377
- const offending = split.classes.flatMap((cls) => {
6663
+ for (const cls of split.classes) {
6664
+ if (!utilityHasDynamicValue(cls)) continue;
6378
6665
  const { utility, variant } = splitUtilityAndVariant(cls);
6379
- const { bare: bareUtility, position } = splitImportant(utility);
6380
- const match = detectRawVariable(bareUtility);
6381
- if (!match) return [];
6382
- const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6383
- if (!cache.isValid(candidate)) return [];
6384
- const target = `--${match.varName}`;
6385
- const baseCandidate = `${match.prefix}-${match.varName}`;
6386
- if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6387
- const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6388
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6389
- return [{
6390
- cls,
6391
- replacement: variant + reattachImportant(candidate, position)
6392
- }];
6393
- });
6394
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6666
+ const { bare, position } = splitImportant(utility);
6667
+ const equivalent = equivalentOf(cache, bare);
6668
+ if (!equivalent) continue;
6669
+ const replacement = variant + reattachImportant(equivalent, position);
6670
+ const fixedValue = rebuildClassString(split, split.classes.map((c) => c === cls ? replacement : c));
6671
+ context.report({
6672
+ node: loc.node,
6673
+ messageId: "preferToken",
6674
+ data: {
6675
+ className: cls,
6676
+ replacement
6677
+ },
6678
+ suggest: [{
6679
+ messageId: "suggestReplace",
6680
+ data: {
6681
+ className: cls,
6682
+ replacement
6683
+ },
6684
+ fix(fixer) {
6685
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6686
+ }
6687
+ }]
6688
+ });
6689
+ }
6395
6690
  }
6396
6691
  }
6397
6692
  return createExtractorVisitors(context, check);
package/dist/index.mjs CHANGED
@@ -963,6 +963,7 @@ function roundRemValue(className) {
963
963
  //#endregion
964
964
  //#region src/design-system/cache.ts
965
965
  const EMPTY_DECLARATIONS = [];
966
+ const EMPTY_TOKEN_VALUES = [];
966
967
  var DesignSystemCache = class DesignSystemCache {
967
968
  canonicalMap = /* @__PURE__ */ new Map();
968
969
  deprecatedMap = /* @__PURE__ */ new Map();
@@ -974,6 +975,7 @@ var DesignSystemCache = class DesignSystemCache {
974
975
  propsMemo = /* @__PURE__ */ new Map();
975
976
  partialSet = /* @__PURE__ */ new Set();
976
977
  valueIdByText = null;
978
+ nextValueId = 0;
977
979
  variantOrderMap = /* @__PURE__ */ new Map();
978
980
  variantFactsMap = /* @__PURE__ */ new Map();
979
981
  arbitraryEquivMap = /* @__PURE__ */ new Map();
@@ -984,6 +986,8 @@ var DesignSystemCache = class DesignSystemCache {
984
986
  componentSet = /* @__PURE__ */ new Set();
985
987
  themeRefs = /* @__PURE__ */ new Map();
986
988
  definedVarSet = /* @__PURE__ */ new Set();
989
+ tokenValuesMap = /* @__PURE__ */ new Map();
990
+ scaleFacts = null;
987
991
  static fromPrecomputed(data) {
988
992
  const cache = new DesignSystemCache();
989
993
  cache._validClasses = data.validClasses;
@@ -1011,6 +1015,12 @@ var DesignSystemCache = class DesignSystemCache {
1011
1015
  }
1012
1016
  for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
1013
1017
  if (data.themeRefs) for (const [name, refs] of Object.entries(data.themeRefs)) cache.themeRefs.set(name, refs);
1018
+ for (const [prefix, entries] of Object.entries(data.tokenValues ?? {})) cache.tokenValuesMap.set(prefix, entries);
1019
+ if (data.scale) cache.scaleFacts = {
1020
+ unit: data.scale.unit,
1021
+ step: data.scale.step,
1022
+ prefixes: new Set(data.scale.prefixes)
1023
+ };
1014
1024
  cache._prefix = data.prefix ?? "";
1015
1025
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
1016
1026
  return cache;
@@ -1137,6 +1147,27 @@ var DesignSystemCache = class DesignSystemCache {
1137
1147
  variantNames() {
1138
1148
  return [...this.variantOrderMap.keys()];
1139
1149
  }
1150
+ /**
1151
+ * The numeric theme tokens this utility prefix can be written with, as
1152
+ * `[literal value, class]`. Empty when the prefix has none.
1153
+ */
1154
+ tokenValuesFor(prefix) {
1155
+ return this.tokenValuesMap.get(this.stripProjectPrefix(prefix)) ?? EMPTY_TOKEN_VALUES;
1156
+ }
1157
+ /**
1158
+ * The spacing scale as the design system describes it: the resolved value of
1159
+ * `--spacing`, the granularity Tailwind's own enumerated steps use, and whether
1160
+ * a given prefix reads it. `null` when the theme has no `--spacing`.
1161
+ */
1162
+ get scale() {
1163
+ return this.scaleFacts ? {
1164
+ unit: this.scaleFacts.unit,
1165
+ step: this.scaleFacts.step
1166
+ } : null;
1167
+ }
1168
+ readsScale(prefix) {
1169
+ return this.scaleFacts?.prefixes.has(this.stripProjectPrefix(prefix)) ?? false;
1170
+ }
1140
1171
  isValid(className) {
1141
1172
  if (this.validitySet.has(className)) return true;
1142
1173
  const utility = extractUtility(className);
@@ -1281,7 +1312,10 @@ var DesignSystemCache = class DesignSystemCache {
1281
1312
  internDeclarations(className, raws, valueFacts) {
1282
1313
  const index = this.declIndex;
1283
1314
  if (!index) return EMPTY_DECLARATIONS;
1284
- if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1315
+ if (!this.valueIdByText) {
1316
+ this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1317
+ this.nextValueId = index.values.length;
1318
+ }
1285
1319
  const decls = [];
1286
1320
  let hasElement = false;
1287
1321
  let hasDescendant = false;
@@ -1289,8 +1323,7 @@ var DesignSystemCache = class DesignSystemCache {
1289
1323
  for (const [scopeToken, prop, value] of raws) {
1290
1324
  let valueId = this.valueIdByText.get(value);
1291
1325
  if (valueId === void 0) {
1292
- valueId = index.values.length;
1293
- index.values.push(value);
1326
+ valueId = this.nextValueId++;
1294
1327
  this.valueIdByText.set(value, valueId);
1295
1328
  }
1296
1329
  const facts = valueFacts[value];
@@ -1811,7 +1844,12 @@ function resolveImport(specifier, baseDir) {
1811
1844
  return null;
1812
1845
  }
1813
1846
 
1814
- function extractComponentClasses(cssPath, baseDir) {
1847
+ // The entry CSS plus every \`@import\` that resolves, one level deep. Shared by
1848
+ // the component-class scan and the \`definedVars\` scan: a custom property declared
1849
+ // in an imported file is as real to the browser as one in the entry, and treating
1850
+ // it as undefined makes prefer-theme-tokens propose a token that can change the
1851
+ // design (the #78 hazard, in miniature).
1852
+ function collectCssSources(cssPath, baseDir) {
1815
1853
  let css;
1816
1854
  try { css = readFileSync(cssPath, 'utf-8'); } catch { return []; }
1817
1855
  const files = [css];
@@ -1823,6 +1861,11 @@ function extractComponentClasses(cssPath, baseDir) {
1823
1861
  try { files.push(readFileSync(resolved, 'utf-8')); } catch {}
1824
1862
  }
1825
1863
  }
1864
+ return files;
1865
+ }
1866
+
1867
+ function extractComponentClasses(cssPath, baseDir) {
1868
+ const files = collectCssSources(cssPath, baseDir);
1826
1869
  const result = [];
1827
1870
  for (const content of files) {
1828
1871
  // Scan both @layer components AND @layer utilities
@@ -2309,20 +2352,21 @@ async function main() {
2309
2352
  }
2310
2353
  }
2311
2354
 
2312
- // Theme variables that dereference to another custom property. Only the
2313
- // referencing ones are stored (~a handful), and the reference list reuses the
2314
- // same balanced scanner the declaration values go through.
2315
- // Custom properties the project defines. The entry file covers the standard
2316
- // ':root { --x: ... }' pattern; definitions inside @imported files are not
2317
- // scanned, so an unseen definition reads as "undefined" — which only ever makes
2318
- // prefer-theme-tokens more willing to suggest, never less accurate about a
2319
- // definition it can see.
2320
- const definedVars = [...new Set(css.match(/--[\\w-]+(?=\\s*:)/g) || [])];
2355
+ // Custom properties the project defines, across the entry AND its resolved
2356
+ // @imports — splitting the theme across files is the normal shadcn/ui layout,
2357
+ // and a definition we cannot see reads as "undefined", which is what makes
2358
+ // prefer-theme-tokens propose a token that means something else. One level
2359
+ // deep, same as the component-class scan it shares \`collectCssSources\` with.
2360
+ const definedVars = [...new Set(
2361
+ collectCssSources(cssPath, base).flatMap(src => src.match(/--[\\w-]+(?=\\s*:)/g) || [])
2362
+ )];
2321
2363
 
2322
2364
  const themeRefs = {};
2365
+ const themeValues = new Map();
2323
2366
  if (ds.theme && typeof ds.theme.entries === 'function') {
2324
2367
  for (const [name, entry] of ds.theme.entries()) {
2325
2368
  const value = entry && typeof entry.value === 'string' ? entry.value : '';
2369
+ themeValues.set(name, value);
2326
2370
  if (!value.includes('var(')) continue;
2327
2371
  const reads = scanVarReads(value);
2328
2372
  const all = [...new Set([...reads[0], ...reads[1]])];
@@ -2330,7 +2374,77 @@ async function main() {
2330
2374
  }
2331
2375
  }
2332
2376
 
2333
- const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
2377
+ // ── What a literal value could have been written as (for prefer-scale-token) ──
2378
+ //
2379
+ // Two families, both derived. Neither is a name table: the emitted CSS says
2380
+ // which variable a class reads and the theme says what that variable is worth.
2381
+
2382
+ // A single declaration whose whole value is one \`var(--x)\` that the theme
2383
+ // resolves to a NUMBER. Numeric because that is the only thing the rule can
2384
+ // compare — a colour token could never match a literal the user typed — and
2385
+ // SINGLE because a class that declares more than the original is not an
2386
+ // equivalent: \`text-sm\` sets \`line-height\` too, so \`text-[14px]\` is not it.
2387
+ const NUMERIC_LITERAL = /^-?\\d*\\.?\\d+(rem|px|em|%|s|ms|deg)?$/;
2388
+ const tokenValues = {};
2389
+ for (const cls of validClasses) {
2390
+ if (cls.includes('[') || cls.includes('/')) continue;
2391
+ const css = declCss[cls];
2392
+ if (!css) continue;
2393
+ const open = css.indexOf('{');
2394
+ const close = css.indexOf('}');
2395
+ if (open < 0 || close < 0) continue;
2396
+ const body = css.slice(open + 1, close).replace(/\\s+/g, ' ').replace(/;\\s*$/, '').trim();
2397
+ const m = /^([a-z-]+):\\s*var\\((--[\\w-]+)\\)$/.exec(body);
2398
+ if (!m) continue;
2399
+ const value = themeValues.get(m[2]);
2400
+ if (!value || !NUMERIC_LITERAL.test(value)) continue;
2401
+ const dash = cls.lastIndexOf('-');
2402
+ if (dash <= 0) continue;
2403
+ const prefix = unpfx(cls).slice(0, unpfx(cls).lastIndexOf('-'));
2404
+ if (!prefix) continue;
2405
+ if (!tokenValues[prefix]) tokenValues[prefix] = [];
2406
+ tokenValues[prefix].push([value, unpfx(cls)]);
2407
+ }
2408
+
2409
+ // The spacing scale: its unit, which prefixes read it, and the granularity
2410
+ // Tailwind's own enumerated steps use. Every step getClassList() lists is a
2411
+ // multiple of that granularity, so deriving it is how the rule stays inside
2412
+ // what Tailwind does instead of inventing a threshold.
2413
+ const scaleUnit = themeValues.get('--spacing') || '';
2414
+ const scalePrefixes = [];
2415
+ if (scaleUnit) {
2416
+ const probes = [...knownPrefixes];
2417
+ const probeResults = ds.candidatesToCss(probes.map(p => pfx(p + '-1')));
2418
+ for (let i = 0; i < probes.length; i++) {
2419
+ const css = probeResults[i];
2420
+ if (!css) continue;
2421
+ // \`size-1\` emits width AND height, both reading the unit — one match is enough.
2422
+ if (css.includes('var(--spacing)')) scalePrefixes.push(probes[i]);
2423
+ }
2424
+ }
2425
+ let scaleStep = 0;
2426
+ if (scalePrefixes.length > 0) {
2427
+ const steps = new Set();
2428
+ const scaleSet = new Set(scalePrefixes);
2429
+ for (const cls of validClasses) {
2430
+ const dash = cls.lastIndexOf('-');
2431
+ if (dash <= 0) continue;
2432
+ if (!scaleSet.has(cls.slice(0, dash))) continue;
2433
+ const suffix = cls.slice(dash + 1);
2434
+ if (!/^\\d*\\.?\\d+$/.test(suffix)) continue;
2435
+ steps.add(parseFloat(suffix));
2436
+ }
2437
+ const sorted = [...steps].sort((a, b) => a - b);
2438
+ for (let i = 1; i < sorted.length; i++) {
2439
+ const gap = Math.round((sorted[i] - sorted[i - 1]) * 1000) / 1000;
2440
+ if (gap > 0 && (scaleStep === 0 || gap < scaleStep)) scaleStep = gap;
2441
+ }
2442
+ }
2443
+ const scale = scaleUnit && scalePrefixes.length > 0
2444
+ ? { unit: scaleUnit, step: scaleStep || 1, prefixes: scalePrefixes.sort() }
2445
+ : undefined;
2446
+
2447
+ const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, tokenValues, scale, prefix });
2334
2448
  // Atomic write: write to a unique temp path then rename, so a peer isolate
2335
2449
  // busy-waiting on the cache file never observes a half-written JSON.
2336
2450
  writeFileSync(WD_TMP_PATH, json);
@@ -3333,45 +3447,49 @@ function answersFor(cache) {
3333
3447
  * Ask the design system about every class there is no answer for yet, intern the
3334
3448
  * declarations it returns, and record which classes produce no CSS at all.
3335
3449
  *
3336
- * Returns false when the service is unavailable. Callers treat that as "no
3337
- * information" rather than as an answer, so a broken worker degrades to the
3338
- * behaviour that predates it instead of to wrong diagnostics. Real failures still
3339
- * surface through the sticky error the worker records.
3450
+ * **Throws `SortServiceError` when the service is unavailable**, like the sort and
3451
+ * canonicalize services do. It used to swallow the failure and report "no
3452
+ * information", which was defensible when `no-conflicting-classes` was the only
3453
+ * caller — no declarations means no comparison, so the rule just went quiet. It
3454
+ * stopped being defensible once `no-unknown-classes` started asking about
3455
+ * VALIDITY: there, silence sends the rule back to the tolerant heuristic, so a
3456
+ * dead worker quietly reinstates the very false negatives the service exists to
3457
+ * remove, with nothing anywhere to say so.
3458
+ *
3459
+ * The caller decides what to do, and the two postures already exist in the
3460
+ * plugin: a DS-dependent rule surfaces it through `safeGetDS` as
3461
+ * `designSystemUnavailable` (what `enforce-canonical` does with the canonicalize
3462
+ * worker), a DS-OPTIONAL rule catches it and degrades.
3340
3463
  */
3341
3464
  function ask(cssPath, cache, classes) {
3342
3465
  const known = answersFor(cache);
3343
3466
  const pending = [...new Set(classes.filter((cls) => !known.has(cls)))];
3344
- if (pending.length === 0) return true;
3345
- let response;
3346
- try {
3347
- response = declWorker.callSync(cssPath, { classes: pending });
3348
- } catch (error) {
3349
- if (error instanceof SortServiceError) return false;
3350
- throw error;
3351
- }
3467
+ if (pending.length === 0) return;
3468
+ const response = declWorker.callSync(cssPath, { classes: pending });
3352
3469
  const invalid = new Set(response.invalid);
3353
3470
  for (const cls of pending) known.set(cls, !invalid.has(cls));
3354
3471
  for (const [cls, raws] of Object.entries(response.decls)) cache.internDeclarations(cls, raws, response.values);
3355
- return true;
3356
3472
  }
3357
3473
  /**
3358
3474
  * Resolve and intern declarations for `classes` that the precompute doesn't know.
3359
3475
  * They land in the cache, so the caller reads them back through
3360
3476
  * `cache.getCssDeclarations` like any other class.
3477
+ *
3478
+ * Throws `SortServiceError` if the service is unavailable — see `ask`.
3361
3479
  */
3362
3480
  function resolveDeclarationsSync(cssPath, cache, classes) {
3363
3481
  ask(cssPath, cache, classes);
3364
3482
  }
3365
3483
  /**
3366
- * Which of these classes produce CSS. `null` when the service is unavailable, so
3367
- * the caller can fall back instead of reading silence as an answer.
3484
+ * Which of these classes produce CSS.
3368
3485
  *
3369
3486
  * This is what makes validity exact for the classes the precompute cannot
3370
3487
  * enumerate: `w-45` and `bg-red-5000` are shaped identically, and only Tailwind
3371
- * knows that it compiles the first and not the second.
3488
+ * knows that it compiles the first and not the second. Throws
3489
+ * `SortServiceError` if the service is unavailable — see `ask`.
3372
3490
  */
3373
3491
  function validateClassesSync(cssPath, cache, classes) {
3374
- if (!ask(cssPath, cache, classes)) return null;
3492
+ ask(cssPath, cache, classes);
3375
3493
  return answersFor(cache);
3376
3494
  }
3377
3495
  //#endregion
@@ -3451,8 +3569,7 @@ const noUnknownClasses = defineRule({
3451
3569
  const memo = chainAnswers.get(key);
3452
3570
  if (memo !== void 0) return memo;
3453
3571
  const probe = `${chain}${PROBE_UTILITY}`;
3454
- const answers = validateClassesSync(entryPoint, cache, [probe]);
3455
- const verdict = answers ? answers.get(probe) ?? null : null;
3572
+ const verdict = validateClassesSync(entryPoint, cache, [probe]).get(probe) ?? null;
3456
3573
  chainAnswers.set(key, verdict);
3457
3574
  return verdict;
3458
3575
  }
@@ -3480,6 +3597,14 @@ const noUnknownClasses = defineRule({
3480
3597
  const ds = safeGetDS(getDS, context, locations[0].node);
3481
3598
  if (!ds) return;
3482
3599
  const { cache, entryPoint } = ds;
3600
+ try {
3601
+ checkLocations(locations, cache, entryPoint);
3602
+ } catch (error) {
3603
+ if (reportFatalDsError(context, error, locations[0].node)) return;
3604
+ throw error;
3605
+ }
3606
+ }
3607
+ function checkLocations(locations, cache, entryPoint) {
3483
3608
  for (const loc of locations) {
3484
3609
  const split = splitClassesWithSeparators(loc.value);
3485
3610
  const classes = split.classes;
@@ -3950,7 +4075,12 @@ const noConflictingClasses = defineRule({
3950
4075
  for (const [, variantClasses] of byVariant) {
3951
4076
  if (variantClasses.length < 2) continue;
3952
4077
  const unknown = variantClasses.map((cls) => splitImportant(extractUtility(cls)).bare).filter((bare) => cache.getCssDeclarations(bare).length === 0 && isUserValued(bare));
3953
- if (unknown.length > 0) resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4078
+ if (unknown.length > 0) {
4079
+ if (!safeGetDS(() => {
4080
+ resolveDeclarationsSync(ds.entryPoint, cache, unknown);
4081
+ return true;
4082
+ }, context, loc.node)) return;
4083
+ }
3954
4084
  const facts = variantClasses.map((cls) => {
3955
4085
  const utility = extractUtility(cls);
3956
4086
  const bare = splitImportant(utility).bare;
@@ -5690,7 +5820,12 @@ const noDarkWithoutLight = defineRule({
5690
5820
  if (!unresolved) unresolved = [];
5691
5821
  unresolved.push(bare);
5692
5822
  }
5693
- if (unresolved) resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5823
+ if (unresolved) try {
5824
+ resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5825
+ } catch (error) {
5826
+ if (!isFatalError(error)) throw error;
5827
+ debugLog(`declaration service unavailable, grouping by prefix only: ${String(error)}`);
5828
+ }
5694
5829
  }
5695
5830
  const basePrefixes = /* @__PURE__ */ new Set();
5696
5831
  const baseProperties = /* @__PURE__ */ new Set();
@@ -6324,6 +6459,106 @@ function detectRawVariable(utility) {
6324
6459
  };
6325
6460
  return null;
6326
6461
  }
6462
+ const preferThemeTokens = defineRule({
6463
+ meta: {
6464
+ type: "suggestion",
6465
+ docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6466
+ fixable: "code",
6467
+ schema: [{
6468
+ type: "object",
6469
+ properties: { entryPoint: { type: "string" } },
6470
+ additionalProperties: false
6471
+ }],
6472
+ hasSuggestions: true,
6473
+ defaultOptions: [{}],
6474
+ messages: {
6475
+ preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6476
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6477
+ ...DS_UNAVAILABLE_MESSAGE
6478
+ }
6479
+ },
6480
+ createOnce(context) {
6481
+ const getDS = createLazyLoader(context);
6482
+ function check(locations) {
6483
+ if (locations.length === 0) return;
6484
+ const ds = safeGetDS(getDS, context, locations[0].node);
6485
+ if (!ds) return;
6486
+ const { cache } = ds;
6487
+ for (const loc of locations) {
6488
+ const split = splitClassesWithSeparators(loc.value);
6489
+ const offending = split.classes.flatMap((cls) => {
6490
+ const { utility, variant } = splitUtilityAndVariant(cls);
6491
+ const { bare: bareUtility, position } = splitImportant(utility);
6492
+ const match = detectRawVariable(bareUtility);
6493
+ if (!match) return [];
6494
+ const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6495
+ if (!cache.isValid(candidate)) return [];
6496
+ const target = `--${match.varName}`;
6497
+ const baseCandidate = `${match.prefix}-${match.varName}`;
6498
+ if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6499
+ const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6500
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6501
+ return [{
6502
+ cls,
6503
+ replacement: variant + reattachImportant(candidate, position)
6504
+ }];
6505
+ });
6506
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6507
+ }
6508
+ }
6509
+ return createExtractorVisitors(context, check);
6510
+ }
6511
+ });
6512
+ //#endregion
6513
+ //#region src/rules/prefer-scale-token.ts
6514
+ /** A length or plain number. Anything else can't be compared arithmetically. */
6515
+ const LENGTH_RE = /^(-?\d*\.?\d+)(rem|px|em)?$/;
6516
+ /**
6517
+ * Parse a CSS length. `em` is treated as `rem`, which is what it is at the root
6518
+ * and the only interpretation available without a layout.
6519
+ */
6520
+ function measure(value, rootFontSize) {
6521
+ const match = LENGTH_RE.exec(value.trim());
6522
+ if (!match) return null;
6523
+ const n = Number.parseFloat(match[1]);
6524
+ if (!Number.isFinite(n)) return null;
6525
+ switch (match[2]) {
6526
+ case "rem":
6527
+ case "em": return {
6528
+ px: n * rootFontSize,
6529
+ unitless: false
6530
+ };
6531
+ case "px": return {
6532
+ px: n,
6533
+ unitless: false
6534
+ };
6535
+ case void 0: return {
6536
+ px: n,
6537
+ unitless: true
6538
+ };
6539
+ default: return null;
6540
+ }
6541
+ }
6542
+ /**
6543
+ * Same value, allowing for float noise (`0.875rem` × 16 = 13.999999999999998).
6544
+ * A unitless number and a length are never the same value, whatever the digits.
6545
+ */
6546
+ function sameMeasure(a, b) {
6547
+ return a.unitless === b.unitless && Math.abs(a.px - b.px) < 1e-4;
6548
+ }
6549
+ /**
6550
+ * Is `n` a whole number of `step`s? `10 / 0.5` is exact in binary, `0.3 / 0.1`
6551
+ * is not, so the remainder is compared with a tolerance rather than to zero.
6552
+ */
6553
+ function isOnStep(n, step) {
6554
+ if (step <= 0) return false;
6555
+ const steps = n / step;
6556
+ return Math.abs(steps - Math.round(steps)) < 1e-4;
6557
+ }
6558
+ /** Trailing zeros make `p-2.50`, which is not what Tailwind calls the class. */
6559
+ function formatStep(n) {
6560
+ return String(Number.parseFloat(n.toFixed(4)));
6561
+ }
6327
6562
  //#endregion
6328
6563
  //#region src/index.ts
6329
6564
  const plugin = definePlugin({
@@ -6351,26 +6586,77 @@ const plugin = definePlugin({
6351
6586
  "consistent-variant-order": consistentVariantOrder,
6352
6587
  "enforce-consistent-line-wrapping": enforceConsistentLineWrapping,
6353
6588
  "no-unnecessary-arbitrary-value": noUnnecessaryArbitraryValue,
6354
- "prefer-theme-tokens": defineRule({
6589
+ "prefer-theme-tokens": preferThemeTokens,
6590
+ "prefer-scale-token": defineRule({
6355
6591
  meta: {
6356
6592
  type: "suggestion",
6357
- docs: { description: "Prefer named theme-token utilities over raw CSS variable references when a matching utility exists" },
6358
- fixable: "code",
6593
+ docs: { description: "Prefer the scale step or theme token a hardcoded value is numerically equal to" },
6594
+ hasSuggestions: true,
6359
6595
  schema: [{
6360
6596
  type: "object",
6361
- properties: { entryPoint: { type: "string" } },
6597
+ properties: {
6598
+ entryPoint: { type: "string" },
6599
+ step: { type: "number" },
6600
+ allow: {
6601
+ type: "array",
6602
+ items: { type: "string" }
6603
+ }
6604
+ },
6362
6605
  additionalProperties: false
6363
6606
  }],
6364
- hasSuggestions: true,
6365
6607
  defaultOptions: [{}],
6366
6608
  messages: {
6367
- preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
6609
+ preferToken: "\"{{className}}\" is the same value as \"{{replacement}}\". Use the token — but check it first: the token resolves through a CSS variable, so the two are equal in this theme, not by construction.",
6368
6610
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
6369
6611
  ...DS_UNAVAILABLE_MESSAGE
6370
6612
  }
6371
6613
  },
6372
6614
  createOnce(context) {
6373
6615
  const getDS = createLazyLoader(context);
6616
+ const getOptions = createLazyOptions(context, (o) => ({
6617
+ step: typeof o?.step === "number" ? o.step : null,
6618
+ allow: o?.allow ?? []
6619
+ }));
6620
+ let _rem = null;
6621
+ function rootFontSize() {
6622
+ if (_rem === null) _rem = rootFontSizeFromSettings(safeSettings(context));
6623
+ return _rem;
6624
+ }
6625
+ /**
6626
+ * The class this literal could have been written as, or null.
6627
+ *
6628
+ * Two families, in order of preference: a named theme token whose value
6629
+ * matches (`rounded-[0.5rem]` → `rounded-lg`), then a step of the spacing
6630
+ * scale (`p-[10px]` → `p-2.5`). Both come from data the precompute derived
6631
+ * from the design system, so neither is a name table.
6632
+ */
6633
+ function equivalentOf(cache, bare) {
6634
+ const { step: stepOverride, allow } = getOptions();
6635
+ if (allow.some((prefix) => bare.startsWith(prefix))) return null;
6636
+ if (cache.getNamedEquivalent(bare)) return null;
6637
+ const value = getArbitraryValue(bare);
6638
+ if (value === null) return null;
6639
+ const written = measure(value, rootFontSize());
6640
+ if (written === null) return null;
6641
+ const open = bare.indexOf("[");
6642
+ if (open <= 0 || bare[open - 1] !== "-") return null;
6643
+ const prefix = bare.slice(0, open - 1);
6644
+ if (!prefix) return null;
6645
+ for (const [literal, className] of cache.tokenValuesFor(prefix)) {
6646
+ const token = measure(literal, rootFontSize());
6647
+ if (token !== null && sameMeasure(written, token)) return className;
6648
+ }
6649
+ if (!cache.readsScale(prefix)) return null;
6650
+ const scale = cache.scale;
6651
+ if (!scale) return null;
6652
+ const unit = measure(scale.unit, rootFontSize());
6653
+ if (unit === null || unit.px <= 0 || unit.unitless !== written.unitless) return null;
6654
+ const steps = written.px / unit.px;
6655
+ if (steps < 0) return null;
6656
+ if (!isOnStep(steps, stepOverride ?? scale.step)) return null;
6657
+ const candidate = `${prefix}-${formatStep(steps)}`;
6658
+ return cache.isValid(candidate) ? candidate : null;
6659
+ }
6374
6660
  function check(locations) {
6375
6661
  if (locations.length === 0) return;
6376
6662
  const ds = safeGetDS(getDS, context, locations[0].node);
@@ -6378,24 +6664,33 @@ const plugin = definePlugin({
6378
6664
  const { cache } = ds;
6379
6665
  for (const loc of locations) {
6380
6666
  const split = splitClassesWithSeparators(loc.value);
6381
- const offending = split.classes.flatMap((cls) => {
6667
+ for (const cls of split.classes) {
6668
+ if (!utilityHasDynamicValue(cls)) continue;
6382
6669
  const { utility, variant } = splitUtilityAndVariant(cls);
6383
- const { bare: bareUtility, position } = splitImportant(utility);
6384
- const match = detectRawVariable(bareUtility);
6385
- if (!match) return [];
6386
- const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
6387
- if (!cache.isValid(candidate)) return [];
6388
- const target = `--${match.varName}`;
6389
- const baseCandidate = `${match.prefix}-${match.varName}`;
6390
- if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
6391
- const namedEquivalent = cache.getNamedEquivalent(bareUtility);
6392
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
6393
- return [{
6394
- cls,
6395
- replacement: variant + reattachImportant(candidate, position)
6396
- }];
6397
- });
6398
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
6670
+ const { bare, position } = splitImportant(utility);
6671
+ const equivalent = equivalentOf(cache, bare);
6672
+ if (!equivalent) continue;
6673
+ const replacement = variant + reattachImportant(equivalent, position);
6674
+ const fixedValue = rebuildClassString(split, split.classes.map((c) => c === cls ? replacement : c));
6675
+ context.report({
6676
+ node: loc.node,
6677
+ messageId: "preferToken",
6678
+ data: {
6679
+ className: cls,
6680
+ replacement
6681
+ },
6682
+ suggest: [{
6683
+ messageId: "suggestReplace",
6684
+ data: {
6685
+ className: cls,
6686
+ replacement
6687
+ },
6688
+ fix(fixer) {
6689
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
6690
+ }
6691
+ }]
6692
+ });
6693
+ }
6399
6694
  }
6400
6695
  }
6401
6696
  return createExtractorVisitors(context, check);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oxlint-tailwindcss",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Tailwind CSS linting rules for oxlint",
5
5
  "keywords": [
6
6
  "css",