oxlint-tailwindcss 1.3.5 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,7 +3,7 @@ let node_crypto = require("node:crypto");
3
3
  let node_fs = require("node:fs");
4
4
  let node_path = require("node:path");
5
5
  let node_os = require("node:os");
6
- //#region ../../node_modules/.pnpm/@oxlint+plugins@1.73.0/node_modules/@oxlint/plugins/index.js
6
+ //#region ../../node_modules/.pnpm/@oxlint+plugins@1.74.0/node_modules/@oxlint/plugins/index.js
7
7
  /**
8
8
  * Define a plugin.
9
9
  *
@@ -653,8 +653,8 @@ function extractVariants(cls) {
653
653
  const variants = [];
654
654
  let depth = 0;
655
655
  let segmentStart = 0;
656
- for (let i = 0; i < cls.length; i++) if (cls[i] === "[") depth++;
657
- else if (cls[i] === "]") depth--;
656
+ for (let i = 0; i < cls.length; i++) if (cls[i] === "[" || cls[i] === "(") depth++;
657
+ else if (cls[i] === "]" || cls[i] === ")") depth--;
658
658
  else if (cls[i] === ":" && depth === 0) {
659
659
  variants.push(cls.slice(segmentStart, i));
660
660
  segmentStart = i + 1;
@@ -674,8 +674,8 @@ function extractVariants(cls) {
674
674
  function extractUtility(cls) {
675
675
  let depth = 0;
676
676
  let lastColon = -1;
677
- for (let i = 0; i < cls.length; i++) if (cls[i] === "[") depth++;
678
- else if (cls[i] === "]") depth--;
677
+ for (let i = 0; i < cls.length; i++) if (cls[i] === "[" || cls[i] === "(") depth++;
678
+ else if (cls[i] === "]" || cls[i] === ")") depth--;
679
679
  else if (cls[i] === ":" && depth === 0) lastColon = i;
680
680
  return lastColon >= 0 ? cls.slice(lastColon + 1) : cls;
681
681
  }
@@ -687,8 +687,8 @@ function extractUtility(cls) {
687
687
  function getVariantPrefix(cls) {
688
688
  let depth = 0;
689
689
  let lastColon = -1;
690
- for (let i = 0; i < cls.length; i++) if (cls[i] === "[") depth++;
691
- else if (cls[i] === "]") depth--;
690
+ for (let i = 0; i < cls.length; i++) if (cls[i] === "[" || cls[i] === "(") depth++;
691
+ else if (cls[i] === "]" || cls[i] === ")") depth--;
692
692
  else if (cls[i] === ":" && depth === 0) lastColon = i;
693
693
  return lastColon >= 0 ? cls.slice(0, lastColon + 1) : "";
694
694
  }
@@ -699,8 +699,8 @@ function getVariantPrefix(cls) {
699
699
  function splitUtilityAndVariant(cls) {
700
700
  let depth = 0;
701
701
  let lastColon = -1;
702
- for (let i = 0; i < cls.length; i++) if (cls[i] === "[") depth++;
703
- else if (cls[i] === "]") depth--;
702
+ for (let i = 0; i < cls.length; i++) if (cls[i] === "[" || cls[i] === "(") depth++;
703
+ else if (cls[i] === "]" || cls[i] === ")") depth--;
704
704
  else if (cls[i] === ":" && depth === 0) lastColon = i;
705
705
  return {
706
706
  utility: lastColon >= 0 ? cls.slice(lastColon + 1) : cls,
@@ -731,6 +731,18 @@ function utilityHasDynamicValue(cls) {
731
731
  return utility.includes("[") || utility.includes("(");
732
732
  }
733
733
  /**
734
+ * A utility the precompute cannot have enumerated, because the VALUE comes from
735
+ * the user rather than from the design system's class list: arbitrary brackets,
736
+ * the `(--var)` shorthand, a `/` modifier, or an off-scale number.
737
+ *
738
+ * Asking the design system about exactly these is what closes the "looks like
739
+ * coverage" false negatives — `p-4 p-[5px]` used to be accepted silently while
740
+ * `p-4 p-6` reported. Takes the bare utility (no variants, no `!`).
741
+ */
742
+ function isUserValued(utility) {
743
+ return utility.includes("[") || utility.includes("(") || utility.includes("/") || /-\d/.test(utility);
744
+ }
745
+ /**
734
746
  * Gets the arbitrary value from a class, or null if none.
735
747
  * e.g. "w-[200px]" → "200px"
736
748
  * "bg-[#ff0000]" → "#ff0000"
@@ -779,11 +791,13 @@ function reattachImportant(bare, position) {
779
791
  return bare;
780
792
  }
781
793
  /**
782
- * Pseudo-element variants. They select a generated box (`::before`, `::marker`,
783
- * …) rather than the element itself, so they must sit innermost in the variant
784
- * chain (closest to the utility). Canonical home shared by
785
- * `consistent-variant-order` (partitions them last) and
786
- * `no-contradicting-variants` (they can't contradict a base class).
794
+ * Pseudo-element variants, as a static fallback for when no design system is
795
+ * configured. They select a generated box (`::before`, `::marker`, …) rather than
796
+ * the element itself, so they must sit innermost in the variant chain (closest to
797
+ * the utility).
798
+ *
799
+ * Prefer the derived facts: this list cannot know a project's own variants, and
800
+ * `consistent-variant-order` is DS-optional by design, so both paths must work.
787
801
  */
788
802
  const PSEUDO_ELEMENT_VARIANTS = /* @__PURE__ */ new Set([
789
803
  "before",
@@ -797,32 +811,135 @@ const PSEUDO_ELEMENT_VARIANTS = /* @__PURE__ */ new Set([
797
811
  "first-letter",
798
812
  "details-content"
799
813
  ]);
800
- function isPseudoElementVariant(variant) {
814
+ function isPseudoElementVariant(variant, facts) {
815
+ if (facts) return facts.pseudoElement === true;
801
816
  return PSEUDO_ELEMENT_VARIANTS.has(variant);
802
817
  }
803
818
  /**
804
819
  * Selector barriers: variants that re-point the selector at a *different*
805
- * element than the ones around them — child (`*`), descendant (`**`),
806
- * arbitrary selectors (`[&>svg]`) and compound child selectors (`*:data-[…]`).
820
+ * element than the ones around them — child (`*`), descendant (`**`), arbitrary
821
+ * selectors (`[&>svg]`), compound child selectors (`*:data-[…]`), and — only
822
+ * visible in the generated selector — ancestor/sibling variants like
823
+ * `group-hover` and `peer-checked`.
807
824
  *
808
825
  * Unlike pseudo-elements, these are NOT free to move to the end of the chain:
809
826
  * `hover:*:flex` (`&:hover > *`) and `*:hover:flex` (`& > *:hover`) target
810
- * different elements. `consistent-variant-order` treats them as hard
827
+ * different elements, and `peer-checked:group-hover:*` is not
828
+ * `group-hover:peer-checked:*`. `consistent-variant-order` treats them as hard
811
829
  * reordering barriers — variants never cross them.
830
+ *
831
+ * The syntactic checks stay as the fallback, and also as a floor: an arbitrary
832
+ * selector is a barrier whether or not the design system enumerated it.
812
833
  */
813
- function isSelectorBarrier(variant) {
834
+ function isSelectorBarrier(variant, facts) {
814
835
  if (variant === "*" || variant === "**") return true;
815
836
  if (variant.startsWith("[") && variant.endsWith("]")) return true;
816
837
  if (variant.startsWith("*:")) return true;
817
- return false;
838
+ return facts?.structural === true;
818
839
  }
819
840
  /**
820
841
  * Whether a variant changes the selector target (pseudo-element OR selector
821
842
  * barrier). Such variants don't impose a condition on the same element, so they
822
843
  * can't make a variant class contradict/duplicate a base class.
823
844
  */
824
- function changesTarget(variant) {
825
- return isPseudoElementVariant(variant) || isSelectorBarrier(variant);
845
+ function changesTarget(variant, facts) {
846
+ return isPseudoElementVariant(variant, facts) || isSelectorBarrier(variant, facts);
847
+ }
848
+ //#endregion
849
+ //#region src/design-system/css-declarations.ts
850
+ const EMPTY_DECLS = [];
851
+ const EMPTY_VARS = [];
852
+ /** Splits a scope token into its decoded parts. Unknown tokens degrade to `element`. */
853
+ function parseScopeToken(token) {
854
+ const conditional = token.startsWith("@");
855
+ const body = conditional ? token.slice(1) : token;
856
+ if (body === "") return {
857
+ scope: "element",
858
+ pseudo: "",
859
+ conditional
860
+ };
861
+ if (body === ">") return {
862
+ scope: "descendant",
863
+ pseudo: "",
864
+ conditional
865
+ };
866
+ if (body.startsWith("::")) return {
867
+ scope: "pseudo",
868
+ pseudo: body,
869
+ conditional
870
+ };
871
+ return {
872
+ scope: "element",
873
+ pseudo: "",
874
+ conditional
875
+ };
876
+ }
877
+ /**
878
+ * Builds a decoder bound to one index. The returned function turns a packed
879
+ * `byClass` entry into declarations, memoizing each table entry the first time
880
+ * it is touched — a linted file mentions hundreds of classes, not 23 000.
881
+ */
882
+ function createDeclarationDecoder(index) {
883
+ const pure = new Set(index.pureValues);
884
+ const decoded = Array.from({ length: index.table.length });
885
+ function varNames(map, valueId) {
886
+ const ids = map[String(valueId)];
887
+ if (!ids || ids.length === 0) return EMPTY_VARS;
888
+ const out = [];
889
+ for (const id of ids) {
890
+ const name = index.vars[id];
891
+ if (name !== void 0) out.push(name);
892
+ }
893
+ return out;
894
+ }
895
+ function declAt(declId) {
896
+ const cached = decoded[declId];
897
+ if (cached) return cached;
898
+ const entry = index.table[declId];
899
+ if (entry === void 0) return void 0;
900
+ const first = entry.indexOf("|");
901
+ const second = entry.indexOf("|", first + 1);
902
+ if (first < 0 || second < 0) return void 0;
903
+ const scopeId = parseInt(entry.slice(0, first), 36);
904
+ const propId = parseInt(entry.slice(first + 1, second), 36);
905
+ const valueId = parseInt(entry.slice(second + 1), 36);
906
+ const prop = index.props[propId];
907
+ const value = index.values[valueId];
908
+ if (prop === void 0 || value === void 0) return void 0;
909
+ const { scope, pseudo, conditional } = parseScopeToken(index.scopes[scopeId] ?? "");
910
+ const decl = {
911
+ prop,
912
+ value,
913
+ valueId,
914
+ scope,
915
+ pseudo,
916
+ conditional,
917
+ readsVars: varNames(index.valueVars, valueId),
918
+ readsFallbackVars: varNames(index.valueFallbackVars, valueId),
919
+ pureVarRead: pure.has(valueId)
920
+ };
921
+ decoded[declId] = decl;
922
+ return decl;
923
+ }
924
+ return function decode(packed) {
925
+ if (!packed) return EMPTY_DECLS;
926
+ const out = [];
927
+ let start = 0;
928
+ for (let i = 0; i <= packed.length; i++) if (i === packed.length || packed[i] === ",") {
929
+ if (i > start) {
930
+ const decl = declAt(parseInt(packed.slice(start, i), 36));
931
+ if (decl) out.push(decl);
932
+ }
933
+ start = i + 1;
934
+ }
935
+ return out;
936
+ };
937
+ }
938
+ /** Shape check for a value read back from the disk cache. */
939
+ function isCssDeclarationIndex(value) {
940
+ if (typeof value !== "object" || value === null) return false;
941
+ const i = value;
942
+ return Array.isArray(i.scopes) && i.scopes.length > 0 && i.scopes[0] === "" && Array.isArray(i.props) && Array.isArray(i.values) && Array.isArray(i.vars) && Array.isArray(i.table) && Array.isArray(i.pureValues) && Array.isArray(i.partial) && typeof i.byClass === "object" && i.byClass !== null && typeof i.valueVars === "object" && i.valueVars !== null && typeof i.valueFallbackVars === "object" && i.valueFallbackVars !== null;
826
943
  }
827
944
  //#endregion
828
945
  //#region src/utils/floating-point.ts
@@ -841,34 +958,55 @@ function roundRemValue(className) {
841
958
  }
842
959
  //#endregion
843
960
  //#region src/design-system/cache.ts
961
+ const EMPTY_DECLARATIONS = [];
844
962
  var DesignSystemCache = class DesignSystemCache {
845
963
  canonicalMap = /* @__PURE__ */ new Map();
964
+ deprecatedMap = /* @__PURE__ */ new Map();
846
965
  validitySet = /* @__PURE__ */ new Set();
847
966
  orderMap = /* @__PURE__ */ new Map();
848
- cssPropsMap = /* @__PURE__ */ new Map();
967
+ declIndex = null;
968
+ decodeDecls = null;
969
+ declMemo = /* @__PURE__ */ new Map();
970
+ propsMemo = /* @__PURE__ */ new Map();
971
+ partialSet = /* @__PURE__ */ new Set();
972
+ valueIdByText = null;
849
973
  variantOrderMap = /* @__PURE__ */ new Map();
974
+ variantFactsMap = /* @__PURE__ */ new Map();
850
975
  arbitraryEquivMap = /* @__PURE__ */ new Map();
851
976
  _validClasses = [];
852
977
  _knownPrefixes = null;
853
978
  _maxOrder = 0n;
854
979
  _prefix = "";
855
980
  componentSet = /* @__PURE__ */ new Set();
981
+ themeRefs = /* @__PURE__ */ new Map();
982
+ definedVarSet = /* @__PURE__ */ new Set();
856
983
  static fromPrecomputed(data) {
857
984
  const cache = new DesignSystemCache();
858
985
  cache._validClasses = data.validClasses;
859
986
  for (const cls of data.validClasses) cache.validitySet.add(cls);
860
987
  for (const [from, to] of Object.entries(data.canonical)) cache.canonicalMap.set(from, roundRemValue(to));
988
+ if (data.deprecated) for (const [from, to] of Object.entries(data.deprecated)) cache.deprecatedMap.set(from, to);
861
989
  for (const [cls, val] of Object.entries(data.order)) {
862
990
  const order = BigInt(val);
863
991
  cache.orderMap.set(cls, order);
864
992
  if (order > cache._maxOrder) cache._maxOrder = order;
865
993
  }
866
- for (const [cls, props] of Object.entries(data.cssProps)) cache.cssPropsMap.set(cls, props);
994
+ if (data.cssDeclarations) {
995
+ cache.declIndex = data.cssDeclarations;
996
+ cache.decodeDecls = createDeclarationDecoder(data.cssDeclarations);
997
+ for (const cls of data.cssDeclarations.partial ?? []) cache.partialSet.add(cls);
998
+ }
867
999
  if (data.variantOrder) for (const [name, index] of Object.entries(data.variantOrder)) cache.variantOrderMap.set(name, index);
1000
+ for (const [name, facts] of Object.entries(data.variantFacts ?? {})) cache.variantFactsMap.set(name, {
1001
+ pseudoElement: facts.p === 1,
1002
+ structural: facts.s === 1
1003
+ });
868
1004
  if (data.componentClasses) for (const cls of data.componentClasses) {
869
1005
  cache.validitySet.add(cls);
870
1006
  cache.componentSet.add(cls);
871
1007
  }
1008
+ for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
1009
+ if (data.themeRefs) for (const [name, refs] of Object.entries(data.themeRefs)) cache.themeRefs.set(name, refs);
872
1010
  cache._prefix = data.prefix ?? "";
873
1011
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
874
1012
  return cache;
@@ -902,6 +1040,24 @@ var DesignSystemCache = class DesignSystemCache {
902
1040
  return className;
903
1041
  }
904
1042
  /**
1043
+ * The v4 name of a class Tailwind renamed, or `null` if it isn't a renamed
1044
+ * spelling. Takes the BARE utility (no variants, no `!`) — the caller has
1045
+ * already split those off to rebuild the replacement around them.
1046
+ *
1047
+ * Derived by the precompute from what `canonicalizeCandidates` reports for the
1048
+ * v3 spellings, rather than from a map maintained by hand. Two rules read it:
1049
+ * `no-deprecated-classes`, which owns the diagnostic, and `enforce-canonical`,
1050
+ * which stays quiet about these so one class doesn't produce two identical
1051
+ * rewrites.
1052
+ */
1053
+ deprecatedReplacement(bareUtility) {
1054
+ return this.deprecatedMap.get(this.stripProjectPrefix(bareUtility)) ?? null;
1055
+ }
1056
+ /** Whether the precompute produced a deprecation map at all (older artifacts didn't). */
1057
+ get hasDeprecatedMap() {
1058
+ return this.deprecatedMap.size > 0;
1059
+ }
1060
+ /**
905
1061
  * Resolve a variant name to its priority in the CSS output order.
906
1062
  * Named variants use the precomputed map. Arbitrary variants use pattern-based heuristics
907
1063
  * to approximate their position relative to named variants.
@@ -960,6 +1116,23 @@ var DesignSystemCache = class DesignSystemCache {
960
1116
  }
961
1117
  return this._knownPrefixes;
962
1118
  }
1119
+ /**
1120
+ * Is this class name in the precomputed set VERBATIM?
1121
+ *
1122
+ * `isValid` is deliberately tolerant: it accepts anything shaped like a dynamic
1123
+ * value (`w-45`, `bg-red-5000`, `bg-red-500/foo`) because there used to be no
1124
+ * way to ask the design system at lint time. That tolerance is what let
1125
+ * `no-unknown-classes` accept classes Tailwind compiles to nothing. This is the
1126
+ * exact answer, so a rule can tell "known to produce CSS" from "shaped like it
1127
+ * might" and ask the design system about the difference.
1128
+ */
1129
+ isKnownClass(className) {
1130
+ return this.validitySet.has(this.stripProjectPrefix(className));
1131
+ }
1132
+ /** Variant names the design system reports, for suggesting a typo's neighbour. */
1133
+ variantNames() {
1134
+ return [...this.variantOrderMap.keys()];
1135
+ }
963
1136
  isValid(className) {
964
1137
  if (this.validitySet.has(className)) return true;
965
1138
  const utility = extractUtility(className);
@@ -1057,15 +1230,151 @@ var DesignSystemCache = class DesignSystemCache {
1057
1230
  const bucketSize = this._maxOrder + 1n;
1058
1231
  return BigInt(firstPriority) * 1000n * bucketSize + BigInt(subPriority) * bucketSize + baseOrder;
1059
1232
  }
1233
+ /**
1234
+ * Whether the stylesheet order for this exact class is known, as opposed to
1235
+ * approximated from a prefix sibling. Callers that name a winner must not do
1236
+ * so from an approximation: `w-[10px]` and `w-[20px]` both borrow the order of
1237
+ * the first `w-*` class, which says nothing about their real positions.
1238
+ */
1239
+ hasExactOrder(className) {
1240
+ const key = this.stripProjectPrefix(className);
1241
+ if (this.orderMap.get(key) != null) return true;
1242
+ const { bare, position } = splitImportant(key);
1243
+ return position !== null && this.orderMap.get(bare) != null;
1244
+ }
1060
1245
  getClassOrder(classes) {
1061
1246
  return classes.map((cls) => [cls, this.getOrder(cls)]);
1062
1247
  }
1248
+ /**
1249
+ * Every declaration the class emits, in emission order, not deduplicated.
1250
+ * Includes declarations on pseudo-elements and (for classes that style only
1251
+ * their descendants, like `space-x-*`) on descendants — each tagged with its
1252
+ * scope, so callers never mistake one box for another.
1253
+ */
1254
+ getCssDeclarations(className) {
1255
+ const key = this.stripProjectPrefix(className);
1256
+ const memo = this.declMemo.get(key);
1257
+ if (memo) return memo;
1258
+ const byClass = this.declIndex?.byClass;
1259
+ let packed = byClass?.[key];
1260
+ if (packed === void 0) {
1261
+ const { bare, position } = splitImportant(key);
1262
+ if (position) packed = byClass?.[bare];
1263
+ }
1264
+ const decoded = this.decodeDecls?.(packed) ?? EMPTY_DECLARATIONS;
1265
+ this.declMemo.set(key, decoded);
1266
+ return decoded;
1267
+ }
1268
+ /**
1269
+ * Adds declarations resolved at lint time (for classes the precompute never
1270
+ * saw — arbitrary values, slash modifiers, off-scale numbers) and memoizes
1271
+ * them like any other class.
1272
+ *
1273
+ * Values are interned against the SAME table the precompute filled, which is
1274
+ * the point: `p-4`'s value id has to be comparable with `p-[1rem]`'s, or the
1275
+ * two could never be told apart from a genuine conflict.
1276
+ */
1277
+ internDeclarations(className, raws, valueFacts) {
1278
+ const index = this.declIndex;
1279
+ if (!index) return EMPTY_DECLARATIONS;
1280
+ if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1281
+ const decls = [];
1282
+ let hasElement = false;
1283
+ let hasDescendant = false;
1284
+ let hasConditional = false;
1285
+ for (const [scopeToken, prop, value] of raws) {
1286
+ let valueId = this.valueIdByText.get(value);
1287
+ if (valueId === void 0) {
1288
+ valueId = index.values.length;
1289
+ index.values.push(value);
1290
+ this.valueIdByText.set(value, valueId);
1291
+ }
1292
+ const facts = valueFacts[value];
1293
+ const { scope, pseudo, conditional } = parseScopeToken(scopeToken);
1294
+ if (conditional) hasConditional = true;
1295
+ else if (scope === "element") hasElement = true;
1296
+ else if (scope === "descendant") hasDescendant = true;
1297
+ decls.push({
1298
+ prop,
1299
+ value,
1300
+ valueId,
1301
+ scope,
1302
+ pseudo,
1303
+ conditional,
1304
+ readsVars: facts?.p ?? [],
1305
+ readsFallbackVars: facts?.f ?? [],
1306
+ pureVarRead: facts?.u ?? false
1307
+ });
1308
+ }
1309
+ const key = this.stripProjectPrefix(className);
1310
+ if (hasConditional || hasElement && hasDescendant) this.partialSet.add(key);
1311
+ this.declMemo.set(key, decls);
1312
+ this.propsMemo.delete(key);
1313
+ return decls;
1314
+ }
1315
+ /**
1316
+ * True when the class emits CSS we deliberately did not model in full
1317
+ * (descendant rules alongside its own, or `@media`/`@supports` blocks). Such a
1318
+ * class must never be reported as redundant.
1319
+ */
1320
+ isPartial(className) {
1321
+ return this.partialSet.has(this.stripProjectPrefix(className));
1322
+ }
1323
+ /**
1324
+ * Property names the class declares on its OWN box, unconditionally.
1325
+ * Deduplicated, in emission order.
1326
+ */
1063
1327
  getCssProperties(className) {
1064
- const result = this.cssPropsMap.get(className);
1065
- if (result) return result;
1066
- const { bare, position } = splitImportant(className);
1067
- if (position) return this.cssPropsMap.get(bare) ?? [];
1068
- return [];
1328
+ const key = this.stripProjectPrefix(className);
1329
+ const memo = this.propsMemo.get(key);
1330
+ if (memo) return memo;
1331
+ const seen = /* @__PURE__ */ new Set();
1332
+ const props = [];
1333
+ for (const decl of this.getCssDeclarations(key)) {
1334
+ if (decl.scope !== "element" || decl.conditional) continue;
1335
+ if (seen.has(decl.prop)) continue;
1336
+ seen.add(decl.prop);
1337
+ props.push(decl.prop);
1338
+ }
1339
+ this.propsMemo.set(key, props);
1340
+ return props;
1341
+ }
1342
+ /** Strips the Tailwind project prefix (`tw:flex` → `flex`), if configured. */
1343
+ stripProjectPrefix(className) {
1344
+ if (this._prefix && className.startsWith(this._prefix + ":")) return className.slice(this._prefix.length + 1);
1345
+ return className;
1346
+ }
1347
+ /**
1348
+ * Whether `varName` resolves to `target` through theme indirection.
1349
+ *
1350
+ * `@theme inline { --color-primary: var(--primary) }` makes `bg-primary` and
1351
+ * `bg-(--primary)` the same declaration; a literal `--color-primary: oklch(…)`
1352
+ * makes them different colours. Only the theme table can tell those apart.
1353
+ */
1354
+ themeVarResolvesTo(varName, target, depth = 4) {
1355
+ if (varName === target) return true;
1356
+ if (depth <= 0) return false;
1357
+ const refs = this.themeRefs.get(varName);
1358
+ if (!refs) return false;
1359
+ return refs.some((ref) => this.themeVarResolvesTo(ref, target, depth - 1));
1360
+ }
1361
+ /** Whether the project defines this custom property (theme or plain CSS). */
1362
+ definesVar(varName) {
1363
+ return this.definedVarSet.has(varName) || this.themeRefs.has(varName);
1364
+ }
1365
+ /**
1366
+ * What the variant's selector does, derived from the design system. `undefined`
1367
+ * means "no information" — the caller falls back to its static predicates,
1368
+ * which is what keeps the variant rules working without an entry point.
1369
+ *
1370
+ * Compound variants (`group-hover/name`, `peer-checked`) resolve through the
1371
+ * same normalisation the priority lookup uses.
1372
+ */
1373
+ getVariantFacts(variant) {
1374
+ const direct = this.variantFactsMap.get(variant);
1375
+ if (direct) return direct;
1376
+ const slash = variant.indexOf("/");
1377
+ if (slash > 0) return this.variantFactsMap.get(variant.slice(0, slash));
1069
1378
  }
1070
1379
  getVariantPriority(variant) {
1071
1380
  return this.variantOrderMap.get(variant) ?? null;
@@ -1161,6 +1470,29 @@ function safeGetDS(getDS, context, node) {
1161
1470
  throw err;
1162
1471
  }
1163
1472
  }
1473
+ /**
1474
+ * `safeGetDS`'s quiet sibling, for the DS-OPTIONAL rules.
1475
+ *
1476
+ * A handful of rules work without a design system — their static fallback is
1477
+ * itself deterministic (`consistent-variant-order`'s variant table,
1478
+ * `no-dark-without-light`'s prefix grouping) — and an entry point only makes
1479
+ * them more accurate. Those rules must never emit `designSystemUnavailable`:
1480
+ * they were usable with no configuration before the DS lookup existed and have
1481
+ * to stay that way, or adding the lookup would break every project that runs
1482
+ * them without a CSS entry point.
1483
+ *
1484
+ * So: returns the load result, or `null` when the design system is unavailable
1485
+ * for a reason the plugin knows about. Non-fatal errors still propagate, since
1486
+ * those are bugs rather than missing configuration.
1487
+ */
1488
+ function softGetDS(getDS) {
1489
+ try {
1490
+ return getDS();
1491
+ } catch (err) {
1492
+ if (isFatalError(err)) return null;
1493
+ throw err;
1494
+ }
1495
+ }
1164
1496
  //#endregion
1165
1497
  //#region src/design-system/tailwind-node.ts
1166
1498
  /**
@@ -1228,6 +1560,181 @@ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPat
1228
1560
  *
1229
1561
  * For arbitrary values (bg-[#123]) that aren't in the class list, we use heuristics.
1230
1562
  */
1563
+ /**
1564
+ * Declaration extractor, as source text, interpolated into PRECOMPUTE_SCRIPT.
1565
+ *
1566
+ * It lives in its own constant for two reasons: the benchmark in
1567
+ * `tests/benchmarks/precompute-phases.test.ts` used to keep a hand-copied
1568
+ * duplicate of the extractor that silently drifted from the real one, and it is
1569
+ * interpolated (not concatenated at runtime), so its text still feeds the
1570
+ * `CACHE_KEY` md5 and any edit here invalidates the disk cache automatically.
1571
+ *
1572
+ * Exports (in the worker scope): `walkDeclarations`, `scanVarReads`,
1573
+ * `isPureVarRead`.
1574
+ */
1575
+ const DECL_EXTRACTOR_SOURCE = `
1576
+ // One declaration per line, '{' closing the selector line, '}' alone — the
1577
+ // shape candidatesToCss pretty-prints. Verified against every fixture: zero
1578
+ // unparsed declaration lines.
1579
+ const DECL_RE = /^([\\w-]+)\\s*:\\s*(.*?)\\s*;?$/;
1580
+
1581
+ // Class-name characters, plus '\\\\' because escaped selectors continue the name
1582
+ // ('.w-1\\\\/2' must not be matched by the token '.w-1').
1583
+ function isNameChar(c) {
1584
+ if (c === undefined) return false;
1585
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
1586
+ || c === '-' || c === '_' || c === '\\\\';
1587
+ }
1588
+
1589
+ // Classify what follows the class token inside a selector:
1590
+ // '::name' → the declaration styles that pseudo-element's box
1591
+ // '>' → a combinator intervenes, so the class is not the subject
1592
+ // '' → the element's own box (pseudo-CLASSES land here)
1593
+ // The combinator scan is paren-aware: tw-animate-css emits
1594
+ // '&:where(:dir(ltr), [dir="ltr"], [dir="ltr"]*)', whose spaces and commas sit
1595
+ // inside :where(). A naive "is there a space" test would mislabel 92 rules as
1596
+ // descendant and silently stop reporting on the slide-in-* family.
1597
+ function classifyAfter(after) {
1598
+ if (after.startsWith('::')) {
1599
+ let e = 2;
1600
+ while (e < after.length && isNameChar(after[e]) && after[e] !== '\\\\') e++;
1601
+ return after.slice(0, e);
1602
+ }
1603
+ let depth = 0;
1604
+ for (let x = 0; x < after.length; x++) {
1605
+ const ch = after[x];
1606
+ if (ch === '(') depth++;
1607
+ else if (ch === ')') { if (depth > 0) depth--; }
1608
+ else if (depth === 0) {
1609
+ if (ch === '>' || ch === '+' || ch === '~' || ch === ' ' || ch === '\\t') return '>';
1610
+ if (ch === ',') break;
1611
+ }
1612
+ }
1613
+ return '';
1614
+ }
1615
+
1616
+ // Find the token as a COMPLETE compound ('.rounded' must not match inside
1617
+ // '.rounded-lg'). Returns null when the token is absent, which the caller
1618
+ // treats as element scope: that is today's behaviour for selectors we cannot
1619
+ // attribute, and widening it to 'descendant' would blind the rule.
1620
+ function classifyTopLevel(sel, token) {
1621
+ let from = 0;
1622
+ for (;;) {
1623
+ const i = sel.indexOf(token, from);
1624
+ if (i < 0) return null;
1625
+ if (!isNameChar(sel[i + token.length])) return classifyAfter(sel.slice(i + token.length));
1626
+ from = i + 1;
1627
+ }
1628
+ }
1629
+
1630
+ // Nested block (CSS nesting). A selector that does not start with '&' is
1631
+ // implicitly '& <sel>', i.e. a descendant — that is what keeps prose's
1632
+ // ':where(p)' rules out of the element's declaration set.
1633
+ function classifyNested(sel) {
1634
+ if (sel[0] !== '&') return '>';
1635
+ return classifyAfter(sel.slice(1));
1636
+ }
1637
+
1638
+ // Tailwind emits the same value two ways: 'slide-in-from-left' declares
1639
+ // '-100%' and 'slide-in-from-left-full' declares 'calc(1 * -100%)'. Same
1640
+ // computed value, different text — and a text comparison would call that a
1641
+ // conflict. Only a SINGLE numeric term is unwrapped, so 'calc(1 * 2px + 3px)'
1642
+ // (where the multiplication is part of a larger expression) is left alone.
1643
+ const CALC_ONE_LEFT = /^calc\\(\\s*1\\s*\\*\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+)[a-z%]*)\\s*\\)$/;
1644
+ const CALC_ONE_RIGHT = /^calc\\(\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+)[a-z%]*)\\s*\\*\\s*1\\s*\\)$/;
1645
+ function normalizeDeclValue(value) {
1646
+ const trimmed = value.trim();
1647
+ const m = CALC_ONE_LEFT.exec(trimmed) || CALC_ONE_RIGHT.exec(trimmed);
1648
+ return m ? m[1] : trimmed;
1649
+ }
1650
+
1651
+ function walkDeclarations(cssText, className, sink) {
1652
+ const token = '.' + className.replace(/([^\\w-])/g, '\\\\$1');
1653
+ const stack = [];
1654
+ let skipDepth = 0;
1655
+ const lines = cssText.split('\\n');
1656
+ for (let li = 0; li < lines.length; li++) {
1657
+ const line = lines[li].trim();
1658
+ if (line === '') continue;
1659
+ if (line === '}') { if (skipDepth > 0) skipDepth--; else stack.pop(); continue; }
1660
+ if (line.charCodeAt(line.length - 1) === 123 /* { */) {
1661
+ if (skipDepth > 0) { skipDepth++; continue; }
1662
+ const sel = line.slice(0, -1).trim();
1663
+ // @property blocks describe a variable, they don't style anything: skip
1664
+ // the whole block (that also drops syntax/inherits/initial-value).
1665
+ if (sel.startsWith('@property')) { skipDepth++; continue; }
1666
+ stack.push(sel);
1667
+ continue;
1668
+ }
1669
+ if (skipDepth > 0) continue;
1670
+ const m = DECL_RE.exec(line);
1671
+ if (!m) continue;
1672
+ // Resolve the scope from the open block stack.
1673
+ let conditional = false, scope = '', seenSubject = false;
1674
+ for (let k = 0; k < stack.length; k++) {
1675
+ const sel = stack[k];
1676
+ if (sel.charCodeAt(0) === 64 /* @ */) { conditional = true; continue; }
1677
+ if (!seenSubject) {
1678
+ seenSubject = true;
1679
+ const top = classifyTopLevel(sel, token);
1680
+ scope = top === null ? '' : top;
1681
+ } else {
1682
+ const inner = classifyNested(sel);
1683
+ if (inner === '>') scope = '>';
1684
+ else if (inner !== '' && scope !== '>') scope = inner;
1685
+ }
1686
+ }
1687
+ sink((conditional ? '@' : '') + scope, m[1], normalizeDeclValue(m[2]));
1688
+ }
1689
+ }
1690
+
1691
+ // Custom properties a value reads. 'primary' means "not inside another var()'s
1692
+ // fallback" — NOT "at paren depth 0": the vars inside linear-gradient(...) are
1693
+ // primary reads. Fallback reads are reported separately because a fallback is a
1694
+ // last resort, not the composition channel.
1695
+ function scanVarReads(value) {
1696
+ const primary = [], fallback = [];
1697
+ function walk(s, inFallback) {
1698
+ let i = 0;
1699
+ for (;;) {
1700
+ const at = s.indexOf('var(', i);
1701
+ if (at < 0) break;
1702
+ let d = 1, j = at + 4;
1703
+ while (j < s.length && d > 0) { if (s[j] === '(') d++; else if (s[j] === ')') d--; j++; }
1704
+ const inner = s.slice(at + 4, j - 1);
1705
+ let c = 0, comma = -1;
1706
+ for (let x = 0; x < inner.length; x++) {
1707
+ if (inner[x] === '(') c++;
1708
+ else if (inner[x] === ')') c--;
1709
+ else if (inner[x] === ',' && c === 0) { comma = x; break; }
1710
+ }
1711
+ const name = (comma < 0 ? inner : inner.slice(0, comma)).trim();
1712
+ if (name.startsWith('--')) (inFallback ? fallback : primary).push(name);
1713
+ if (comma >= 0) walk(inner.slice(comma + 1), true);
1714
+ i = j;
1715
+ }
1716
+ }
1717
+ walk(value, false);
1718
+ return [[...new Set(primary)], [...new Set(fallback)]];
1719
+ }
1720
+
1721
+ // A value is a pure var() read when, with every balanced var(...) group removed,
1722
+ // only separators remain. 'var(--tw-scale-x) var(--tw-scale-y)' is pure;
1723
+ // 'translateZ(0) var(--tw-rotate-x,)' is not (it contributes a value of its own).
1724
+ function isPureVarRead(value) {
1725
+ let rest = '', i = 0;
1726
+ while (i < value.length) {
1727
+ if (value.startsWith('var(', i)) {
1728
+ let d = 1, j = i + 4;
1729
+ while (j < value.length && d > 0) { if (value[j] === '(') d++; else if (value[j] === ')') d--; j++; }
1730
+ i = j;
1731
+ continue;
1732
+ }
1733
+ rest += value[i++];
1734
+ }
1735
+ return /^[\\s,]*$/.test(rest);
1736
+ }
1737
+ `;
1231
1738
  const PRECOMPUTE_SCRIPT = `
1232
1739
  // Runs as a worker_thread (NOT a forked child process). Inputs arrive via
1233
1740
  // workerData; the result is written straight to the disk cache and completion
@@ -1337,6 +1844,8 @@ function extractComponentClasses(cssPath, baseDir) {
1337
1844
  return [...new Set(result)];
1338
1845
  }
1339
1846
 
1847
+ ${DECL_EXTRACTOR_SOURCE}
1848
+
1340
1849
  async function main() {
1341
1850
  const cssPath = WD_CSS_PATH;
1342
1851
  const css = readFileSync(cssPath, 'utf-8');
@@ -1362,10 +1871,21 @@ async function main() {
1362
1871
 
1363
1872
  // Validity: which classes produce CSS. Validate the prefixed form, but keep
1364
1873
  // cssResults aligned positionally to the unprefixed classNames so the later
1365
- // cssProps / arbitraryEquivalents phases keep indexing by position.
1874
+ // declarations / arbitraryEquivalents phases keep indexing by position.
1366
1875
  const cssResults = ds.candidatesToCss(classNames.map(pfx));
1367
1876
  const validClasses = classNames.filter((_, i) => cssResults[i] != null);
1368
1877
 
1878
+ // className → its emitted CSS, for the declarations phase. Every phase that
1879
+ // validates extra candidates feeds this map, so classes recovered outside
1880
+ // getClassList() (bare utilities like \`rounded\`, negatives like \`-col-1\`,
1881
+ // legacy v3 spellings) get declarations too. They used to be pushed into
1882
+ // validClasses with their CSS thrown away, which left ~300 valid classes
1883
+ // invisible to no-conflicting-classes (\`rounded rounded-lg\` never reported).
1884
+ const declCss = {};
1885
+ for (let i = 0; i < classNames.length; i++) {
1886
+ if (cssResults[i] != null) declCss[classNames[i]] = cssResults[i];
1887
+ }
1888
+
1369
1889
  // Expand: validate extra candidates not in getClassList() but valid in v4
1370
1890
  const validSet = new Set(validClasses);
1371
1891
  const knownPrefixes = new Set();
@@ -1383,7 +1903,7 @@ async function main() {
1383
1903
  // utilities; their functional bases enumerate values but omit \`none\`.
1384
1904
  // - \`max-w-screen\` (\`max-width: 100vw\`).
1385
1905
  // Validated via candidatesToCss (self-prunes on any Tailwind version that doesn't
1386
- // emit them) and their CSS is captured so the cssProps phase below treats them
1906
+ // emit them) and their CSS is captured so the declarations phase below treats them
1387
1907
  // exactly like their getClassList siblings — otherwise no-conflicting-classes
1388
1908
  // would flag \`@container @container-normal\` but silently accept
1389
1909
  // \`@container @container-size\`. Named forms (\`@container-size/main\`) are covered
@@ -1394,14 +1914,13 @@ async function main() {
1394
1914
  'backdrop-filter-none',
1395
1915
  'max-w-screen',
1396
1916
  ].filter((c) => !validSet.has(c));
1397
- const staticExtraCss = {};
1398
1917
  if (staticExtras.length > 0) {
1399
1918
  const staticResults = ds.candidatesToCss(staticExtras.map(pfx));
1400
1919
  for (let i = 0; i < staticExtras.length; i++) {
1401
1920
  if (staticResults[i] != null) {
1402
1921
  validClasses.push(staticExtras[i]);
1403
1922
  validSet.add(staticExtras[i]);
1404
- staticExtraCss[staticExtras[i]] = staticResults[i];
1923
+ declCss[staticExtras[i]] = staticResults[i];
1405
1924
  }
1406
1925
  }
1407
1926
  }
@@ -1423,6 +1942,7 @@ async function main() {
1423
1942
  if (extraResults[i] != null) {
1424
1943
  validClasses.push(extraCandidates[i]);
1425
1944
  validSet.add(extraCandidates[i]);
1945
+ declCss[extraCandidates[i]] = extraResults[i];
1426
1946
  }
1427
1947
  }
1428
1948
  }
@@ -1444,6 +1964,7 @@ async function main() {
1444
1964
  if (negResults[i] != null && !validSet.has(negativeProbes[i])) {
1445
1965
  validClasses.push(negativeProbes[i]);
1446
1966
  validSet.add(negativeProbes[i]);
1967
+ declCss[negativeProbes[i]] = negResults[i];
1447
1968
  }
1448
1969
  }
1449
1970
  }
@@ -1481,11 +2002,17 @@ async function main() {
1481
2002
  // their v4 equivalent, so we feed them in explicitly. Without this pass,
1482
2003
  // classes like \`break-words\` would be invisible to enforce-canonical
1483
2004
  // (issue #16).
1484
- // - Fixed renames mirror the internal v3->v4 map in tailwindcss/canonicalize.
1485
- // - Pattern renames (start-* -> inset-s-*, end-* -> inset-e-*) are derived
1486
- // from the inset-{s,e}-* utilities present in validClasses so we cover
1487
- // every numeric/named value the design system exposes.
1488
- const legacyCandidates = [
2005
+ //
2006
+ // Two kinds, and the difference is what \`deprecated\` records:
2007
+ // - RENAMES: a v3 spelling of a utility v4 calls something else. Mirrors the
2008
+ // internal v3->v4 map in tailwindcss/canonicalize. These ARE deprecated, and
2009
+ // no-deprecated-classes owns them.
2010
+ // - Pattern renames (start-* -> inset-s-*, end-* -> inset-e-*), derived from
2011
+ // the inset-{s,e}-* utilities in validClasses so every numeric/named value is
2012
+ // covered. These are NOT deprecated: \`start-2\` is current Tailwind (it is
2013
+ // what the docs use), it just isn't the canonical spelling. Calling it
2014
+ // deprecated would be a lie, so only enforce-canonical speaks about it.
2015
+ const v3Renames = [
1489
2016
  'order-none',
1490
2017
  'break-words',
1491
2018
  'overflow-ellipsis',
@@ -1500,12 +2027,15 @@ async function main() {
1500
2027
  'bg-left-top', 'bg-right-top', 'bg-left-bottom', 'bg-right-bottom',
1501
2028
  'object-left-top', 'object-right-top', 'object-left-bottom', 'object-right-bottom',
1502
2029
  ];
2030
+ const renameSet = new Set(v3Renames);
2031
+ const legacyCandidates = [...v3Renames];
1503
2032
  for (const cls of validClasses) {
1504
2033
  if (cls.startsWith('inset-s-')) legacyCandidates.push('start-' + cls.slice(8));
1505
2034
  else if (cls.startsWith('-inset-s-')) legacyCandidates.push('-start-' + cls.slice(9));
1506
2035
  else if (cls.startsWith('inset-e-')) legacyCandidates.push('end-' + cls.slice(8));
1507
2036
  else if (cls.startsWith('-inset-e-')) legacyCandidates.push('-end-' + cls.slice(9));
1508
2037
  }
2038
+ const deprecated = {};
1509
2039
  const legacyToProcess = legacyCandidates.filter(cls => !validSet.has(cls));
1510
2040
  if (legacyToProcess.length > 0) {
1511
2041
  const legacyCssResults = ds.candidatesToCss(legacyToProcess.map(pfx));
@@ -1516,10 +2046,15 @@ async function main() {
1516
2046
  const canon = result[0] ? unpfx(result[0]) : null;
1517
2047
  if (canon && canon !== cls) {
1518
2048
  canonical[cls] = canon;
2049
+ // Only a v3 rename that this Tailwind still compiles AND still renames.
2050
+ // A release that drops either of those drops the entry, so the rule can
2051
+ // never suggest a replacement for a class that no longer exists.
2052
+ if (renameSet.has(cls)) deprecated[cls] = canon;
1519
2053
  }
1520
2054
  // Mark as valid so no-unknown-classes doesn't flag legacy spellings.
1521
2055
  validClasses.push(cls);
1522
2056
  validSet.add(cls);
2057
+ declCss[cls] = legacyCssResults[i];
1523
2058
  }
1524
2059
  }
1525
2060
 
@@ -1534,108 +2069,126 @@ async function main() {
1534
2069
  if (val !== null) order[unpfx(name)] = val.toString();
1535
2070
  }
1536
2071
 
1537
- // CSS properties per class — extract only from the ROOT selector, not descendant selectors.
1538
- // Plugin classes like "prose" generate CSS for both the root element (.prose { color: ...; })
1539
- // and descendant selectors (:where(.prose pre) { overflow-x: auto; }).
1540
- // Only root-level properties should be used for conflict detection.
1541
- const cssProps = {};
1542
- const atPropertyDescriptors = new Set(['syntax', 'inherits', 'initial-value']);
2072
+ // CSS declarations per class, interned. The walker, the scope grammar and the
2073
+ // var-read scanner live in DECL_EXTRACTOR_SOURCE above (shared with the
2074
+ // benchmark so the two can no longer drift).
2075
+ const scopeIds = new Map([['', 0]]);
2076
+ const scopeTable = [''];
2077
+ const propIds = new Map();
2078
+ const propTable = [];
2079
+ const valueIds = new Map();
2080
+ const valueTable = [];
2081
+ const declFreq = new Map();
2082
+ const perClass = {};
2083
+ const partial = [];
1543
2084
 
1544
- function extractRootCssProps(cssText, className) {
1545
- const rootProps = [];
1546
- const allProps = [];
1547
- // CSS-escape special chars in class name for selector matching
1548
- const escapedName = className.replace(/([^\\w-])/g, '\\\\$1');
1549
- const classSelector = '.' + escapedName;
1550
- const rawSelector = '.' + className;
1551
- const propRe = /^\\s+([\\w-]+)\\s*:/gm;
1552
-
1553
- function isRoot(sel) {
1554
- for (const s of [classSelector, rawSelector]) {
1555
- if (sel === s) return true;
1556
- if (sel.length > s.length && sel.startsWith(s) && sel[s.length] === ':') return true;
1557
- }
1558
- return false;
1559
- }
2085
+ for (const cls in declCss) {
2086
+ // Collect first, intern after, so the descendant-scope decision below can
2087
+ // look at the whole class.
2088
+ const raw = [];
2089
+ let hasElement = false, hasDescendant = false, hasConditional = false;
2090
+ walkDeclarations(declCss[cls], pfx(cls), (scopeTok, prop, value) => {
2091
+ raw.push([scopeTok, prop, value]);
2092
+ const conditional = scopeTok.charCodeAt(0) === 64;
2093
+ const body = conditional ? scopeTok.slice(1) : scopeTok;
2094
+ if (conditional) hasConditional = true;
2095
+ if (body === '') hasElement = true;
2096
+ else if (body === '>') hasDescendant = true;
2097
+ });
1560
2098
 
1561
- // Extract only top-level declarations from a block body (skip nested blocks).
1562
- // For CSS nesting like .prose { color: ...; :where(a) { color: ...; } },
1563
- // only extracts "color" from the top level, not from the nested :where(a) block.
1564
- function extractTopLevelProps(body) {
1565
- const props = [];
1566
- let depth = 0;
1567
- let lineStart = 0;
1568
- for (let i = 0; i <= body.length; i++) {
1569
- if (i === body.length || body[i] === '\\n') {
1570
- if (depth === 0) {
1571
- const line = body.slice(lineStart, i);
1572
- const m = /^\\s+([\\w-]+)\\s*:/.exec(line);
1573
- if (m && !atPropertyDescriptors.has(m[1])) props.push(m[1]);
1574
- }
1575
- lineStart = i + 1;
1576
- } else if (body[i] === '{') {
1577
- depth++;
1578
- } else if (body[i] === '}') {
1579
- depth--;
1580
- }
1581
- }
1582
- return props;
1583
- }
2099
+ // A class whose CSS styles BOTH itself and its descendants (\`prose\` and its
2100
+ // dozens of \`:where(p)\` rules) only advertises what it puts on the element:
2101
+ // comparing descendant declarations would turn every \`prose prose-sm\` into
2102
+ // ~40 conflicts. Classes that style ONLY descendants (\`space-x-*\`,
2103
+ // \`divide-*\`) keep them — that is what makes \`space-x-4 space-x-2\` a
2104
+ // conflict while \`ms-2 space-x-4\` is not. Pseudo-elements are always kept:
2105
+ // they are a distinct box and there are few of them.
2106
+ const dropDescendants = hasElement && hasDescendant;
2107
+ // Anything we deliberately did not model. A class in here must never be
2108
+ // called redundant: \`container\` looks like a plain \`width: 100%\` because its
2109
+ // breakpoint \`max-width\`es live in @media, so "remove it" would be wrong.
2110
+ if (dropDescendants || hasConditional) partial.push(cls);
1584
2111
 
1585
- function processText(text) {
1586
- let i = 0;
1587
- while (i < text.length) {
1588
- while (i < text.length && /\\s/.test(text[i])) i++;
1589
- if (i >= text.length) break;
1590
- const braceIdx = text.indexOf('{', i);
1591
- if (braceIdx === -1) break;
1592
- const selector = text.slice(i, braceIdx).trim();
1593
- let depth = 1, j = braceIdx + 1;
1594
- while (j < text.length && depth > 0) {
1595
- if (text[j] === '{') depth++;
1596
- if (text[j] === '}') depth--;
1597
- j++;
1598
- }
1599
- const body = text.slice(braceIdx + 1, j - 1);
1600
- if (selector.startsWith('@media') || selector.startsWith('@supports') || selector.startsWith('@layer')) {
1601
- processText(body);
1602
- } else if (!selector.startsWith('@')) {
1603
- propRe.lastIndex = 0;
1604
- let m;
1605
- while ((m = propRe.exec(body)) !== null) {
1606
- if (!atPropertyDescriptors.has(m[1])) allProps.push(m[1]);
1607
- }
1608
- if (isRoot(selector)) rootProps.push(...extractTopLevelProps(body));
1609
- }
1610
- i = j;
1611
- }
2112
+ const keys = [];
2113
+ for (let r = 0; r < raw.length; r++) {
2114
+ const scopeTok = raw[r][0], prop = raw[r][1], value = raw[r][2];
2115
+ const body = scopeTok.charCodeAt(0) === 64 ? scopeTok.slice(1) : scopeTok;
2116
+ if (dropDescendants && body === '>') continue;
2117
+ let s = scopeIds.get(scopeTok);
2118
+ if (s === undefined) { s = scopeTable.length; scopeTable.push(scopeTok); scopeIds.set(scopeTok, s); }
2119
+ let p = propIds.get(prop);
2120
+ if (p === undefined) { p = propTable.length; propTable.push(prop); propIds.set(prop, p); }
2121
+ let v = valueIds.get(value);
2122
+ if (v === undefined) { v = valueTable.length; valueTable.push(value); valueIds.set(value, v); }
2123
+ const key = s + '|' + p + '|' + v;
2124
+ declFreq.set(key, (declFreq.get(key) || 0) + 1);
2125
+ keys.push(key);
1612
2126
  }
1613
-
1614
- processText(cssText);
1615
- // Use root-only properties when found; fall back to all for classes with
1616
- // escaped selectors or single-block output where root matching may miss.
1617
- const result = rootProps.length > 0 ? rootProps : allProps;
1618
- return [...new Set(result)];
2127
+ // Kept in emission order and NOT deduplicated: a class that declares the
2128
+ // same property twice (bg-linear-to-r does, once plainly and once inside
2129
+ // @supports) keeps both. Within one block the LAST one wins, which is CSS
2130
+ // semantics — the consumer applies that, the data keeps everything.
2131
+ if (keys.length > 0) perClass[cls] = keys;
1619
2132
  }
1620
2133
 
1621
- for (let i = 0; i < classNames.length; i++) {
1622
- if (cssResults[i]) {
1623
- // Match against the prefixed selector (the CSS emits \`.tw\\:flex\`), but
1624
- // store under the unprefixed key. extractRootCssProps CSS-escapes the ':'.
1625
- const props = extractRootCssProps(cssResults[i], pfx(classNames[i]));
1626
- if (props.length > 0) cssProps[classNames[i]] = props;
2134
+ // Hottest declarations get the shortest base36 ids. Ties break on the key so
2135
+ // the artifact stays byte-reproducible for a given design system.
2136
+ const sortedKeys = [...declFreq.keys()].sort((a, b) => {
2137
+ const d = declFreq.get(b) - declFreq.get(a);
2138
+ return d !== 0 ? d : (a < b ? -1 : a > b ? 1 : 0);
2139
+ });
2140
+ const declIds = new Map();
2141
+ const table = [];
2142
+ for (let i = 0; i < sortedKeys.length; i++) {
2143
+ declIds.set(sortedKeys[i], i);
2144
+ const parts = sortedKeys[i].split('|');
2145
+ table.push(
2146
+ Number(parts[0]).toString(36) + '|' + Number(parts[1]).toString(36) + '|' + Number(parts[2]).toString(36)
2147
+ );
2148
+ }
2149
+ const byClass = {};
2150
+ for (const cls in perClass) {
2151
+ const ids = perClass[cls];
2152
+ let packed = '';
2153
+ for (let i = 0; i < ids.length; i++) {
2154
+ packed += (i === 0 ? '' : ',') + declIds.get(ids[i]).toString(36);
1627
2155
  }
2156
+ byClass[cls] = packed;
1628
2157
  }
1629
2158
 
1630
- // cssProps for the curated static extras (#37) so they participate in conflict
1631
- // detection exactly like their getClassList siblings (e.g. \`@container-size\` and
1632
- // \`@container\` both declaring \`container-type\`).
1633
- for (const name in staticExtraCss) {
1634
- const props = extractRootCssProps(staticExtraCss[name], pfx(name));
1635
- if (props.length > 0) cssProps[name] = props;
2159
+ // Which variables a value reads is a property of the VALUE, so it is computed
2160
+ // once per interned value (~2.7k) instead of once per declaration (~55k).
2161
+ const varIds = new Map();
2162
+ const varTable = [];
2163
+ const valueVars = {};
2164
+ const valueFallbackVars = {};
2165
+ const pureValues = [];
2166
+ function internVar(name) {
2167
+ let id = varIds.get(name);
2168
+ if (id === undefined) { id = varTable.length; varTable.push(name); varIds.set(name, id); }
2169
+ return id;
2170
+ }
2171
+ for (let v = 0; v < valueTable.length; v++) {
2172
+ const reads = scanVarReads(valueTable[v]);
2173
+ if (reads[0].length > 0) valueVars[v] = reads[0].map(internVar);
2174
+ if (reads[1].length > 0) valueFallbackVars[v] = reads[1].map(internVar);
2175
+ if (isPureVarRead(valueTable[v])) pureValues.push(v);
1636
2176
  }
1637
2177
 
1638
- // Variant ordering from the design system
2178
+ const cssDeclarations = {
2179
+ partial,
2180
+ scopes: scopeTable,
2181
+ props: propTable,
2182
+ values: valueTable,
2183
+ vars: varTable,
2184
+ valueVars,
2185
+ valueFallbackVars,
2186
+ pureValues,
2187
+ table,
2188
+ byClass,
2189
+ };
2190
+
2191
+ // Variant ordering from the design system.
1639
2192
  const variantOrder = {};
1640
2193
  const variants = ds.getVariants();
1641
2194
  for (let i = 0; i < variants.length; i++) {
@@ -1644,6 +2197,54 @@ async function main() {
1644
2197
  }
1645
2198
  }
1646
2199
 
2200
+ // What each variant DOES to the selector, so the variant rules can stop
2201
+ // guessing from a list of names — the list cannot know a project's own
2202
+ // \`@custom-variant\`.
2203
+ //
2204
+ // Derived by compiling a probe utility and reading the emitted selector, NOT
2205
+ // from \`variant.selectors()\`: that returns '&'-relative strings, comes back
2206
+ // empty for \`before\`/\`after\`, and reports \`group\`/\`peer\` as arbitrary with no
2207
+ // selectors at all. Compiling is the same mechanism the declaration extractor
2208
+ // already trusts, and \`walkDeclarations\` already classifies exactly what we
2209
+ // need — the scope of each emitted declaration.
2210
+ //
2211
+ // Functional variants (\`group-*\`, \`peer-*\`, \`data-*\`, \`nth-*\`) are skipped:
2212
+ // probing them would need a value, and none of them retargets the selector.
2213
+ // Measured in Tailwind 4.3.3: \`group-hover\`/\`peer-checked\` compile to
2214
+ // \`&:is(:where(.group):hover *)\` — an \`:is()\` on the element itself — so two of
2215
+ // them in either order produce equivalent selectors and neither is a
2216
+ // reordering barrier.
2217
+ const variantFacts = {};
2218
+ const probeNames = [];
2219
+ for (let i = 0; i < variants.length; i++) {
2220
+ const v = variants[i];
2221
+ if (v.isArbitrary) continue;
2222
+ if (v.values && v.values.length > 0) continue;
2223
+ probeNames.push(v.name);
2224
+ }
2225
+ if (probeNames.length > 0) {
2226
+ const probeClasses = probeNames.map((n) => n + ':flex');
2227
+ const probeCss = ds.candidatesToCss(probeClasses.map(pfx));
2228
+ for (let i = 0; i < probeNames.length; i++) {
2229
+ if (!probeCss[i]) continue;
2230
+ let pseudo = false, structural = false;
2231
+ walkDeclarations(probeCss[i], pfx(probeClasses[i]), (scopeTok) => {
2232
+ const body = scopeTok.charCodeAt(0) === 64 ? scopeTok.slice(1) : scopeTok;
2233
+ if (body.startsWith('::')) pseudo = true;
2234
+ else if (body === '>') structural = true;
2235
+ });
2236
+ // A variant that styles a generated box is a pseudo-element variant even
2237
+ // when it ALSO reaches descendants' boxes (\`marker\` emits both
2238
+ // \`& ::marker\` and \`&::marker\`): it belongs innermost, not treated as a
2239
+ // reordering barrier.
2240
+ if (pseudo) {
2241
+ variantFacts[probeNames[i]] = { p: 1 };
2242
+ } else if (structural) {
2243
+ variantFacts[probeNames[i]] = { s: 1 };
2244
+ }
2245
+ }
2246
+ }
2247
+
1647
2248
  // Component classes from @layer components
1648
2249
  const componentClasses = extractComponentClasses(cssPath, base);
1649
2250
 
@@ -1704,7 +2305,28 @@ async function main() {
1704
2305
  }
1705
2306
  }
1706
2307
 
1707
- const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents, prefix });
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) || [])];
2317
+
2318
+ const themeRefs = {};
2319
+ if (ds.theme && typeof ds.theme.entries === 'function') {
2320
+ for (const [name, entry] of ds.theme.entries()) {
2321
+ const value = entry && typeof entry.value === 'string' ? entry.value : '';
2322
+ if (!value.includes('var(')) continue;
2323
+ const reads = scanVarReads(value);
2324
+ const all = [...new Set([...reads[0], ...reads[1]])];
2325
+ if (all.length > 0) themeRefs[name] = all;
2326
+ }
2327
+ }
2328
+
2329
+ const json = JSON.stringify({ validClasses, canonical, deprecated, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
1708
2330
  // Atomic write: write to a unique temp path then rename, so a peer isolate
1709
2331
  // busy-waiting on the cache file never observes a half-written JSON.
1710
2332
  writeFileSync(WD_TMP_PATH, json);
@@ -1789,6 +2411,19 @@ function getContentCachePath(contentHash) {
1789
2411
  return (0, node_path.join)(CACHE_DIR, `${contentHash}.json`);
1790
2412
  }
1791
2413
  /**
2414
+ * The on-disk cache artifacts for a CSS entry point: the precomputed `json`
2415
+ * and the coordination `lock`. Exposed for tests that exercise the
2416
+ * cold-cache precompute coordination (issue #24).
2417
+ */
2418
+ function cacheArtifactPaths(cssPath) {
2419
+ const resolved = (0, node_path.resolve)(cssPath);
2420
+ const hash = computeContentHash(hashableContent(resolved, (0, node_fs.readFileSync)(resolved, "utf-8")));
2421
+ return {
2422
+ json: getContentCachePath(hash),
2423
+ lock: (0, node_path.join)(CACHE_DIR, `${hash}.lock`)
2424
+ };
2425
+ }
2426
+ /**
1792
2427
  * Minimal shape check for a cache payload. Guards against (a) a poisoned file
1793
2428
  * planted by a local attacker and (b) a corrupt/half-written or version-skewed
1794
2429
  * file. A `{}` that is valid JSON but missing fields would otherwise blow up
@@ -1800,7 +2435,7 @@ function isPrecomputedData(data) {
1800
2435
  if (typeof data !== "object" || data === null) return false;
1801
2436
  const d = data;
1802
2437
  const isObject = (v) => typeof v === "object" && v !== null;
1803
- return Array.isArray(d.validClasses) && Array.isArray(d.componentClasses) && typeof d.prefix === "string" && isObject(d.canonical) && isObject(d.order) && isObject(d.cssProps) && isObject(d.variantOrder) && isObject(d.arbitraryEquivalents);
2438
+ return Array.isArray(d.validClasses) && Array.isArray(d.componentClasses) && typeof d.prefix === "string" && isObject(d.canonical) && isObject(d.order) && isCssDeclarationIndex(d.cssDeclarations) && isObject(d.variantOrder) && isObject(d.arbitraryEquivalents);
1804
2439
  }
1805
2440
  function tryReadCache(cachePath) {
1806
2441
  const raw = tryReadRawCache(cachePath);
@@ -1833,7 +2468,7 @@ function lockAgeMs(lockPath) {
1833
2468
  return Number.POSITIVE_INFINITY;
1834
2469
  }
1835
2470
  }
1836
- function tryUnlink(path) {
2471
+ function tryUnlink$1(path) {
1837
2472
  try {
1838
2473
  (0, node_fs.unlinkSync)(path);
1839
2474
  } catch {}
@@ -1846,14 +2481,14 @@ function tryUnlink(path) {
1846
2481
  * exists to prevent, #24). `renameSync` moves the file atomically: only one
1847
2482
  * waiter wins the move; the loser gets ENOENT and loops back to re-check.
1848
2483
  */
1849
- function reclaimStaleLock(lockPath) {
2484
+ function reclaimStaleLock$1(lockPath) {
1850
2485
  const reclaimPath = `${lockPath}.reclaim.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
1851
2486
  try {
1852
2487
  (0, node_fs.renameSync)(lockPath, reclaimPath);
1853
2488
  } catch {
1854
2489
  return;
1855
2490
  }
1856
- tryUnlink(reclaimPath);
2491
+ tryUnlink$1(reclaimPath);
1857
2492
  }
1858
2493
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1859
2494
  const PRECOMPUTE_SIGNAL_INDEX = 2;
@@ -1892,6 +2527,11 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1892
2527
  const errLengthView = new DataView(sharedBuffer, 16, 4);
1893
2528
  const errDataArea = new Uint8Array(sharedBuffer, 20);
1894
2529
  const tmpPath = `${cachePath}.tmp.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
2530
+ try {
2531
+ new Function(PRECOMPUTE_SCRIPT);
2532
+ } catch (cause) {
2533
+ throw precomputeLoadError(resolvedPath, cause);
2534
+ }
1895
2535
  let worker;
1896
2536
  try {
1897
2537
  worker = new node_worker_threads.Worker(PRECOMPUTE_SCRIPT, {
@@ -1915,7 +2555,7 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1915
2555
  throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : /* @__PURE__ */ new Error("precompute worker exited without reporting a cause (it may have been killed by the OS, e.g. under memory pressure)"));
1916
2556
  }
1917
2557
  } finally {
1918
- tryUnlink(tmpPath);
2558
+ tryUnlink$1(tmpPath);
1919
2559
  worker.terminate();
1920
2560
  }
1921
2561
  }
@@ -1957,18 +2597,18 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1957
2597
  lockFd = (0, node_fs.openSync)(lockPath, "wx");
1958
2598
  } catch (cause) {
1959
2599
  if (cause.code === "EEXIST") {
1960
- if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock(lockPath);
2600
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock$1(lockPath);
1961
2601
  else syncSleep(LOCK_POLL_MS);
1962
2602
  continue;
1963
2603
  }
1964
2604
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1965
2605
  }
1966
2606
  try {
1967
- tryUnlink(cachePath);
2607
+ tryUnlink$1(cachePath);
1968
2608
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1969
2609
  } finally {
1970
2610
  (0, node_fs.closeSync)(lockFd);
1971
- tryUnlink(lockPath);
2611
+ tryUnlink$1(lockPath);
1972
2612
  }
1973
2613
  }
1974
2614
  }
@@ -2390,126 +3030,353 @@ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath, cwd
2390
3030
  throw new MissingEntryPointError(`\`settings.tailwindcss.entryPoint\` is required${filePath ? ` (linting \`${filePath}\`)` : ""}.`, "Set it to a string (single-project) or an array of `{ files, use }` mappings (monorepo).");
2391
3031
  }
2392
3032
  //#endregion
2393
- //#region src/utils/report.ts
3033
+ //#region src/design-system/ds-worker.ts
2394
3034
  /**
2395
- * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
2396
- *
2397
- * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
2398
- * enforce-consistent-variable-syntax, enforce-consistent-important-position,
2399
- * enforce-negative-arbitrary-values, no-deprecated-classes,
2400
- * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
2401
- * replacements via the same shape:
3035
+ * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
2402
3036
  *
2403
- * 1. Collect `{ cls, replacement }` entries from a class string.
2404
- * 2. Rebuild the full class string with replacements applied.
2405
- * 3. Emit ONE diagnostic with the autofix attached.
2406
- * 4. Emit one MORE diagnostic per remaining offender, each carrying
2407
- * the same autofix as a `suggest`.
3037
+ * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
3038
+ * (~500 LOC) — both spawned a worker that loaded the design system, then served
3039
+ * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
3040
+ * real difference was the body of the request loop: `getClassOrder` vs
3041
+ * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
3042
+ * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
3043
+ * service shrinks to ~40 LOC of singleton + public signature.
2408
3044
  *
2409
- * oxlint's fixer is single-shot per AST node, so multiple offenders in the
2410
- * same class string can only get one mechanical fix; the rest stay as
2411
- * suggestions the IDE can offer interactively.
3045
+ * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
3046
+ * of the process (per cssPath) so subsequent calls don't pay another
3047
+ * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
3048
+ * single `designSystemUnavailable` diagnostic.
2412
3049
  */
3050
+ const BUFFER_SIZE = 4 * 1024 * 1024;
3051
+ const HEADER_INTS = 4;
3052
+ const LENGTH_OFFSET = HEADER_INTS * 4;
3053
+ const DATA_OFFSET = 20;
3054
+ const INIT_TIMEOUT = 6e4;
3055
+ const REQUEST_TIMEOUT = 3e4;
3056
+ const MAX_WORKERS = 8;
2413
3057
  /**
2414
- * Emit autofix + suggestion diagnostics for a list of class replacements.
2415
- *
2416
- * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
2417
- * across all diagnostics — the first one is the primary fix, the rest carry
2418
- * the same fix as a suggestion (oxlint can only apply one autofix per node).
3058
+ * Build the worker script shared by `sort-service` and `canonicalize-service`.
3059
+ * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
3060
+ * constants the host uses, so they can't drift), the design-system load with
3061
+ * error propagation (DS-M4: the real cause is written into the buffer so the
3062
+ * host can surface it, not a generic "failed to load"), the ready signal, and
3063
+ * the request loop. `handlerExpr` is a function expression `(ds, request) =>
3064
+ * result` — the only part that differs between services.
2419
3065
  */
2420
- function reportClassReplacements(context, loc, split, classes, offending, options) {
2421
- if (offending.length === 0) return;
2422
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2423
- const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
2424
- const replacementKey = options.replacementKey ?? "replacement";
2425
- const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
2426
- const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2427
- const report = context.report;
2428
- for (let i = 0; i < offending.length; i++) {
2429
- const { cls, replacement } = offending[i];
2430
- const primaryData = {
2431
- className: cls,
2432
- [replacementKey]: replacement
2433
- };
2434
- if (i === 0) report({
2435
- node: loc.node,
2436
- messageId: options.messageId,
2437
- data: primaryData,
2438
- fix: applyFix
2439
- });
2440
- else report({
2441
- node: loc.node,
2442
- messageId: options.messageId,
2443
- data: primaryData,
2444
- suggest: [{
2445
- messageId: suggestMessageId,
2446
- data: {
2447
- className: cls,
2448
- replacement
2449
- },
2450
- fix: applyFix
2451
- }]
2452
- });
2453
- }
2454
- }
2455
- //#endregion
2456
- //#region src/rules/no-deprecated-classes.ts
2457
- const DEPRECATED_MAP = {
2458
- "flex-grow": "grow",
2459
- "flex-grow-0": "grow-0",
2460
- "flex-shrink": "shrink",
2461
- "flex-shrink-0": "shrink-0",
2462
- "overflow-ellipsis": "text-ellipsis",
2463
- "decoration-slice": "box-decoration-slice",
2464
- "decoration-clone": "box-decoration-clone",
2465
- "bg-gradient-to-t": "bg-linear-to-t",
2466
- "bg-gradient-to-tr": "bg-linear-to-tr",
2467
- "bg-gradient-to-r": "bg-linear-to-r",
2468
- "bg-gradient-to-br": "bg-linear-to-br",
2469
- "bg-gradient-to-b": "bg-linear-to-b",
2470
- "bg-gradient-to-bl": "bg-linear-to-bl",
2471
- "bg-gradient-to-l": "bg-linear-to-l",
2472
- "bg-gradient-to-tl": "bg-linear-to-tl"
2473
- };
2474
- const noDeprecatedClasses = defineRule({
2475
- meta: {
2476
- type: "problem",
2477
- docs: { description: "Disallow deprecated Tailwind CSS v4 classes" },
2478
- fixable: "code",
2479
- schema: [{
2480
- type: "object",
2481
- properties: { entryPoint: { type: "string" } },
2482
- additionalProperties: false
2483
- }],
2484
- hasSuggestions: true,
2485
- defaultOptions: [{}],
2486
- messages: {
2487
- deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
2488
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3066
+ function makeWorkerScript(handlerExpr, preamble = "") {
3067
+ return `
3068
+ ${preamble}
3069
+ const { workerData } = require('worker_threads');
3070
+ async function main() {
3071
+ const { sharedBuffer, cssPath } = workerData;
3072
+ const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
3073
+ const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
3074
+ const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
3075
+
3076
+ // On load failure, write the real cause into the data region so the host can
3077
+ // report it instead of a bare "failed to load the design system".
3078
+ function signalLoadError(e) {
3079
+ try {
3080
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
3081
+ const n = Math.min(msg.length, dataArea.length);
3082
+ dataArea.set(msg.subarray(0, n), 0);
3083
+ lengthView.setUint32(0, n);
3084
+ } catch {}
3085
+ Atomics.store(control, 2, -1);
3086
+ Atomics.notify(control, 2);
3087
+ }
3088
+
3089
+ let ds;
3090
+ try {
3091
+ const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
3092
+ const { readFileSync } = require('fs');
3093
+ const { dirname } = require('path');
3094
+ const css = readFileSync(cssPath, 'utf-8');
3095
+ ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
3096
+ } catch (e) {
3097
+ signalLoadError(e);
3098
+ return;
3099
+ }
3100
+
3101
+ Atomics.store(control, 2, 1);
3102
+ Atomics.notify(control, 2);
3103
+
3104
+ const handler = ${handlerExpr};
3105
+
3106
+ while (true) {
3107
+ Atomics.wait(control, 0, 0);
3108
+ const len = lengthView.getUint32(0);
3109
+ const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
3110
+ Atomics.store(control, 0, 0);
3111
+
3112
+ let response;
3113
+ try {
3114
+ const request = JSON.parse(requestStr);
3115
+ const result = handler(ds, request);
3116
+ response = Buffer.from(JSON.stringify(result), 'utf-8');
3117
+ } catch {
3118
+ response = Buffer.from('null', 'utf-8');
3119
+ }
3120
+
3121
+ // DS-M6: if the response doesn't fit the shared buffer, reply with a
3122
+ // sentinel the host reads as a rejected request, instead of letting
3123
+ // dataArea.set throw and kill the worker (which would hang the caller
3124
+ // until the request timeout and then report a misleading timeout).
3125
+ if (response.length > dataArea.length) {
3126
+ response = Buffer.from('null', 'utf-8');
3127
+ }
3128
+
3129
+ dataArea.set(response, 0);
3130
+ lengthView.setUint32(0, response.length);
3131
+ Atomics.store(control, 1, 1);
3132
+ Atomics.notify(control, 1);
3133
+ }
3134
+ }
3135
+ main().catch(() => {});
3136
+ `;
3137
+ }
3138
+ var DesignSystemWorker = class {
3139
+ opts;
3140
+ workers = /* @__PURE__ */ new Map();
3141
+ errors = /* @__PURE__ */ new Map();
3142
+ constructor(opts) {
3143
+ this.opts = opts;
3144
+ }
3145
+ /** Record an error as sticky for `cssPath` and return it for `throw`. */
3146
+ remember(cssPath, err) {
3147
+ this.errors.set(cssPath, err);
3148
+ return err;
3149
+ }
3150
+ /**
3151
+ * Ensure the worker is running and pointed at `cssPath`. Returns the
3152
+ * ready state. Throws `SortServiceError` on any failure (init timeout,
3153
+ * spawn error, DS-load error). Sticky: subsequent calls for the same
3154
+ * cssPath rethrow without retrying.
3155
+ */
3156
+ ensure(cssPath) {
3157
+ const sticky = this.errors.get(cssPath);
3158
+ if (sticky) throw sticky;
3159
+ const existing = this.workers.get(cssPath);
3160
+ if (existing) {
3161
+ this.workers.delete(cssPath);
3162
+ this.workers.set(cssPath, existing);
3163
+ return existing;
2489
3164
  }
2490
- },
2491
- createOnce(context) {
2492
- function check(locations) {
2493
- if (locations.length === 0) return;
2494
- for (const loc of locations) {
2495
- const split = splitClassesWithSeparators(loc.value);
2496
- const offending = split.classes.flatMap((cls) => {
2497
- const { utility, variant } = splitUtilityAndVariant(cls);
2498
- const { bare: bareUtility, position } = splitImportant(utility);
2499
- const replacement = DEPRECATED_MAP[bareUtility];
2500
- return replacement ? [{
2501
- cls,
2502
- replacement: variant + reattachImportant(replacement, position)
2503
- }] : [];
2504
- });
2505
- reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
2506
- }
3165
+ if (TAILWIND_NODE_PATH === null) throw this.remember(cssPath, new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run."));
3166
+ const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
3167
+ const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
3168
+ const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
3169
+ const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
3170
+ let worker;
3171
+ try {
3172
+ worker = new node_worker_threads.Worker(this.opts.workerScript, {
3173
+ eval: true,
3174
+ workerData: {
3175
+ sharedBuffer,
3176
+ cssPath,
3177
+ tailwindNodePath: TAILWIND_NODE_PATH
3178
+ }
3179
+ });
3180
+ } catch (cause) {
3181
+ throw this.remember(cssPath, new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 }));
2507
3182
  }
2508
- return createExtractorVisitors(context, check);
3183
+ worker.unref();
3184
+ worker.on("error", (err) => {
3185
+ this.errors.set(cssPath, new SortServiceError(`${this.opts.serviceName} worker died: ${err.message}`, "The worker will not be restarted in this process. Restart the lint session.", { cause: err }));
3186
+ const current = this.workers.get(cssPath);
3187
+ if (current && current.worker === worker) this.workers.delete(cssPath);
3188
+ });
3189
+ if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
3190
+ this.terminateWorker(worker);
3191
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Verify the CSS imports resolve; this can also happen if the machine or CI runner is heavily loaded."));
3192
+ }
3193
+ if (controlArray[2] === -1) {
3194
+ const len = lengthView.getUint32(0);
3195
+ const detail = len > 0 ? Buffer.from(dataArea.slice(0, len)).toString("utf-8") : "";
3196
+ this.terminateWorker(worker);
3197
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".${detail ? ` ${detail}` : ""}`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid."));
3198
+ }
3199
+ const state = {
3200
+ worker,
3201
+ controlArray,
3202
+ lengthView,
3203
+ dataArea,
3204
+ cssPath
3205
+ };
3206
+ this.workers.set(cssPath, state);
3207
+ this.evictIfNeeded();
3208
+ return state;
3209
+ }
3210
+ /** Evict least-recently-used workers past the cap (#77). */
3211
+ evictIfNeeded() {
3212
+ while (this.workers.size > MAX_WORKERS) {
3213
+ const oldestKey = this.workers.keys().next().value;
3214
+ if (oldestKey === void 0) break;
3215
+ const oldest = this.workers.get(oldestKey);
3216
+ this.workers.delete(oldestKey);
3217
+ if (oldest) this.terminateWorker(oldest.worker);
3218
+ }
3219
+ }
3220
+ /**
3221
+ * Send a request to the worker and synchronously wait for the response.
3222
+ * Throws `SortServiceError` on any failure.
3223
+ */
3224
+ callSync(cssPath, req) {
3225
+ const state = this.ensure(cssPath);
3226
+ const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
3227
+ if (requestBytes.length > BUFFER_SIZE - DATA_OFFSET) throw new SortServiceError(`${this.opts.serviceName} request payload is too large (${requestBytes.length} > ${BUFFER_SIZE - DATA_OFFSET} bytes).`, "This is unexpected with typical class lists; please open an issue.");
3228
+ state.dataArea.set(requestBytes, 0);
3229
+ state.lengthView.setUint32(0, requestBytes.length);
3230
+ Atomics.store(state.controlArray, 0, 1);
3231
+ Atomics.notify(state.controlArray, 0);
3232
+ if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
3233
+ this.dropWorker(cssPath);
3234
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "This is unexpected for typical class lists; please open an issue if it persists."));
3235
+ }
3236
+ const responseLen = state.lengthView.getUint32(0);
3237
+ const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
3238
+ Atomics.store(state.controlArray, 1, 0);
3239
+ let parsed;
3240
+ try {
3241
+ parsed = JSON.parse(responseStr);
3242
+ } catch (cause) {
3243
+ this.dropWorker(cssPath);
3244
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned non-JSON response.`, "This is a bug; please open an issue.", { cause: cause instanceof Error ? cause : void 0 }));
3245
+ }
3246
+ if (parsed === null) {
3247
+ this.dropWorker(cssPath);
3248
+ throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned null — the request body was rejected or its response did not fit the buffer.`, "This is a bug; please open an issue with the input that triggered it."));
3249
+ }
3250
+ return parsed;
3251
+ }
3252
+ reset() {
3253
+ for (const state of this.workers.values()) this.terminateWorker(state.worker);
3254
+ this.workers.clear();
3255
+ this.errors.clear();
3256
+ }
3257
+ /** Terminate and forget the worker for a single cssPath (on request failure). */
3258
+ dropWorker(cssPath) {
3259
+ const state = this.workers.get(cssPath);
3260
+ if (state) {
3261
+ this.workers.delete(cssPath);
3262
+ this.terminateWorker(state.worker);
3263
+ }
3264
+ }
3265
+ terminateWorker(worker) {
3266
+ try {
3267
+ worker.removeAllListeners("error");
3268
+ worker.terminate();
3269
+ } catch {}
2509
3270
  }
3271
+ };
3272
+ //#endregion
3273
+ //#region src/design-system/declaration-service.ts
3274
+ const declWorker = new DesignSystemWorker({
3275
+ workerScript: makeWorkerScript(`(ds, request) => {
3276
+ const decls = {};
3277
+ const values = {};
3278
+ const invalid = [];
3279
+ // A prefixed design system only resolves the PREFIXED form (\`tw:p-[5px]\`), and
3280
+ // the host asks with prefix-free names — \`extractUtility\` strips the project
3281
+ // prefix along with the variants. Same invariant the precompute follows: apply
3282
+ // the prefix only when talking to the design system, key everything returned
3283
+ // prefix-free. Without this the service resolved NOTHING in a prefixed project,
3284
+ // so every user-written value went silently uncompared.
3285
+ const prefix = (ds.theme && ds.theme.prefix) || '';
3286
+ const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3287
+ const css = ds.candidatesToCss(request.classes.map(pfx));
3288
+ for (let i = 0; i < request.classes.length; i++) {
3289
+ if (!css[i]) { invalid.push(request.classes[i]); continue; }
3290
+ const cls = request.classes[i];
3291
+ const list = [];
3292
+ // The selector carries the prefix, so the scope classifier needs the
3293
+ // prefixed name even though the result is keyed by the bare one.
3294
+ walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
3295
+ list.push([scope, prop, value]);
3296
+ if (!(value in values)) {
3297
+ const reads = scanVarReads(value);
3298
+ values[value] = { p: reads[0], f: reads[1], u: isPureVarRead(value) };
3299
+ }
3300
+ });
3301
+ if (list.length > 0) decls[cls] = list;
3302
+ }
3303
+ return { decls, values, invalid };
3304
+ }`, DECL_EXTRACTOR_SOURCE),
3305
+ serviceName: "declarations"
2510
3306
  });
3307
+ /**
3308
+ * Everything already asked about, per design-system CACHE — not per entry point:
3309
+ * class name → does the design system produce CSS for it. A miss is remembered
3310
+ * too, so a class that compiles to nothing is not re-queried on every AST node it
3311
+ * appears in.
3312
+ *
3313
+ * The lifetime has to match the cache's, because that is where the declarations
3314
+ * are interned. Keyed by path, a rebuilt cache (an mtime bump in a long-lived
3315
+ * editor process, or `resetDesignSystem()`) inherited a fully-populated map and
3316
+ * could never re-learn: the rules went permanently blind to user-written values
3317
+ * with no diagnostic. A WeakMap also means there is nothing to reset.
3318
+ */
3319
+ const answers = /* @__PURE__ */ new WeakMap();
3320
+ function answersFor(cache) {
3321
+ let map = answers.get(cache);
3322
+ if (!map) {
3323
+ map = /* @__PURE__ */ new Map();
3324
+ answers.set(cache, map);
3325
+ }
3326
+ return map;
3327
+ }
3328
+ /**
3329
+ * Ask the design system about every class there is no answer for yet, intern the
3330
+ * declarations it returns, and record which classes produce no CSS at all.
3331
+ *
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.
3336
+ */
3337
+ function ask(cssPath, cache, classes) {
3338
+ const known = answersFor(cache);
3339
+ 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
+ }
3348
+ const invalid = new Set(response.invalid);
3349
+ for (const cls of pending) known.set(cls, !invalid.has(cls));
3350
+ for (const [cls, raws] of Object.entries(response.decls)) cache.internDeclarations(cls, raws, response.values);
3351
+ return true;
3352
+ }
3353
+ /**
3354
+ * Resolve and intern declarations for `classes` that the precompute doesn't know.
3355
+ * They land in the cache, so the caller reads them back through
3356
+ * `cache.getCssDeclarations` like any other class.
3357
+ */
3358
+ function resolveDeclarationsSync(cssPath, cache, classes) {
3359
+ ask(cssPath, cache, classes);
3360
+ }
3361
+ /**
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.
3364
+ *
3365
+ * This is what makes validity exact for the classes the precompute cannot
3366
+ * enumerate: `w-45` and `bg-red-5000` are shaped identically, and only Tailwind
3367
+ * knows that it compiles the first and not the second.
3368
+ */
3369
+ function validateClassesSync(cssPath, cache, classes) {
3370
+ if (!ask(cssPath, cache, classes)) return null;
3371
+ return answersFor(cache);
3372
+ }
2511
3373
  //#endregion
2512
3374
  //#region src/rules/no-unknown-classes.ts
3375
+ /**
3376
+ * Utility used to probe a variant chain. Any always-valid utility works; `flex`
3377
+ * is the shortest one every Tailwind build has.
3378
+ */
3379
+ const PROBE_UTILITY = "flex";
2513
3380
  const noUnknownClasses = defineRule({
2514
3381
  meta: {
2515
3382
  type: "problem",
@@ -2538,6 +3405,8 @@ const noUnknownClasses = defineRule({
2538
3405
  unknown: "\"{{className}}\" is not a valid Tailwind class.",
2539
3406
  unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
2540
3407
  missingPrefix: "\"{{className}}\" needs the \"{{prefix}}:\" prefix to produce CSS. Did you mean \"{{suggestion}}\"?",
3408
+ unknownVariant: "\"{{className}}\" produces no CSS: \"{{variant}}\" is not a variant this design system knows.",
3409
+ unknownVariantWithSuggestion: "\"{{className}}\" produces no CSS: \"{{variant}}\" is not a variant this design system knows. Did you mean \"{{suggestion}}\"?",
2541
3410
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2542
3411
  ...DS_UNAVAILABLE_MESSAGE
2543
3412
  }
@@ -2562,136 +3431,184 @@ const noUnknownClasses = defineRule({
2562
3431
  position
2563
3432
  };
2564
3433
  }
3434
+ /**
3435
+ * Does the design system compile this variant chain?
3436
+ *
3437
+ * `variantOrder` only lists the STATIC variants (71 of them: `hover`, `md`,
3438
+ * `dark`, …). It has no `group`, no `data`, no `@md`, because those are
3439
+ * functional variants whose values are unbounded — so validating a chain
3440
+ * against that list would report `group-hover:` and `data-[x=1]:` as unknown.
3441
+ * Compiling a probe utility under the chain is the only exact answer, and it
3442
+ * costs one design-system call per DISTINCT chain in the project.
3443
+ */
3444
+ const chainAnswers = /* @__PURE__ */ new Map();
3445
+ function chainProduces(cache, entryPoint, chain) {
3446
+ const key = `${entryPoint}\0${chain}`;
3447
+ const memo = chainAnswers.get(key);
3448
+ if (memo !== void 0) return memo;
3449
+ const probe = `${chain}${PROBE_UTILITY}`;
3450
+ const answers = validateClassesSync(entryPoint, cache, [probe]);
3451
+ const verdict = answers ? answers.get(probe) ?? null : null;
3452
+ chainAnswers.set(key, verdict);
3453
+ return verdict;
3454
+ }
3455
+ /** Replace one class in the location and report, with a quick-fix suggestion. */
3456
+ function reportWithSuggestion(loc, classes, cls, replacement, messageId, data, split) {
3457
+ const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? replacement : c));
3458
+ context.report({
3459
+ node: loc.node,
3460
+ messageId,
3461
+ data,
3462
+ suggest: [{
3463
+ messageId: "suggestReplace",
3464
+ data: {
3465
+ className: cls,
3466
+ replacement
3467
+ },
3468
+ fix(fixer) {
3469
+ return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3470
+ }
3471
+ }]
3472
+ });
3473
+ }
2565
3474
  function check(locations) {
2566
3475
  if (locations.length === 0) return;
2567
3476
  const ds = safeGetDS(getDS, context, locations[0].node);
2568
3477
  if (!ds) return;
2569
- const { cache } = ds;
3478
+ const { cache, entryPoint } = ds;
2570
3479
  for (const loc of locations) {
2571
3480
  const split = splitClassesWithSeparators(loc.value);
2572
3481
  const classes = split.classes;
3482
+ let toVerify = null;
3483
+ for (const cls of classes) {
3484
+ if (shouldIgnore(cls)) continue;
3485
+ const bare = strippedUtility(cls).bare;
3486
+ if (cache.isKnownClass(bare)) continue;
3487
+ if (!toVerify) toVerify = [];
3488
+ toVerify.push(bare);
3489
+ }
3490
+ const verified = toVerify ? validateClassesSync(entryPoint, cache, toVerify) : null;
2573
3491
  for (const cls of classes) {
2574
3492
  if (shouldIgnore(cls)) continue;
2575
3493
  const validity = cache.classValidity(cls);
2576
- if (validity === "valid") continue;
2577
3494
  const { variant, bare, position } = strippedUtility(cls);
2578
- if (DEPRECATED_MAP[bare]) continue;
3495
+ if (validity === "valid" && !variant && cache.isKnownClass(bare)) continue;
3496
+ if (cache.deprecatedReplacement(bare)) continue;
2579
3497
  if (validity === "missing-prefix") {
2580
3498
  const fixed = `${cache.prefix}:${cls}`;
2581
- const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? fixed : c));
2582
- context.report({
2583
- node: loc.node,
2584
- messageId: "missingPrefix",
2585
- data: {
2586
- className: cls,
2587
- prefix: cache.prefix,
2588
- suggestion: fixed
2589
- },
2590
- suggest: [{
2591
- messageId: "suggestReplace",
2592
- data: {
2593
- className: cls,
2594
- replacement: fixed
2595
- },
2596
- fix(fixer) {
2597
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2598
- }
2599
- }]
2600
- });
3499
+ reportWithSuggestion(loc, classes, cls, fixed, "missingPrefix", {
3500
+ className: cls,
3501
+ prefix: cache.prefix,
3502
+ suggestion: fixed
3503
+ }, split);
2601
3504
  continue;
2602
3505
  }
2603
- const suggestionBare = findBestSuggestion(bare, cache.validClasses);
2604
- const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
2605
- if (suggestion) {
2606
- const fixedValue = rebuildClassString(split, classes.map((c) => c === cls ? suggestion : c));
2607
- context.report({
3506
+ const compiles = cache.isKnownClass(bare) ? true : verified?.get(bare);
3507
+ if (validity === "unknown" || compiles === false) {
3508
+ const suggestionBare = findBestSuggestion(bare, cache.validClasses);
3509
+ const suggestion = suggestionBare ? variant + reattachImportant(suggestionBare, position) : null;
3510
+ if (suggestion) reportWithSuggestion(loc, classes, cls, suggestion, "unknownWithSuggestion", {
3511
+ className: cls,
3512
+ suggestion
3513
+ }, split);
3514
+ else context.report({
2608
3515
  node: loc.node,
2609
- messageId: "unknownWithSuggestion",
2610
- data: {
2611
- className: cls,
2612
- suggestion
2613
- },
2614
- suggest: [{
2615
- messageId: "suggestReplace",
2616
- data: {
2617
- className: cls,
2618
- replacement: suggestion
2619
- },
2620
- fix(fixer) {
2621
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2622
- }
2623
- }]
3516
+ messageId: "unknown",
3517
+ data: { className: cls }
2624
3518
  });
2625
- } else context.report({
3519
+ continue;
3520
+ }
3521
+ if (!variant) continue;
3522
+ if (chainProduces(cache, entryPoint, variant) !== false) continue;
3523
+ const { variant: offending, suggestion, fixedChain } = diagnoseChain(cache, entryPoint, variant);
3524
+ const fixedClass = fixedChain ? fixedChain + reattachImportant(bare, position) : null;
3525
+ if (fixedClass && suggestion) reportWithSuggestion(loc, classes, cls, fixedClass, "unknownVariantWithSuggestion", {
3526
+ className: cls,
3527
+ variant: offending,
3528
+ suggestion
3529
+ }, split);
3530
+ else context.report({
2626
3531
  node: loc.node,
2627
- messageId: "unknown",
2628
- data: { className: cls }
3532
+ messageId: "unknownVariant",
3533
+ data: {
3534
+ className: cls,
3535
+ variant: offending
3536
+ }
2629
3537
  });
2630
3538
  }
2631
3539
  }
2632
3540
  }
3541
+ /**
3542
+ * Which segment of an invalid chain is to blame, and what to use instead.
3543
+ *
3544
+ * Every candidate correction is checked against the design system before it
3545
+ * is offered, so a suggestion is never a guess: `group-hoverr` is corrected by
3546
+ * fixing its last dash-segment and confirming that `group-hover:` compiles.
3547
+ * That also means no list of compound roots (`group`, `peer`, `data`, …) has
3548
+ * to be maintained here.
3549
+ */
3550
+ function diagnoseChain(cache, entryPoint, chain) {
3551
+ const segments = extractVariants(`${chain}${PROBE_UTILITY}`);
3552
+ const names = cache.variantNames();
3553
+ for (const segment of segments) {
3554
+ if (segment.startsWith("[")) continue;
3555
+ if (chainProduces(cache, entryPoint, `${segment}:`) !== false) continue;
3556
+ for (const candidate of correctionsFor(segment, names)) {
3557
+ if (chainProduces(cache, entryPoint, `${candidate}:`) !== true) continue;
3558
+ return {
3559
+ variant: segment,
3560
+ suggestion: candidate,
3561
+ fixedChain: segments.map((s) => s === segment ? candidate : s).join(":") + ":"
3562
+ };
3563
+ }
3564
+ return {
3565
+ variant: segment,
3566
+ suggestion: null,
3567
+ fixedChain: null
3568
+ };
3569
+ }
3570
+ return {
3571
+ variant: chain.slice(0, -1),
3572
+ suggestion: null,
3573
+ fixedChain: null
3574
+ };
3575
+ }
3576
+ /** Spelling candidates for a variant segment, nearest neighbour first. */
3577
+ function correctionsFor(segment, names) {
3578
+ const out = [];
3579
+ const whole = findBestSuggestion(segment, names);
3580
+ if (whole) out.push(whole);
3581
+ const dash = segment.lastIndexOf("-");
3582
+ if (dash > 0) {
3583
+ const tail = findBestSuggestion(segment.slice(dash + 1), names);
3584
+ if (tail) out.push(`${segment.slice(0, dash)}-${tail}`);
3585
+ }
3586
+ return out;
3587
+ }
2633
3588
  return createExtractorVisitors(context, check);
2634
3589
  }
2635
3590
  });
2636
3591
  //#endregion
2637
3592
  //#region src/rules/no-conflicting-classes/spec.ts
2638
- const COMPLEMENTARY_GROUPS = [
2639
- {
2640
- pattern: /^(from|via|to)-/,
2641
- reason: "Gradient stops (`from-*`, `via-*`, `to-*`) share `--tw-gradient-stops`; different prefixes compose, same prefix conflicts."
2642
- },
2643
- {
2644
- pattern: /^(transition|duration|ease|delay)(?:-|$)/,
2645
- reason: "`transition-*` composes with `duration-*`, `ease-*`, `delay-*` — `transition-all` itself has no `--tw-*` vars so the heuristic misses it."
2646
- },
2647
- {
2648
- pattern: /^-?(translate|scale|rotate|skew)-/,
2649
- reason: "Transform axes (translate / scale / rotate / skew) compose into a single `transform`; the overlap is not captured in `cssProps`."
2650
- },
2651
- {
2652
- pattern: /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
2653
- reason: "Mask gradients: different families (e.g. `mask-linear-*` vs `mask-radial-*`) or roles (`from`/`via`/`to`/`at`) compose; same family+role conflicts."
2654
- },
2655
- {
2656
- pattern: /^prose(?:-|$)/,
2657
- reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
2658
- }
2659
- ];
3593
+ const COMPLEMENTARY_GROUPS = [{
3594
+ pattern: /^prose(?:-|$)/,
3595
+ reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
3596
+ }];
2660
3597
  const COMPOSITION_PAIRS = [
2661
- {
2662
- a: /^text-/,
2663
- b: /^leading-/,
2664
- reason: "`text-*` sets line-height via its size token; `leading-*` overrides it."
2665
- },
2666
- {
2667
- a: /^text-/,
2668
- b: /^tracking-/,
2669
- reason: "`text-*` may set letter-spacing via its size token; `tracking-*` overrides it."
2670
- },
2671
- {
2672
- a: /^border(?:-[0-9]|$)/,
2673
- b: /^border-(?:solid|dashed|dotted|double|hidden|none)$/,
2674
- reason: "`border-*` (width) composes with `border-{solid,dashed,…}` (style)."
2675
- },
2676
- {
2677
- a: /^divide-/,
2678
- b: /^border(?:-[trblxyse])?-/,
2679
- reason: "`divide-*` styles direct children; `border-*` styles the element itself."
2680
- },
2681
3598
  {
2682
3599
  a: /^prose(?:-|$)/,
2683
3600
  b: /^max-w-/,
2684
3601
  reason: "`prose` sets a default max-width; `max-w-*` overrides it."
2685
3602
  },
2686
3603
  {
2687
- a: /^animate-in$/,
2688
- b: /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/,
2689
- reason: "`animate-in` initializes all `--tw-enter-*` vars; `*-in` modifiers each override one. (`tailwindcss-animate` / `tw-animate-css`.)"
3604
+ a: /^prose(?:-|$)/,
3605
+ b: /^(?:text-|leading-|tracking-)/,
3606
+ reason: "`prose` sets default typographic values on the element; `text-*`/`leading-*`/`tracking-*` override them."
2690
3607
  },
2691
3608
  {
2692
- a: /^animate-out$/,
2693
- b: /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/,
2694
- reason: "`animate-out` initializes all `--tw-exit-*` vars; `*-out` modifiers each override one."
3609
+ a: /^-?(?:space|divide)-[xy](?:-|$)/,
3610
+ b: /^(?:space|divide)-[xy]-reverse$/,
3611
+ reason: "`space-*`/`divide-*` write the reverse flag as its default; `*-reverse` flips it — the documented way to space a reversed flex row."
2695
3612
  },
2696
3613
  {
2697
3614
  a: /^mask-(?:add|subtract|intersect|exclude)$/,
@@ -2700,39 +3617,239 @@ const COMPOSITION_PAIRS = [
2700
3617
  }
2701
3618
  ];
2702
3619
  //#endregion
2703
- //#region src/rules/no-conflicting-classes.ts
3620
+ //#region src/rules/no-conflicting-classes/decide.ts
3621
+ /** Builds the comparison key. Same property on two different boxes never clashes. */
3622
+ function declKey(decl) {
3623
+ return decl.scope === "element" ? decl.prop : `${decl.pseudo || ">"}|${decl.prop}`;
3624
+ }
3625
+ /** The property name a key refers to, for the diagnostic message. */
3626
+ function keyProp(key) {
3627
+ const sep = key.lastIndexOf("|");
3628
+ return sep < 0 ? key : key.slice(sep + 1);
3629
+ }
3630
+ /** How to describe a key's box in the message; empty for the element itself. */
3631
+ function keyScopeLabel(key) {
3632
+ const sep = key.indexOf("|");
3633
+ if (sep < 0) return "";
3634
+ const scope = key.slice(0, sep);
3635
+ return scope === ">" ? "direct children" : scope;
3636
+ }
3637
+ const NO_INFO_VALUES = /* @__PURE__ */ new Set([
3638
+ "",
3639
+ "initial",
3640
+ "unset"
3641
+ ]);
3642
+ const CLOSURE_LIMIT = 64;
3643
+ function collectFacts(classes) {
3644
+ const groupWrites = /* @__PURE__ */ new Set();
3645
+ const effectiveWriter = /* @__PURE__ */ new Map();
3646
+ for (const cls of classes) for (const varName of cls.writes.keys()) {
3647
+ groupWrites.add(varName);
3648
+ const current = effectiveWriter.get(varName);
3649
+ if (current === void 0 || cls.order !== null && (current.order === null || cls.order > current.order)) effectiveWriter.set(varName, cls);
3650
+ }
3651
+ return {
3652
+ groupWrites,
3653
+ effectiveWriter
3654
+ };
3655
+ }
3656
+ /** Splits `!` off and reports whether the class was important. */
3657
+ function isImportant(className) {
3658
+ return splitImportant(className).position !== null;
3659
+ }
3660
+ /**
3661
+ * Which custom properties a value actually depends on.
3662
+ *
3663
+ * A `var()` fallback is dead once the variable is supplied, so fallback reads
3664
+ * only count when a direct read is missing from the group. Without this,
3665
+ * `text-sm` would appear to need `--text-sm--line-height` — a token no utility
3666
+ * writes — and its composition with `leading-6` would read as a conflict.
3667
+ */
3668
+ function neededVars(decl, groupWrites) {
3669
+ const needed = [...decl.readsVars];
3670
+ if (!needed.every((v) => groupWrites.has(v))) {
3671
+ for (const v of decl.readsFallbackVars) if (!needed.includes(v)) needed.push(v);
3672
+ }
3673
+ return needed;
3674
+ }
3675
+ /**
3676
+ * Does the winner's declaration still pull in the loser's contribution?
3677
+ *
3678
+ * Walks the winner's variable reads, expanding each through the group's
3679
+ * effective writer, and hits when that chain reaches the loser. This is what
3680
+ * covers `drop-shadow-xl drop-shadow-indigo-500` directly and the gradient
3681
+ * family (`from-*` → `--tw-gradient-via-stops` → `via-*`) transitively.
3682
+ */
3683
+ function winnerAbsorbsLoser(winnerDecl, loser, group) {
3684
+ const seen = /* @__PURE__ */ new Set();
3685
+ const frontier = [...winnerDecl.readsVars, ...winnerDecl.readsFallbackVars];
3686
+ let steps = 0;
3687
+ while (frontier.length > 0 && steps++ < CLOSURE_LIMIT) {
3688
+ const varName = frontier.pop();
3689
+ if (seen.has(varName)) continue;
3690
+ seen.add(varName);
3691
+ const writer = group.effectiveWriter.get(varName);
3692
+ if (writer === loser) return true;
3693
+ if (!writer) continue;
3694
+ const written = writer.decls.get(varName);
3695
+ if (written) frontier.push(...written.readsVars, ...written.readsFallbackVars);
3696
+ }
3697
+ return false;
3698
+ }
3699
+ /**
3700
+ * Was the loser's declaration only forwarding a value someone else supplies?
3701
+ *
3702
+ * `outline-2` declares `outline-style: var(--tw-outline-style)` — it carries no
3703
+ * value of its own, and `outline-solid` both writes that variable and declares
3704
+ * the property concretely. Losing the forwarding declaration changes nothing.
3705
+ *
3706
+ * The three guards matter:
3707
+ * - variables the loser writes ITSELF are excluded, so `transform-none
3708
+ * rotate-x-45` (whose `transform` forwards four variables nobody supplies)
3709
+ * stays a conflict;
3710
+ * - the winner must supply one of them, otherwise an unrelated class that simply
3711
+ * outranks a reader/writer pair would silence a real clobber;
3712
+ * - a loser that forwards nothing (empty set) is carrying its own contribution.
3713
+ */
3714
+ function loserOnlyForwards(loserDecl, loser, winner, group) {
3715
+ if (!loserDecl.pureVarRead) return false;
3716
+ const needed = neededVars(loserDecl, group.groupWrites).filter((v) => !loser.writes.has(v));
3717
+ if (needed.length === 0) return false;
3718
+ if (!needed.every((v) => group.groupWrites.has(v))) return false;
3719
+ return needed.some((v) => winner.writes.has(v));
3720
+ }
3721
+ /** Resolves which of the two classes wins the cascade. `!` beats stylesheet order. */
3722
+ function resolveWinner(a, b) {
3723
+ if (a.important !== b.important) return a.important ? {
3724
+ winner: a,
3725
+ loser: b,
3726
+ orderKnown: true
3727
+ } : {
3728
+ winner: b,
3729
+ loser: a,
3730
+ orderKnown: true
3731
+ };
3732
+ if (a.order === null || b.order === null || a.order === b.order) return {
3733
+ winner: b,
3734
+ loser: a,
3735
+ orderKnown: false
3736
+ };
3737
+ return a.order > b.order ? {
3738
+ winner: a,
3739
+ loser: b,
3740
+ orderKnown: true
3741
+ } : {
3742
+ winner: b,
3743
+ loser: a,
3744
+ orderKnown: true
3745
+ };
3746
+ }
3747
+ /** A custom property cleared to a value that says nothing. */
3748
+ function isReset(decl) {
3749
+ return decl.prop.startsWith("--") && NO_INFO_VALUES.has(decl.value.trim());
3750
+ }
2704
3751
  /**
2705
- * Two utilities compose via CSS custom properties if both define their own
2706
- * --tw-* properties that don't overlap — they each contribute to a shared
2707
- * shorthand (e.g. `shadow` and `ring` both end up in `box-shadow` via
2708
- * different intermediate vars).
3752
+ * Is clearing variables the whole point of this class?
3753
+ *
3754
+ * `blur-none` writes `--tw-blur: ` and then only forwards the filter chain;
3755
+ * `animate-in` clears `--tw-enter-*` but also declares real values of its own.
3756
+ * The first cannot afford to lose its reset, the second can.
2709
3757
  */
2710
- function isCompositionViaCssVars(propsA, propsB) {
2711
- const customA = propsA.filter((p) => p.startsWith("--"));
2712
- const customB = propsB.filter((p) => p.startsWith("--"));
2713
- if (customA.length === 0 || customB.length === 0) return false;
2714
- return !customA.some((p) => customB.includes(p));
3758
+ function resetIsAllTheClassDoes(cls) {
3759
+ let sawSubstance = false;
3760
+ for (const decl of cls.decls.values()) {
3761
+ if (isReset(decl)) continue;
3762
+ if (decl.pureVarRead) continue;
3763
+ sawSubstance = true;
3764
+ break;
3765
+ }
3766
+ return !sawSubstance;
3767
+ }
3768
+ /** Does the surviving declaration reproduce what the other one contributed? */
3769
+ function composes(winnerDecl, winner, loserDecl, loser, group) {
3770
+ return winnerAbsorbsLoser(winnerDecl, loser, group) || loserOnlyForwards(loserDecl, loser, winner, group);
3771
+ }
3772
+ function decidePair(a, b, group) {
3773
+ const { winner, loser, orderKnown } = resolveWinner(a, b);
3774
+ const conflicts = [];
3775
+ const duplicates = [];
3776
+ for (const [key, loserDecl] of loser.decls) {
3777
+ const winnerDecl = winner.decls.get(key);
3778
+ if (!winnerDecl) continue;
3779
+ if (loser.ambiguousKeys.has(key) || winner.ambiguousKeys.has(key)) continue;
3780
+ if (loserDecl.valueId === winnerDecl.valueId) {
3781
+ duplicates.push(key);
3782
+ continue;
3783
+ }
3784
+ if (isReset(loserDecl) && !resetIsAllTheClassDoes(loser)) continue;
3785
+ if (composes(winnerDecl, winner, loserDecl, loser, group)) continue;
3786
+ if (!orderKnown && composes(loserDecl, loser, winnerDecl, winner, group)) continue;
3787
+ conflicts.push(key);
3788
+ }
3789
+ return {
3790
+ winner,
3791
+ loser,
3792
+ conflicts,
3793
+ duplicates,
3794
+ orderKnown
3795
+ };
2715
3796
  }
2716
3797
  /**
2717
- * Detect a narrowing override: the later class's CSS properties are a strict
2718
- * subset of the earlier class's, so the later class refines one of the
2719
- * shorthand's properties (size-4 h-6, rounded-t-lg rounded-tl-sm, truncate
2720
- * text-clip). Direction-sensitive: the inverse means the wider later class
2721
- * clobbers a prior narrower override.
3798
+ * Which class (if any) is dead weight: every declaration it makes is also made,
3799
+ * identically, by the other one. A `partial` class is never named — its CSS is
3800
+ * only partly modelled, so "it adds nothing" would be a guess.
2722
3801
  */
2723
- function isNarrowingOverride(propsEarlier, propsLater) {
2724
- if (propsLater.length === 0 || propsLater.length >= propsEarlier.length) return false;
2725
- const setEarlier = new Set(propsEarlier);
2726
- return propsLater.every((p) => setEarlier.has(p));
3802
+ function redundantSide(verdict) {
3803
+ if (verdict.conflicts.length > 0 || verdict.duplicates.length === 0) return null;
3804
+ const dup = new Set(verdict.duplicates);
3805
+ const covered = (c) => c.decls.size > 0 && [...c.decls.keys()].every((k) => dup.has(k));
3806
+ if (!verdict.loser.partial && covered(verdict.loser)) return {
3807
+ loser: verdict.loser,
3808
+ winner: verdict.winner
3809
+ };
3810
+ if (!verdict.winner.partial && covered(verdict.winner)) return {
3811
+ loser: verdict.winner,
3812
+ winner: verdict.loser
3813
+ };
3814
+ return null;
3815
+ }
3816
+ //#endregion
3817
+ //#region src/rules/no-conflicting-classes.ts
3818
+ /**
3819
+ * Compiles the `allow` option.
3820
+ *
3821
+ * A bare pattern silences every pair involving a matching class; a two-element
3822
+ * pattern silences that specific combination. This is the supported way to teach
3823
+ * the rule about a stack we cannot derive — nobody should have to wait for a
3824
+ * release of this plugin to silence a combination their own plugins produce.
3825
+ */
3826
+ function compileAllow(allow) {
3827
+ const allowClasses = [];
3828
+ const allowPairs = [];
3829
+ for (const entry of allow ?? []) {
3830
+ if (typeof entry === "string") {
3831
+ allowClasses.push(entry);
3832
+ continue;
3833
+ }
3834
+ const [a, b] = compileRegexList(entry);
3835
+ if (a && b) allowPairs.push([a, b]);
3836
+ }
3837
+ return {
3838
+ allowClasses: compileRegexList(allowClasses),
3839
+ allowPairs
3840
+ };
2727
3841
  }
2728
3842
  /**
2729
- * Returns true if two classes (within the same variant) should NOT be reported
2730
- * as conflicting despite sharing CSS properties. Pure: regex tables are passed
2731
- * in (or default to the module-level constants).
3843
+ * Returns true if two classes (within the same variant) should NOT be compared
3844
+ * at all, despite sharing CSS properties. Pure: regex tables are passed in (or
3845
+ * default to the module-level constants).
3846
+ *
3847
+ * These tables are the exception, not the mechanism: everything a comparison of
3848
+ * the generated CSS can decide is decided in `decide.ts`. What survives here is
3849
+ * plugin intent that no CSS comparison can see — see `spec.ts` for why each
3850
+ * entry cannot be derived.
2732
3851
  */
2733
- function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
2734
- if (isCompositionViaCssVars(propsA, propsB)) return true;
2735
- if (isNarrowingOverride(propsA, propsB)) return true;
3852
+ function shouldSkipPair(a, b, rules = {}) {
2736
3853
  const ua = splitImportant(extractUtility(a)).bare;
2737
3854
  const ub = splitImportant(extractUtility(b)).bare;
2738
3855
  const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
@@ -2750,28 +3867,72 @@ function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
2750
3867
  for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
2751
3868
  return false;
2752
3869
  }
3870
+ /** Whether the user's `allow` option silences this pair. */
3871
+ function isAllowed(a, b, allowClasses, allowPairs) {
3872
+ if (matchesAny(a, allowClasses) || matchesAny(b, allowClasses)) return true;
3873
+ return allowPairs.some(([reA, reB]) => reA.test(a) && reB.test(b) || reA.test(b) && reB.test(a));
3874
+ }
3875
+ /**
3876
+ * `"color"` / `"color", "width"` / `3 CSS properties`, naming the box when it
3877
+ * isn't the element. A pair can clash on several boxes at once (a plugin utility
3878
+ * that styles itself and a `::-webkit-scrollbar` pseudo-element), so the label
3879
+ * goes per property unless every property shares the same box.
3880
+ */
3881
+ function formatProperties(keys) {
3882
+ const scopes = new Set(keys.map(keyScopeLabel));
3883
+ if (scopes.size > 1) {
3884
+ const labelled = [...new Set(keys.map((key) => {
3885
+ const scope = keyScopeLabel(key);
3886
+ return scope ? `"${keyProp(key)}" (${scope})` : `"${keyProp(key)}"`;
3887
+ }))];
3888
+ return labelled.length <= 3 ? labelled.join(", ") : `${labelled.length} CSS properties`;
3889
+ }
3890
+ const props = [...new Set(keys.map(keyProp))];
3891
+ const list = props.length <= 3 ? `"${props.join("\", \"")}"` : `${props.length} CSS properties`;
3892
+ const scope = [...scopes][0];
3893
+ return scope ? `${list} (${scope})` : list;
3894
+ }
2753
3895
  const noConflictingClasses = defineRule({
2754
3896
  meta: {
2755
3897
  type: "problem",
2756
3898
  docs: { description: "Disallow Tailwind CSS classes that generate conflicting CSS properties" },
2757
3899
  schema: [{
2758
3900
  type: "object",
2759
- properties: { entryPoint: { type: "string" } },
3901
+ properties: {
3902
+ entryPoint: { type: "string" },
3903
+ reportRedundant: { type: "boolean" },
3904
+ allow: {
3905
+ type: "array",
3906
+ items: { oneOf: [{ type: "string" }, {
3907
+ type: "array",
3908
+ items: { type: "string" },
3909
+ minItems: 2,
3910
+ maxItems: 2
3911
+ }] }
3912
+ }
3913
+ },
2760
3914
  additionalProperties: false
2761
3915
  }],
2762
- defaultOptions: [{}],
3916
+ defaultOptions: [{ reportRedundant: true }],
2763
3917
  messages: {
2764
- conflict: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
3918
+ conflict: "\"{{winner}}\" overrides \"{{loser}}\" on {{properties}}. \"{{winner}}\" comes later in the generated stylesheet, so it wins no matter how the class attribute is ordered. Remove one.",
3919
+ conflictUnordered: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
3920
+ redundant: "\"{{loser}}\" has no effect: \"{{winner}}\" declares {{properties}} with the same value. Remove \"{{loser}}\".",
2765
3921
  ...DS_UNAVAILABLE_MESSAGE
2766
3922
  }
2767
3923
  },
2768
3924
  createOnce(context) {
2769
3925
  const getDS = createLazyLoader(context);
3926
+ const getOptions = createLazyOptions(context, (o) => ({
3927
+ reportRedundant: o?.reportRedundant ?? true,
3928
+ ...compileAllow(o?.allow)
3929
+ }));
2770
3930
  function check(locations) {
2771
3931
  if (locations.length === 0) return;
2772
3932
  const ds = safeGetDS(getDS, context, locations[0].node);
2773
3933
  if (!ds) return;
2774
3934
  const { cache } = ds;
3935
+ const { reportRedundant, allowClasses, allowPairs } = getOptions();
2775
3936
  for (const loc of locations) {
2776
3937
  const classes = splitClasses(loc.value);
2777
3938
  if (classes.length < 2) continue;
@@ -2784,34 +3945,73 @@ const noConflictingClasses = defineRule({
2784
3945
  }
2785
3946
  for (const [, variantClasses] of byVariant) {
2786
3947
  if (variantClasses.length < 2) continue;
2787
- const propsMap = /* @__PURE__ */ new Map();
2788
- for (const cls of variantClasses) {
2789
- const props = cache.getCssProperties(splitImportant(extractUtility(cls)).bare);
2790
- propsMap.set(cls, props);
2791
- }
2792
- for (let i = 0; i < variantClasses.length; i++) {
2793
- const classA = variantClasses[i];
2794
- const propsA = propsMap.get(classA) ?? [];
2795
- for (let j = i + 1; j < variantClasses.length; j++) {
2796
- const classB = variantClasses[j];
2797
- if (classA === classB) continue;
2798
- const propsB = propsMap.get(classB) ?? [];
2799
- if (shouldSkipPair(classA, classB, propsA, propsB)) continue;
2800
- const propsBSet = new Set(propsB);
2801
- const overlap = propsA.filter((p) => propsBSet.has(p));
2802
- if (overlap.length > 0) {
2803
- const propList = overlap.length <= 3 ? `"${overlap.join("\", \"")}"` : `${overlap.length} CSS properties`;
2804
- context.report({
2805
- node: loc.node,
2806
- messageId: "conflict",
2807
- data: {
2808
- classA,
2809
- classB,
2810
- properties: propList
2811
- }
2812
- });
2813
- }
3948
+ 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);
3950
+ const facts = variantClasses.map((cls) => {
3951
+ const utility = extractUtility(cls);
3952
+ const bare = splitImportant(utility).bare;
3953
+ const declarations = cache.getCssDeclarations(bare);
3954
+ const decls = /* @__PURE__ */ new Map();
3955
+ const writes = /* @__PURE__ */ new Map();
3956
+ const ambiguousKeys = /* @__PURE__ */ new Set();
3957
+ for (const decl of declarations) {
3958
+ if (decl.conditional) continue;
3959
+ const key = declKey(decl);
3960
+ const previous = decls.get(key);
3961
+ if (previous && previous.valueId !== decl.valueId) ambiguousKeys.add(key);
3962
+ decls.set(key, decl);
3963
+ if (decl.prop.startsWith("--")) writes.set(decl.prop, decl.valueId);
3964
+ }
3965
+ return {
3966
+ className: cls,
3967
+ decls,
3968
+ writes,
3969
+ order: cache.hasExactOrder(utility) ? cache.getOrder(cls) : null,
3970
+ important: isImportant(utility),
3971
+ partial: cache.isPartial(bare),
3972
+ ambiguousKeys
3973
+ };
3974
+ });
3975
+ const group = collectFacts(facts);
3976
+ for (let i = 0; i < facts.length; i++) for (let j = i + 1; j < facts.length; j++) {
3977
+ const a = facts[i];
3978
+ const b = facts[j];
3979
+ if (a.className === b.className) continue;
3980
+ if (shouldSkipPair(a.className, b.className)) continue;
3981
+ if (isAllowed(a.className, b.className, allowClasses, allowPairs)) continue;
3982
+ const verdict = decidePair(a, b, group);
3983
+ if (verdict.conflicts.length > 0) {
3984
+ const properties = formatProperties(verdict.conflicts);
3985
+ context.report(verdict.orderKnown ? {
3986
+ node: loc.node,
3987
+ messageId: "conflict",
3988
+ data: {
3989
+ winner: verdict.winner.className,
3990
+ loser: verdict.loser.className,
3991
+ properties
3992
+ }
3993
+ } : {
3994
+ node: loc.node,
3995
+ messageId: "conflictUnordered",
3996
+ data: {
3997
+ classA: a.className,
3998
+ classB: b.className,
3999
+ properties
4000
+ }
4001
+ });
4002
+ continue;
2814
4003
  }
4004
+ if (!reportRedundant) continue;
4005
+ const dead = redundantSide(verdict);
4006
+ if (dead) context.report({
4007
+ node: loc.node,
4008
+ messageId: "redundant",
4009
+ data: {
4010
+ loser: dead.loser.className,
4011
+ winner: dead.winner.className,
4012
+ properties: formatProperties(verdict.duplicates)
4013
+ }
4014
+ });
2815
4015
  }
2816
4016
  }
2817
4017
  }
@@ -2820,226 +4020,155 @@ const noConflictingClasses = defineRule({
2820
4020
  }
2821
4021
  });
2822
4022
  //#endregion
2823
- //#region src/design-system/ds-worker.ts
4023
+ //#region src/utils/report.ts
2824
4024
  /**
2825
- * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
4025
+ * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
2826
4026
  *
2827
- * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
2828
- * (~500 LOC) — both spawned a worker that loaded the design system, then served
2829
- * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
2830
- * real difference was the body of the request loop: `getClassOrder` vs
2831
- * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
2832
- * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
2833
- * service shrinks to ~40 LOC of singleton + public signature.
4027
+ * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
4028
+ * enforce-consistent-variable-syntax, enforce-consistent-important-position,
4029
+ * enforce-negative-arbitrary-values, no-deprecated-classes,
4030
+ * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
4031
+ * replacements via the same shape:
2834
4032
  *
2835
- * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
2836
- * of the process (per cssPath) so subsequent calls don't pay another
2837
- * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
2838
- * single `designSystemUnavailable` diagnostic.
4033
+ * 1. Collect `{ cls, replacement }` entries from a class string.
4034
+ * 2. Rebuild the full class string with replacements applied.
4035
+ * 3. Emit ONE diagnostic with the autofix attached.
4036
+ * 4. Emit one MORE diagnostic per remaining offender, each carrying
4037
+ * the same autofix as a `suggest`.
4038
+ *
4039
+ * oxlint's fixer is single-shot per AST node, so multiple offenders in the
4040
+ * same class string can only get one mechanical fix; the rest stay as
4041
+ * suggestions the IDE can offer interactively.
2839
4042
  */
2840
- const BUFFER_SIZE = 4 * 1024 * 1024;
2841
- const HEADER_INTS = 4;
2842
- const LENGTH_OFFSET = HEADER_INTS * 4;
2843
- const DATA_OFFSET = 20;
2844
- const INIT_TIMEOUT = 6e4;
2845
- const REQUEST_TIMEOUT = 3e4;
2846
4043
  /**
2847
- * Build the worker script shared by `sort-service` and `canonicalize-service`.
2848
- * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
2849
- * constants the host uses, so they can't drift), the design-system load with
2850
- * error propagation (DS-M4: the real cause is written into the buffer so the
2851
- * host can surface it, not a generic "failed to load"), the ready signal, and
2852
- * the request loop. `handlerExpr` is a function expression `(ds, request) =>
2853
- * result` — the only part that differs between services.
4044
+ * Emit autofix + suggestion diagnostics for a list of class replacements.
4045
+ *
4046
+ * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
4047
+ * across all diagnostics — the first one is the primary fix, the rest carry
4048
+ * the same fix as a suggestion (oxlint can only apply one autofix per node).
2854
4049
  */
2855
- function makeWorkerScript(handlerExpr) {
2856
- return `
2857
- const { workerData } = require('worker_threads');
2858
- async function main() {
2859
- const { sharedBuffer, cssPath } = workerData;
2860
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2861
- const lengthView = new DataView(sharedBuffer, ${LENGTH_OFFSET}, 4);
2862
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2863
-
2864
- // On load failure, write the real cause into the data region so the host can
2865
- // report it instead of a bare "failed to load the design system".
2866
- function signalLoadError(e) {
2867
- try {
2868
- const msg = Buffer.from(String((e && e.message) || e || 'unknown design-system load error'), 'utf-8');
2869
- const n = Math.min(msg.length, dataArea.length);
2870
- dataArea.set(msg.subarray(0, n), 0);
2871
- lengthView.setUint32(0, n);
2872
- } catch {}
2873
- Atomics.store(control, 2, -1);
2874
- Atomics.notify(control, 2);
2875
- }
2876
-
2877
- let ds;
2878
- try {
2879
- const { __unstable__loadDesignSystem } = require(workerData.tailwindNodePath);
2880
- const { readFileSync } = require('fs');
2881
- const { dirname } = require('path');
2882
- const css = readFileSync(cssPath, 'utf-8');
2883
- ds = await __unstable__loadDesignSystem(css, { base: dirname(cssPath) });
2884
- } catch (e) {
2885
- signalLoadError(e);
2886
- return;
2887
- }
2888
-
2889
- Atomics.store(control, 2, 1);
2890
- Atomics.notify(control, 2);
2891
-
2892
- const handler = ${handlerExpr};
2893
-
2894
- while (true) {
2895
- Atomics.wait(control, 0, 0);
2896
- const len = lengthView.getUint32(0);
2897
- const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2898
- Atomics.store(control, 0, 0);
2899
-
2900
- let response;
2901
- try {
2902
- const request = JSON.parse(requestStr);
2903
- const result = handler(ds, request);
2904
- response = Buffer.from(JSON.stringify(result), 'utf-8');
2905
- } catch {
2906
- response = Buffer.from('null', 'utf-8');
2907
- }
2908
-
2909
- // DS-M6: if the response doesn't fit the shared buffer, reply with a
2910
- // sentinel the host reads as a rejected request, instead of letting
2911
- // dataArea.set throw and kill the worker (which would hang the caller
2912
- // until the request timeout and then report a misleading timeout).
2913
- if (response.length > dataArea.length) {
2914
- response = Buffer.from('null', 'utf-8');
2915
- }
2916
-
2917
- dataArea.set(response, 0);
2918
- lengthView.setUint32(0, response.length);
2919
- Atomics.store(control, 1, 1);
2920
- Atomics.notify(control, 1);
2921
- }
2922
- }
2923
- main().catch(() => {});
2924
- `;
2925
- }
2926
- var DesignSystemWorker = class {
2927
- opts;
2928
- ready = null;
2929
- lastError = null;
2930
- lastErrorCssPath = null;
2931
- constructor(opts) {
2932
- this.opts = opts;
2933
- }
2934
- /** Record an error as sticky for `cssPath` and return it for `throw`. */
2935
- remember(cssPath, err) {
2936
- this.lastError = err;
2937
- this.lastErrorCssPath = cssPath;
2938
- return err;
2939
- }
2940
- /**
2941
- * Ensure the worker is running and pointed at `cssPath`. Returns the
2942
- * ready state. Throws `SortServiceError` on any failure (init timeout,
2943
- * spawn error, DS-load error). Sticky: subsequent calls for the same
2944
- * cssPath rethrow without retrying.
2945
- */
2946
- ensure(cssPath) {
2947
- if (this.lastError && this.lastErrorCssPath === cssPath) throw this.lastError;
2948
- if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2949
- if (this.ready) this.cleanup();
2950
- this.lastError = null;
2951
- this.lastErrorCssPath = null;
2952
- if (TAILWIND_NODE_PATH === null) throw this.remember(cssPath, new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run."));
2953
- const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2954
- const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2955
- const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2956
- const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2957
- let worker;
2958
- try {
2959
- worker = new node_worker_threads.Worker(this.opts.workerScript, {
2960
- eval: true,
2961
- workerData: {
2962
- sharedBuffer,
2963
- cssPath,
2964
- tailwindNodePath: TAILWIND_NODE_PATH
2965
- }
2966
- });
2967
- } catch (cause) {
2968
- throw this.remember(cssPath, new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 }));
2969
- }
2970
- worker.unref();
2971
- worker.on("error", (err) => {
2972
- this.lastError = new SortServiceError(`${this.opts.serviceName} worker died: ${err.message}`, "The worker will not be restarted in this process. Restart the lint session.", { cause: err });
2973
- this.lastErrorCssPath = cssPath;
2974
- });
2975
- if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2976
- this.terminateWorker(worker);
2977
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Verify the CSS imports resolve; this can also happen if the machine or CI runner is heavily loaded."));
2978
- }
2979
- if (controlArray[2] === -1) {
2980
- const len = lengthView.getUint32(0);
2981
- const detail = len > 0 ? Buffer.from(dataArea.slice(0, len)).toString("utf-8") : "";
2982
- this.terminateWorker(worker);
2983
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".${detail ? ` ${detail}` : ""}`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid."));
2984
- }
2985
- this.ready = {
2986
- worker,
2987
- controlArray,
2988
- lengthView,
2989
- dataArea,
2990
- cssPath
4050
+ function reportClassReplacements(context, loc, split, classes, offending, options) {
4051
+ if (offending.length === 0) return;
4052
+ const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
4053
+ const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
4054
+ const replacementKey = options.replacementKey ?? "replacement";
4055
+ const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
4056
+ const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4057
+ const report = context.report;
4058
+ for (let i = 0; i < offending.length; i++) {
4059
+ const { cls, replacement } = offending[i];
4060
+ const primaryData = {
4061
+ className: cls,
4062
+ [replacementKey]: replacement
2991
4063
  };
2992
- return this.ready;
4064
+ if (i === 0) report({
4065
+ node: loc.node,
4066
+ messageId: options.messageId,
4067
+ data: primaryData,
4068
+ fix: applyFix
4069
+ });
4070
+ else report({
4071
+ node: loc.node,
4072
+ messageId: options.messageId,
4073
+ data: primaryData,
4074
+ suggest: [{
4075
+ messageId: suggestMessageId,
4076
+ data: {
4077
+ className: cls,
4078
+ replacement
4079
+ },
4080
+ fix: applyFix
4081
+ }]
4082
+ });
2993
4083
  }
2994
- /**
2995
- * Send a request to the worker and synchronously wait for the response.
2996
- * Throws `SortServiceError` on any failure.
2997
- */
2998
- callSync(cssPath, req) {
2999
- const state = this.ensure(cssPath);
3000
- const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
3001
- if (requestBytes.length > BUFFER_SIZE - DATA_OFFSET) throw new SortServiceError(`${this.opts.serviceName} request payload is too large (${requestBytes.length} > ${BUFFER_SIZE - DATA_OFFSET} bytes).`, "This is unexpected with typical class lists; please open an issue.");
3002
- state.dataArea.set(requestBytes, 0);
3003
- state.lengthView.setUint32(0, requestBytes.length);
3004
- Atomics.store(state.controlArray, 0, 1);
3005
- Atomics.notify(state.controlArray, 0);
3006
- if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
3007
- this.cleanup();
3008
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "This is unexpected for typical class lists; please open an issue if it persists."));
3009
- }
3010
- const responseLen = state.lengthView.getUint32(0);
3011
- const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
3012
- Atomics.store(state.controlArray, 1, 0);
3013
- let parsed;
3014
- try {
3015
- parsed = JSON.parse(responseStr);
3016
- } catch (cause) {
3017
- this.cleanup();
3018
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned non-JSON response.`, "This is a bug; please open an issue.", { cause: cause instanceof Error ? cause : void 0 }));
3019
- }
3020
- if (parsed === null) {
3021
- this.cleanup();
3022
- throw this.remember(cssPath, new SortServiceError(`${this.opts.serviceName} worker returned null — the request body was rejected or its response did not fit the buffer.`, "This is a bug; please open an issue with the input that triggered it."));
4084
+ }
4085
+ //#endregion
4086
+ //#region src/utils/replacement.ts
4087
+ /**
4088
+ * Returns a predicate that answers "would this replacement produce CSS?".
4089
+ *
4090
+ * `cache.isValid` is the tolerant validity check, so it accepts arbitrary values
4091
+ * (`foo-[5px]`) it cannot verify. That is the right posture here: a rewrite of an
4092
+ * already-invalid class is `no-unknown-classes`' business, and this guard only
4093
+ * has to stop a rewrite from INTRODUCING an invalid class.
4094
+ */
4095
+ function makeReplacementGuard(cache) {
4096
+ if (!cache) return () => true;
4097
+ return (replacement) => cache.isValid(replacement);
4098
+ }
4099
+ //#endregion
4100
+ //#region src/rules/no-deprecated-classes.ts
4101
+ /**
4102
+ * Fallback rename map, for when no design system is available.
4103
+ *
4104
+ * With an `entryPoint` configured the rule uses the map the precompute derives
4105
+ * from `canonicalizeCandidates`, which is strictly better: it covers the renames
4106
+ * this list misses (`break-words`, `order-none`, the reordered
4107
+ * `bg-left-top`/`object-left-top` position spellings) and it prunes itself when a
4108
+ * Tailwind release stops compiling one of them. This table only has to keep the
4109
+ * unconfigured case working exactly as it did.
4110
+ */
4111
+ const DEPRECATED_MAP = {
4112
+ "flex-grow": "grow",
4113
+ "flex-grow-0": "grow-0",
4114
+ "flex-shrink": "shrink",
4115
+ "flex-shrink-0": "shrink-0",
4116
+ "overflow-ellipsis": "text-ellipsis",
4117
+ "decoration-slice": "box-decoration-slice",
4118
+ "decoration-clone": "box-decoration-clone",
4119
+ "bg-gradient-to-t": "bg-linear-to-t",
4120
+ "bg-gradient-to-tr": "bg-linear-to-tr",
4121
+ "bg-gradient-to-r": "bg-linear-to-r",
4122
+ "bg-gradient-to-br": "bg-linear-to-br",
4123
+ "bg-gradient-to-b": "bg-linear-to-b",
4124
+ "bg-gradient-to-bl": "bg-linear-to-bl",
4125
+ "bg-gradient-to-l": "bg-linear-to-l",
4126
+ "bg-gradient-to-tl": "bg-linear-to-tl"
4127
+ };
4128
+ const noDeprecatedClasses = defineRule({
4129
+ meta: {
4130
+ type: "problem",
4131
+ docs: { description: "Disallow deprecated Tailwind CSS v4 classes" },
4132
+ fixable: "code",
4133
+ schema: [{
4134
+ type: "object",
4135
+ properties: { entryPoint: { type: "string" } },
4136
+ additionalProperties: false
4137
+ }],
4138
+ hasSuggestions: true,
4139
+ defaultOptions: [{}],
4140
+ messages: {
4141
+ deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
4142
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3023
4143
  }
3024
- return parsed;
3025
- }
3026
- reset() {
3027
- this.cleanup();
3028
- this.lastError = null;
3029
- this.lastErrorCssPath = null;
3030
- }
3031
- cleanup() {
3032
- if (this.ready) {
3033
- this.terminateWorker(this.ready.worker);
3034
- this.ready = null;
4144
+ },
4145
+ createOnce(context) {
4146
+ const getDS = createLazyLoader(context);
4147
+ function check(locations) {
4148
+ if (locations.length === 0) return;
4149
+ const ds = softGetDS(getDS);
4150
+ const cache = ds ? ds.cache : null;
4151
+ const replacementFor = (bare) => cache?.hasDeprecatedMap ? cache.deprecatedReplacement(bare) : DEPRECATED_MAP[bare] ?? null;
4152
+ const isUsable = makeReplacementGuard(cache);
4153
+ for (const loc of locations) {
4154
+ const split = splitClassesWithSeparators(loc.value);
4155
+ const offending = split.classes.flatMap((cls) => {
4156
+ const { utility, variant } = splitUtilityAndVariant(cls);
4157
+ const { bare: bareUtility, position } = splitImportant(utility);
4158
+ const replacement = replacementFor(bareUtility);
4159
+ if (!replacement) return [];
4160
+ const rebuilt = variant + reattachImportant(replacement, position);
4161
+ return isUsable(rebuilt) ? [{
4162
+ cls,
4163
+ replacement: rebuilt
4164
+ }] : [];
4165
+ });
4166
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
4167
+ }
3035
4168
  }
4169
+ return createExtractorVisitors(context, check);
3036
4170
  }
3037
- terminateWorker(worker) {
3038
- try {
3039
- worker.terminate();
3040
- } catch {}
3041
- }
3042
- };
4171
+ });
3043
4172
  //#endregion
3044
4173
  //#region src/design-system/canonicalize-service.ts
3045
4174
  /**
@@ -3057,23 +4186,195 @@ var DesignSystemWorker = class {
3057
4186
  * after the first few files any given class has been seen, and every
3058
4187
  * subsequent lookup is O(1).
3059
4188
  */
3060
- const canonWorker = new DesignSystemWorker({
3061
- workerScript: makeWorkerScript(`(ds, request) => {
4189
+ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
3062
4190
  const { classes, rem } = request;
3063
4191
  const options = rem ? { rem } : undefined;
4192
+ const declsOf = (cls) => {
4193
+ let out;
4194
+ try { out = ds.candidatesToCss([cls]); } catch (e) { return null; }
4195
+ if (!out || !out[0]) return null;
4196
+ const css = out[0];
4197
+ const open = css.indexOf('{');
4198
+ const close = css.lastIndexOf('}');
4199
+ if (open < 0 || close < 0) return null;
4200
+ return css.slice(open + 1, close).replace(/\\s+/g, ' ').trim();
4201
+ };
3064
4202
  return classes.map((cls) => {
3065
4203
  const r = ds.canonicalizeCandidates([cls], options);
3066
- return r[0] ?? cls;
4204
+ const canonical = r[0] ?? cls;
4205
+ if (canonical === cls) return { canonical: cls, safe: true };
4206
+ const a = declsOf(cls);
4207
+ const b = declsOf(canonical);
4208
+ return { canonical, safe: a !== null && b !== null && a === b };
3067
4209
  });
3068
- }`),
4210
+ }`);
4211
+ const canonWorker = new DesignSystemWorker({
4212
+ workerScript: WORKER_SCRIPT,
3069
4213
  serviceName: "canonicalize"
3070
4214
  });
3071
4215
  /**
3072
- * Process-wide cache of canonicalized classes.
3073
- * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
3074
- * DSs) and different rem settings. Value: canonicalized class string.
4216
+ * Process-wide cache of canonicalized classes.
4217
+ * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
4218
+ * DSs) and different rem settings. Value: the canonical form + its #78 `safe`
4219
+ * flag.
4220
+ */
4221
+ const canonCache = /* @__PURE__ */ new Map();
4222
+ /**
4223
+ * ## Disk persistence (per design system + rem)
4224
+ *
4225
+ * Each `oxlint` invocation is a fresh process, so without persistence every
4226
+ * unique dynamic class (`p-[2px]`, `bg-(--c)`, …) pays a synchronous worker
4227
+ * round-trip again on every run — on arbitrary-value-heavy codebases this
4228
+ * dominates the whole lint (seconds per run, issue: enforce-canonical perf).
4229
+ *
4230
+ * The canonical results are pure functions of the design system + rem + the
4231
+ * canonicalization logic, so we persist them next to the DS precompute
4232
+ * artifact, deriving the filename from `cacheArtifactPaths(cssPath).json`
4233
+ * (content-hash keyed) plus `CANON_LOGIC_HASH` (below). When the DS changes,
4234
+ * the artifact hash changes; when the canonicalization logic changes, the
4235
+ * logic hash changes — either way the canonical cache invalidates with it, so
4236
+ * no manual version bump is needed and stale values can never reach an autofix.
4237
+ *
4238
+ * We persist the full `CanonicalizeResult` (`canonical` + the #78 `safe`
4239
+ * flag), not just the string: `safe` gates whether `enforce-canonical`
4240
+ * actually applies the rewrite, so dropping it on restore would re-introduce
4241
+ * the unsafe-autofix bug #78 fixed.
4242
+ *
4243
+ * Best-effort everywhere: a missing/corrupt/unwritable cache file must never
4244
+ * break linting — it only costs worker round-trips.
4245
+ */
4246
+ const CANON_LOGIC_HASH = (0, node_crypto.createHash)("md5").update(WORKER_SCRIPT + roundRemValue.toString()).digest("hex").slice(0, 8);
4247
+ let tmpSeq = 0;
4248
+ const LOCK_STALE_MS = 1e4;
4249
+ /** One persistence state per `${cssPath}\0${rem}\0` cache prefix. */
4250
+ const persistStates = /* @__PURE__ */ new Map();
4251
+ function tryUnlink(path) {
4252
+ try {
4253
+ (0, node_fs.unlinkSync)(path);
4254
+ } catch {}
4255
+ }
4256
+ /**
4257
+ * Reclaim a stale lock via exclusive rename rather than unlink (mirrors
4258
+ * sync-loader.ts): two isolates that both judge the lock stale would otherwise
4259
+ * both unlink it, and the second could delete a FRESH lock a third isolate just
4260
+ * created. `renameSync` has a single winner; the loser gets ENOENT and moves on.
4261
+ */
4262
+ function reclaimStaleLock(lockPath) {
4263
+ let ageMs;
4264
+ try {
4265
+ ageMs = Date.now() - (0, node_fs.statSync)(lockPath).mtimeMs;
4266
+ } catch {
4267
+ return;
4268
+ }
4269
+ if (ageMs < LOCK_STALE_MS) return;
4270
+ const reclaimPath = `${lockPath}.reclaim.${process.pid}.${node_worker_threads.threadId}.${tmpSeq++}`;
4271
+ try {
4272
+ (0, node_fs.renameSync)(lockPath, reclaimPath);
4273
+ } catch {
4274
+ return;
4275
+ }
4276
+ tryUnlink(reclaimPath);
4277
+ }
4278
+ /**
4279
+ * Acquire the per-file flush lock by atomic exclusive create (`wx`). The lock
4280
+ * serializes the read-merge-write below so concurrent isolates don't clobber
4281
+ * each other's entries (last-writer-wins → the cache would otherwise only
4282
+ * converge over several runs). Distinguishes contention (another isolate is
4283
+ * mid-flush — skip and retry next threshold) from an unwritable dir (give up).
4284
+ */
4285
+ function acquireFlushLock(lockPath) {
4286
+ const tryCreate = () => {
4287
+ try {
4288
+ (0, node_fs.closeSync)((0, node_fs.openSync)(lockPath, "wx"));
4289
+ return "acquired";
4290
+ } catch (e) {
4291
+ return e.code === "EEXIST" ? "contended" : "unavailable";
4292
+ }
4293
+ };
4294
+ const first = tryCreate();
4295
+ if (first !== "contended") return first;
4296
+ reclaimStaleLock(lockPath);
4297
+ return tryCreate();
4298
+ }
4299
+ /** Exported for tests: the exact on-disk cache path for a (cssPath, rem). */
4300
+ function persistFileFor(cssPath, rem) {
4301
+ try {
4302
+ const { json } = cacheArtifactPaths(cssPath);
4303
+ const remKey = rem === void 0 ? "default" : String(rem);
4304
+ return json.replace(/\.json$/, `.canon-${CANON_LOGIC_HASH}-${remKey}.json`);
4305
+ } catch {
4306
+ return null;
4307
+ }
4308
+ }
4309
+ /** Load the persisted map (if any) into `canonCache`, and set up flushing. */
4310
+ function ensurePersistLoaded(cssPath, rem, cachePrefix) {
4311
+ if (persistStates.has(cachePrefix)) return;
4312
+ const file = persistFileFor(cssPath, rem);
4313
+ if (file === null) {
4314
+ persistStates.set(cachePrefix, {
4315
+ file: "",
4316
+ dirty: -1
4317
+ });
4318
+ return;
4319
+ }
4320
+ const state = {
4321
+ file,
4322
+ dirty: 0
4323
+ };
4324
+ persistStates.set(cachePrefix, state);
4325
+ try {
4326
+ const data = JSON.parse((0, node_fs.readFileSync)(file, "utf-8"));
4327
+ if (typeof data === "object" && data !== null) {
4328
+ for (const [cls, entry] of Object.entries(data)) if (Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "boolean") canonCache.set(cachePrefix + cls, {
4329
+ canonical: entry[0],
4330
+ safe: entry[1]
4331
+ });
4332
+ }
4333
+ } catch {}
4334
+ }
4335
+ /**
4336
+ * Persist this prefix's entries under a per-file lock, merging with whatever is
4337
+ * already on disk first. oxlint worker threads are separate JS isolates, each
4338
+ * with its own in-memory `canonCache`, so the file is their shared channel: a
4339
+ * bare overwrite would clobber the entries other isolates persisted
4340
+ * (last-writer-wins), leaving the cache to converge only over several runs.
4341
+ * Read-merge-write under the lock makes it converge in one.
3075
4342
  */
3076
- const canonCache = /* @__PURE__ */ new Map();
4343
+ function flushPersist(cachePrefix, state) {
4344
+ if (state.dirty <= 0) return;
4345
+ const lockPath = `${state.file}.lock`;
4346
+ const lock = acquireFlushLock(lockPath);
4347
+ if (lock === "contended") return;
4348
+ if (lock === "unavailable") {
4349
+ state.dirty = -1;
4350
+ return;
4351
+ }
4352
+ try {
4353
+ const merged = Object.create(null);
4354
+ try {
4355
+ const existing = JSON.parse((0, node_fs.readFileSync)(state.file, "utf-8"));
4356
+ if (typeof existing === "object" && existing !== null) {
4357
+ for (const [cls, entry] of Object.entries(existing)) if (Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "boolean") {
4358
+ merged[cls] = [entry[0], entry[1]];
4359
+ const key = cachePrefix + cls;
4360
+ if (!canonCache.has(key)) canonCache.set(key, {
4361
+ canonical: entry[0],
4362
+ safe: entry[1]
4363
+ });
4364
+ }
4365
+ }
4366
+ } catch {}
4367
+ for (const [key, value] of canonCache) if (key.startsWith(cachePrefix)) merged[key.slice(cachePrefix.length)] = [value.canonical, value.safe];
4368
+ const tmp = `${state.file}.${process.pid}.${node_worker_threads.threadId}.${tmpSeq++}.tmp`;
4369
+ (0, node_fs.writeFileSync)(tmp, JSON.stringify(merged));
4370
+ (0, node_fs.renameSync)(tmp, state.file);
4371
+ state.dirty = 0;
4372
+ } catch {
4373
+ state.dirty = -1;
4374
+ } finally {
4375
+ tryUnlink(lockPath);
4376
+ }
4377
+ }
3077
4378
  /**
3078
4379
  * Canonicalize classes via the worker thread.
3079
4380
  *
@@ -3090,6 +4391,7 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
3090
4391
  const missingIdx = [];
3091
4392
  const missing = [];
3092
4393
  const cachePrefix = `${cssPath}\0${rem ?? ""}\0`;
4394
+ ensurePersistLoaded(cssPath, rem, cachePrefix);
3093
4395
  for (let i = 0; i < classes.length; i++) {
3094
4396
  const key = cachePrefix + classes[i];
3095
4397
  const hit = canonCache.get(key);
@@ -3110,10 +4412,22 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
3110
4412
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
3111
4413
  for (let j = 0; j < missing.length; j++) {
3112
4414
  const cls = missing[j];
3113
- const value = roundRemValue(freshByClass.get(cls) ?? cls);
4415
+ const raw = freshByClass.get(cls) ?? {
4416
+ canonical: cls,
4417
+ safe: true
4418
+ };
4419
+ const value = {
4420
+ canonical: roundRemValue(raw.canonical),
4421
+ safe: raw.safe
4422
+ };
3114
4423
  canonCache.set(cachePrefix + cls, value);
3115
4424
  out[missingIdx[j]] = value;
3116
4425
  }
4426
+ const state = persistStates.get(cachePrefix);
4427
+ if (state && state.dirty >= 0) {
4428
+ state.dirty += uniqueMissing.length;
4429
+ flushPersist(cachePrefix, state);
4430
+ }
3117
4431
  return out;
3118
4432
  }
3119
4433
  //#endregion
@@ -3170,15 +4484,25 @@ const enforceCanonical = defineRule({
3170
4484
  const canonicals = Array.from({ length: classes.length });
3171
4485
  const arbitraryIdx = [];
3172
4486
  const arbitrary = [];
3173
- for (let i = 0; i < classes.length; i++) if (utilityHasDynamicValue(classes[i])) {
3174
- arbitraryIdx.push(i);
3175
- arbitrary.push(classes[i]);
3176
- } else canonicals[i] = cache.canonicalize(classes[i]);
4487
+ for (let i = 0; i < classes.length; i++) {
4488
+ const { utility } = splitUtilityAndVariant(classes[i]);
4489
+ if (cache.deprecatedReplacement(splitImportant(utility).bare)) {
4490
+ canonicals[i] = classes[i];
4491
+ continue;
4492
+ }
4493
+ if (utilityHasDynamicValue(classes[i])) {
4494
+ arbitraryIdx.push(i);
4495
+ arbitrary.push(classes[i]);
4496
+ } else canonicals[i] = cache.canonicalize(classes[i]);
4497
+ }
3177
4498
  if (arbitrary.length > 0) {
3178
4499
  const rem = getRem();
3179
4500
  const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
3180
4501
  if (!dynamic) return;
3181
- for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
4502
+ for (let k = 0; k < arbitrary.length; k++) {
4503
+ const { canonical, safe } = dynamic[k];
4504
+ canonicals[arbitraryIdx[k]] = safe ? preserveImportantPosition(arbitrary[k], canonical) : arbitrary[k];
4505
+ }
3182
4506
  }
3183
4507
  reportClassReplacements(context, loc, split, classes, classes.flatMap((cls, i) => canonicals[i] === cls ? [] : [{
3184
4508
  cls,
@@ -3320,121 +4644,317 @@ const enforceSortOrder = defineRule({
3320
4644
  });
3321
4645
  //#endregion
3322
4646
  //#region src/rules/enforce-shorthand.ts
3323
- const VALUE_RE = /^(?:m[trbl]|mx|my|p[trbl]|px|py|[wh]|rounded-t[lr]|rounded-b[lr]|min-[wh]|max-[wh])-(.+)$/;
3324
- const INVALID_SIZE_VALUES = /* @__PURE__ */ new Set([
3325
- "screen",
3326
- "dvw",
3327
- "dvh",
3328
- "svw",
3329
- "svh",
3330
- "lvw",
3331
- "lvh"
3332
- ]);
3333
4647
  /**
3334
- * Generates shorthand rules parameterized by value.
3335
- * E.g.: mt-2 + mr-2 + mb-2 + ml-2 -> m-2
4648
+ * The `m`/`p` shape, shared by `margin`, `padding`, `scroll-margin` and
4649
+ * `scroll-padding`: four sides, each axis, and the logical inline pair (`ms`+`me`
4650
+ * IS `margin-inline`, so that one is property-identical rather than merely
4651
+ * equivalent).
3336
4652
  */
3337
- function createShorthandRules(value) {
4653
+ function boxFamilies(p) {
3338
4654
  return [
3339
4655
  {
3340
4656
  parts: [
3341
- `mt-${value}`,
3342
- `mr-${value}`,
3343
- `mb-${value}`,
3344
- `ml-${value}`
3345
- ],
3346
- replacement: `m-${value}`
3347
- },
3348
- {
3349
- parts: [`mt-${value}`, `mb-${value}`],
3350
- replacement: `my-${value}`
3351
- },
3352
- {
3353
- parts: [`ml-${value}`, `mr-${value}`],
3354
- replacement: `mx-${value}`
3355
- },
3356
- {
3357
- parts: [`mx-${value}`, `my-${value}`],
3358
- replacement: `m-${value}`
3359
- },
3360
- {
3361
- parts: [
3362
- `pt-${value}`,
3363
- `pr-${value}`,
3364
- `pb-${value}`,
3365
- `pl-${value}`
4657
+ `${p}t`,
4658
+ `${p}r`,
4659
+ `${p}b`,
4660
+ `${p}l`
3366
4661
  ],
3367
- replacement: `p-${value}`
4662
+ to: p
3368
4663
  },
3369
4664
  {
3370
- parts: [`pt-${value}`, `pb-${value}`],
3371
- replacement: `py-${value}`
4665
+ parts: [`${p}t`, `${p}b`],
4666
+ to: `${p}y`
3372
4667
  },
3373
4668
  {
3374
- parts: [`pl-${value}`, `pr-${value}`],
3375
- replacement: `px-${value}`
4669
+ parts: [`${p}l`, `${p}r`],
4670
+ to: `${p}x`
3376
4671
  },
3377
4672
  {
3378
- parts: [`px-${value}`, `py-${value}`],
3379
- replacement: `p-${value}`
4673
+ parts: [`${p}s`, `${p}e`],
4674
+ to: `${p}x`
3380
4675
  },
3381
- ...!INVALID_SIZE_VALUES.has(value) ? [{
3382
- parts: [`w-${value}`, `h-${value}`],
3383
- replacement: `size-${value}`
3384
- }] : [],
3385
4676
  {
3386
- parts: [
3387
- `rounded-tl-${value}`,
3388
- `rounded-tr-${value}`,
3389
- `rounded-br-${value}`,
3390
- `rounded-bl-${value}`
3391
- ],
3392
- replacement: `rounded-${value}`
4677
+ parts: [`${p}x`, `${p}y`],
4678
+ to: p
3393
4679
  }
3394
4680
  ];
3395
4681
  }
4682
+ const SHORTHAND_FAMILIES = [
4683
+ ...boxFamilies("m"),
4684
+ ...boxFamilies("p"),
4685
+ ...boxFamilies("scroll-m"),
4686
+ ...boxFamilies("scroll-p"),
4687
+ {
4688
+ parts: ["w", "h"],
4689
+ to: "size",
4690
+ perAxisNamespaces: true
4691
+ },
4692
+ {
4693
+ parts: [
4694
+ "rounded-tl",
4695
+ "rounded-tr",
4696
+ "rounded-br",
4697
+ "rounded-bl"
4698
+ ],
4699
+ to: "rounded"
4700
+ },
4701
+ {
4702
+ parts: [
4703
+ "rounded-ss",
4704
+ "rounded-se",
4705
+ "rounded-ee",
4706
+ "rounded-es"
4707
+ ],
4708
+ to: "rounded"
4709
+ },
4710
+ {
4711
+ parts: ["rounded-tl", "rounded-tr"],
4712
+ to: "rounded-t"
4713
+ },
4714
+ {
4715
+ parts: ["rounded-bl", "rounded-br"],
4716
+ to: "rounded-b"
4717
+ },
4718
+ {
4719
+ parts: ["rounded-tl", "rounded-bl"],
4720
+ to: "rounded-l"
4721
+ },
4722
+ {
4723
+ parts: ["rounded-tr", "rounded-br"],
4724
+ to: "rounded-r"
4725
+ },
4726
+ {
4727
+ parts: ["rounded-ss", "rounded-es"],
4728
+ to: "rounded-s"
4729
+ },
4730
+ {
4731
+ parts: ["rounded-se", "rounded-ee"],
4732
+ to: "rounded-e"
4733
+ },
4734
+ {
4735
+ parts: ["rounded-t", "rounded-b"],
4736
+ to: "rounded"
4737
+ },
4738
+ {
4739
+ parts: ["rounded-l", "rounded-r"],
4740
+ to: "rounded"
4741
+ },
4742
+ {
4743
+ parts: ["rounded-s", "rounded-e"],
4744
+ to: "rounded"
4745
+ },
4746
+ {
4747
+ parts: [
4748
+ "border-t",
4749
+ "border-r",
4750
+ "border-b",
4751
+ "border-l"
4752
+ ],
4753
+ to: "border"
4754
+ },
4755
+ {
4756
+ parts: ["border-t", "border-b"],
4757
+ to: "border-y"
4758
+ },
4759
+ {
4760
+ parts: ["border-l", "border-r"],
4761
+ to: "border-x"
4762
+ },
4763
+ {
4764
+ parts: ["border-s", "border-e"],
4765
+ to: "border-x"
4766
+ },
4767
+ {
4768
+ parts: ["border-x", "border-y"],
4769
+ to: "border"
4770
+ },
4771
+ {
4772
+ parts: [
4773
+ "top",
4774
+ "right",
4775
+ "bottom",
4776
+ "left"
4777
+ ],
4778
+ to: "inset"
4779
+ },
4780
+ {
4781
+ parts: ["top", "bottom"],
4782
+ to: "inset-y"
4783
+ },
4784
+ {
4785
+ parts: ["left", "right"],
4786
+ to: "inset-x"
4787
+ },
4788
+ {
4789
+ parts: ["start", "end"],
4790
+ to: "inset-x"
4791
+ },
4792
+ {
4793
+ parts: ["inset-x", "inset-y"],
4794
+ to: "inset"
4795
+ },
4796
+ {
4797
+ parts: ["gap-x", "gap-y"],
4798
+ to: "gap"
4799
+ },
4800
+ {
4801
+ parts: ["overflow-x", "overflow-y"],
4802
+ to: "overflow"
4803
+ },
4804
+ {
4805
+ parts: ["overscroll-x", "overscroll-y"],
4806
+ to: "overscroll"
4807
+ },
4808
+ {
4809
+ parts: ["border-spacing-x", "border-spacing-y"],
4810
+ to: "border-spacing"
4811
+ },
4812
+ {
4813
+ parts: ["translate-x", "translate-y"],
4814
+ to: "translate"
4815
+ }
4816
+ ];
4817
+ /**
4818
+ * Largest merges first, so four sides collapse to `m-2` instead of also
4819
+ * reporting the `my-2`/`mx-2` halves — three diagnostics for one problem, which
4820
+ * is what this rule used to emit. `sort` is stable, so same-size families keep
4821
+ * their declaration order and the choice stays deterministic.
4822
+ */
4823
+ const FAMILIES_BY_SIZE = [...SHORTHAND_FAMILIES].sort((a, b) => b.parts.length - a.parts.length);
4824
+ /**
4825
+ * `^<part>-<value>$`, longest prefix first so `rounded-tl-lg` is read as
4826
+ * `rounded-tl` + `lg` and never as `rounded-t` + `l-lg`.
4827
+ */
4828
+ const VALUE_RE = (() => {
4829
+ const prefixes = [...new Set(SHORTHAND_FAMILIES.flatMap((f) => f.parts))].sort((a, b) => b.length - a.length);
4830
+ return new RegExp(`^(${prefixes.join("|")})-(.+)$`);
4831
+ })();
4832
+ /** A plain number or fraction: always the shared numeric/`--spacing` scale. */
4833
+ const NUMERIC_VALUE_RE = /^\d+(?:\.\d+)?(?:\/\d+(?:\.\d+)?)?$/;
4834
+ /**
4835
+ * Core keywords whose per-axis forms are known to agree, for when no design
4836
+ * system is available to check. Deliberately excludes `screen` (`w-screen` is
4837
+ * `100vw`, `h-screen` is `100vh`) and every named theme token, which is the case
4838
+ * that can only be settled by looking at the emitted CSS.
4839
+ */
4840
+ const AXIS_SAFE_KEYWORDS = /* @__PURE__ */ new Set([
4841
+ "full",
4842
+ "auto",
4843
+ "min",
4844
+ "max",
4845
+ "fit",
4846
+ "px",
4847
+ "dvw",
4848
+ "dvh",
4849
+ "lvw",
4850
+ "lvh",
4851
+ "svw",
4852
+ "svh"
4853
+ ]);
4854
+ /** The value is a literal the user wrote, injected verbatim into every part. */
4855
+ function isWrittenValue(value) {
4856
+ return value.startsWith("[") || value.startsWith("(");
4857
+ }
4858
+ /**
4859
+ * Values the class declares on its own box, unconditionally. `null` when the
4860
+ * class produces nothing — which for a named token means it does not exist.
4861
+ */
4862
+ function declaredValues(cache, cls) {
4863
+ const values = /* @__PURE__ */ new Set();
4864
+ for (const decl of cache.getCssDeclarations(cls)) {
4865
+ if (decl.conditional) continue;
4866
+ values.add(decl.value);
4867
+ }
4868
+ return values.size > 0 ? values : null;
4869
+ }
4870
+ function sameValues(a, b) {
4871
+ if (a.size !== b.size) return false;
4872
+ for (const value of a) if (!b.has(value)) return false;
4873
+ return true;
4874
+ }
4875
+ /**
4876
+ * Would collapsing this family at this value keep the CSS identical?
4877
+ *
4878
+ * With a design system this is answered from the emitted declarations. Without
4879
+ * one it falls back to what is safe by construction, which is everything except
4880
+ * a named token on the one family whose parts read different namespaces.
4881
+ */
4882
+ function mergeIsSafe(family, value, cache) {
4883
+ const structurallySafe = NUMERIC_VALUE_RE.test(value) || isWrittenValue(value);
4884
+ if (!cache) {
4885
+ if (!family.perAxisNamespaces) return true;
4886
+ return structurallySafe || AXIS_SAFE_KEYWORDS.has(value);
4887
+ }
4888
+ if (!cache.isValid(`${family.to}-${value}`)) return false;
4889
+ if (structurallySafe) return true;
4890
+ const expected = declaredValues(cache, `${family.parts[0]}-${value}`);
4891
+ if (!expected) return false;
4892
+ for (let i = 1; i < family.parts.length; i++) {
4893
+ const actual = declaredValues(cache, `${family.parts[i]}-${value}`);
4894
+ if (!actual || !sameValues(expected, actual)) return false;
4895
+ }
4896
+ const replacement = declaredValues(cache, `${family.to}-${value}`);
4897
+ return replacement !== null && sameValues(expected, replacement);
4898
+ }
3396
4899
  const enforceShorthand = defineRule({
3397
4900
  meta: {
3398
4901
  type: "suggestion",
3399
4902
  docs: { description: "Enforce shorthand Tailwind CSS classes when all axes have the same value" },
3400
4903
  fixable: "code",
3401
- schema: [],
4904
+ schema: [{
4905
+ type: "object",
4906
+ properties: { entryPoint: { type: "string" } },
4907
+ additionalProperties: false
4908
+ }],
4909
+ defaultOptions: [{}],
3402
4910
  messages: { shorthand: "{{parts}} can be simplified to \"{{replacement}}\"." }
3403
4911
  },
3404
4912
  createOnce(context) {
4913
+ const getDS = createLazyLoader(context);
3405
4914
  function check(locations) {
4915
+ const ds = softGetDS(getDS);
4916
+ const cache = ds ? ds.cache : null;
3406
4917
  for (const loc of locations) {
3407
4918
  const split = splitClassesWithSeparators(loc.value);
3408
4919
  const classes = split.classes;
3409
4920
  if (classes.length < 2) continue;
3410
- const classSet = new Set(classes);
3411
- const variantValues = /* @__PURE__ */ new Set();
4921
+ const groups = /* @__PURE__ */ new Map();
3412
4922
  for (const cls of classes) {
3413
4923
  const { utility, variant } = splitUtilityAndVariant(cls);
3414
- const match = VALUE_RE.exec(splitImportant(utility).bare);
3415
- if (match) variantValues.add(`${variant}\0${match[1]}`);
4924
+ const { bare, position } = splitImportant(utility);
4925
+ const match = VALUE_RE.exec(bare);
4926
+ if (!match) continue;
4927
+ const [, part, value] = match;
4928
+ const key = `${variant}\0${position ?? ""}\0${value}`;
4929
+ let group = groups.get(key);
4930
+ if (!group) {
4931
+ group = {
4932
+ variant,
4933
+ position,
4934
+ value,
4935
+ byPart: /* @__PURE__ */ new Map()
4936
+ };
4937
+ groups.set(key, group);
4938
+ }
4939
+ group.byPart.set(part, cls);
3416
4940
  }
3417
- for (const variantValue of variantValues) {
3418
- const nul = variantValue.indexOf("\0");
3419
- const variant = variantValue.slice(0, nul);
3420
- const rules = createShorthandRules(variantValue.slice(nul + 1));
3421
- for (const rule of rules) {
3422
- const withVariant = (p) => `${variant}${p}`;
3423
- const hasImportantPrefix = rule.parts.every((p) => classSet.has(withVariant(`!${p}`)));
3424
- const hasImportantSuffix = !hasImportantPrefix && rule.parts.every((p) => classSet.has(withVariant(`${p}!`)));
3425
- const hasPlain = rule.parts.every((p) => classSet.has(withVariant(p)));
3426
- if (!hasImportantPrefix && !hasImportantSuffix && !hasPlain) continue;
3427
- const importantStart = hasImportantPrefix ? "!" : "";
3428
- const importantEnd = hasImportantSuffix ? "!" : "";
3429
- const matchParts = rule.parts.map((p) => withVariant(`${importantStart}${p}${importantEnd}`));
3430
- const remaining = classes.filter((c) => !matchParts.includes(c));
3431
- remaining.push(withVariant(`${importantStart}${rule.replacement}${importantEnd}`));
4941
+ for (const group of groups.values()) {
4942
+ if (group.byPart.size < 2) continue;
4943
+ const consumed = /* @__PURE__ */ new Set();
4944
+ for (const family of FAMILIES_BY_SIZE) {
4945
+ if (family.parts.some((part) => !group.byPart.has(part) || consumed.has(part))) continue;
4946
+ if (!mergeIsSafe(family, group.value, cache)) continue;
4947
+ const matched = family.parts.map((part) => group.byPart.get(part));
4948
+ const replacement = group.variant + reattachImportant(`${family.to}-${group.value}`, group.position);
4949
+ const remaining = classes.filter((cls) => !matched.includes(cls));
4950
+ if (!remaining.includes(replacement)) remaining.push(replacement);
4951
+ for (const part of family.parts) consumed.add(part);
3432
4952
  context.report({
3433
4953
  node: loc.node,
3434
4954
  messageId: "shorthand",
3435
4955
  data: {
3436
- parts: matchParts.map((p) => `"${p}"`).join(", "),
3437
- replacement: withVariant(`${importantStart}${rule.replacement}${importantEnd}`)
4956
+ parts: matched.map((p) => `"${p}"`).join(", "),
4957
+ replacement
3438
4958
  },
3439
4959
  fix(fixer) {
3440
4960
  return fixer.replaceTextRange(loc.range, preserveSpaces(loc, rebuildClassString(split, remaining)));
@@ -3463,7 +4983,8 @@ const LOGICAL_PHYSICAL_SCHEMA = {
3463
4983
  "block",
3464
4984
  "both"
3465
4985
  ]
3466
- }
4986
+ },
4987
+ entryPoint: { type: "string" }
3467
4988
  },
3468
4989
  additionalProperties: false
3469
4990
  };
@@ -3557,17 +5078,73 @@ const PHYSICAL_TO_LOGICAL_MAPPINGS = [
3557
5078
  from: "scroll-pr",
3558
5079
  to: "scroll-pe",
3559
5080
  axis: "inline"
5081
+ },
5082
+ {
5083
+ from: "float-left",
5084
+ to: "float-start",
5085
+ axis: "inline",
5086
+ exact: true
5087
+ },
5088
+ {
5089
+ from: "float-right",
5090
+ to: "float-end",
5091
+ axis: "inline",
5092
+ exact: true
5093
+ },
5094
+ {
5095
+ from: "clear-left",
5096
+ to: "clear-start",
5097
+ axis: "inline",
5098
+ exact: true
5099
+ },
5100
+ {
5101
+ from: "clear-right",
5102
+ to: "clear-end",
5103
+ axis: "inline",
5104
+ exact: true
5105
+ },
5106
+ {
5107
+ from: "text-left",
5108
+ to: "text-start",
5109
+ axis: "inline",
5110
+ exact: true
5111
+ },
5112
+ {
5113
+ from: "text-right",
5114
+ to: "text-end",
5115
+ axis: "inline",
5116
+ exact: true
3560
5117
  }
3561
5118
  ];
5119
+ /**
5120
+ * Extra sources for enforce-physical ONLY.
5121
+ *
5122
+ * `enforce-logical` rewrites `left-2` to `start-2`, the spelling Tailwind's own
5123
+ * docs use. `enforce-canonical`, asking the design system, then rewrites that to
5124
+ * `inset-s-2` — same CSS, canonical name. So a codebase that ran both ends up with
5125
+ * `inset-s-*`, and enforce-physical had no way back: its table only knew `start`.
5126
+ *
5127
+ * Kept out of the main table so inverting it doesn't change what enforce-logical
5128
+ * suggests (both spellings map to the same physical class, but only one of them
5129
+ * can be the recommendation).
5130
+ */
5131
+ const LOGICAL_INSET_ALIASES = [{
5132
+ from: "inset-s",
5133
+ to: "left",
5134
+ axis: "inline"
5135
+ }, {
5136
+ from: "inset-e",
5137
+ to: "right",
5138
+ axis: "inline"
5139
+ }];
3562
5140
  /** Invert a directional table. enforce-physical consumes this. */
3563
5141
  function invertAxisMappings(mappings) {
3564
5142
  return mappings.map((m) => ({
5143
+ ...m,
3565
5144
  from: m.to,
3566
- to: m.from,
3567
- axis: m.axis
5145
+ to: m.from
3568
5146
  }));
3569
5147
  }
3570
- Object.fromEntries(PHYSICAL_TO_LOGICAL_MAPPINGS.map((m) => [m.from, m.to]));
3571
5148
  /**
3572
5149
  * Build the `check` callback for a directional-rewrite rule. Both
3573
5150
  * enforce-logical and enforce-physical instantiate this with their own
@@ -3583,6 +5160,7 @@ function createDirectionalMapper(context, opts) {
3583
5160
  allowlist: compileRegexList(o?.allowlist),
3584
5161
  direction: o?.direction ?? "both"
3585
5162
  }));
5163
+ const getDS = createLazyLoader(context);
3586
5164
  function convertClass(cls) {
3587
5165
  const { allowlist, direction } = getState();
3588
5166
  if (matchesAny(cls, allowlist)) return null;
@@ -3590,24 +5168,26 @@ function createDirectionalMapper(context, opts) {
3590
5168
  const { bare: bareUtility, position } = splitImportant(utility);
3591
5169
  const negative = bareUtility.startsWith("-");
3592
5170
  const core = negative ? bareUtility.slice(1) : bareUtility;
3593
- for (const { from, to, axis } of opts.mappings) {
5171
+ for (const { from, to, axis, exact } of opts.mappings) {
3594
5172
  if (direction !== "both" && direction !== axis) continue;
3595
- if (core === from || core.startsWith(`${from}-`)) {
3596
- const suffix = core.slice(from.length);
3597
- return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
3598
- }
5173
+ if (!(core === from || !exact && core.startsWith(`${from}-`))) continue;
5174
+ const suffix = core.slice(from.length);
5175
+ return `${variant}${reattachImportant(`${negative ? "-" : ""}${to}${suffix}`, position)}`;
3599
5176
  }
3600
5177
  return null;
3601
5178
  }
3602
5179
  function check(locations) {
5180
+ const ds = softGetDS(getDS);
5181
+ const isUsable = makeReplacementGuard(ds ? ds.cache : null);
3603
5182
  for (const loc of locations) {
3604
5183
  const split = splitClassesWithSeparators(loc.value);
3605
5184
  const offending = split.classes.flatMap((cls) => {
3606
5185
  const converted = convertClass(cls);
3607
- return converted ? [{
5186
+ if (!converted || !isUsable(converted)) return [];
5187
+ return [{
3608
5188
  cls,
3609
5189
  replacement: converted
3610
- }] : [];
5190
+ }];
3611
5191
  });
3612
5192
  reportClassReplacements(context, loc, split, split.classes, offending, { messageId: opts.messageId });
3613
5193
  }
@@ -3658,7 +5238,7 @@ const enforcePhysical = defineRule({
3658
5238
  },
3659
5239
  createOnce(context) {
3660
5240
  const { check } = createDirectionalMapper(context, {
3661
- mappings: invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS),
5241
+ mappings: [...invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS), ...LOGICAL_INSET_ALIASES],
3662
5242
  messageId: "usePhysical"
3663
5243
  });
3664
5244
  return createExtractorVisitors(context, check);
@@ -3811,7 +5391,7 @@ const noArbitraryValue = defineRule({
3811
5391
  for (const loc of locations) {
3812
5392
  const classes = splitClasses(loc.value);
3813
5393
  for (const cls of classes) {
3814
- if (!hasArbitraryValue(cls)) continue;
5394
+ if (!utilityHasDynamicValue(cls)) continue;
3815
5395
  const utility = splitImportant(extractUtility(cls)).bare;
3816
5396
  if (isAllowed(utility)) continue;
3817
5397
  context.report({
@@ -4076,10 +5656,13 @@ const noDarkWithoutLight = defineRule({
4076
5656
  docs: { description: "Require a base (light) utility when using dark: (or other scheme) variant" },
4077
5657
  schema: [{
4078
5658
  type: "object",
4079
- properties: { variants: {
4080
- type: "array",
4081
- items: { type: "string" }
4082
- } },
5659
+ properties: {
5660
+ variants: {
5661
+ type: "array",
5662
+ items: { type: "string" }
5663
+ },
5664
+ entryPoint: { type: "string" }
5665
+ },
4083
5666
  additionalProperties: false
4084
5667
  }],
4085
5668
  defaultOptions: [{ variants: DEFAULT_VARIANTS }],
@@ -4087,85 +5670,206 @@ const noDarkWithoutLight = defineRule({
4087
5670
  },
4088
5671
  createOnce(context) {
4089
5672
  const getWatchedVariants = createLazyOptions(context, (o) => new Set(o?.variants ?? DEFAULT_VARIANTS));
5673
+ const getDS = createLazyLoader(context);
5674
+ const bareOf = (cls) => splitImportant(extractUtility(cls)).bare;
4090
5675
  function check(locations) {
4091
5676
  const watchedVariants = getWatchedVariants();
5677
+ const ds = softGetDS(getDS);
5678
+ const cache = ds ? ds.cache : null;
4092
5679
  for (const loc of locations) {
4093
5680
  const classes = splitClasses(loc.value);
5681
+ if (cache && ds) {
5682
+ let unresolved = null;
5683
+ for (const cls of classes) {
5684
+ const bare = bareOf(cls);
5685
+ if (cache.getCssProperties(bare).length > 0 || !isUserValued(bare)) continue;
5686
+ if (!unresolved) unresolved = [];
5687
+ unresolved.push(bare);
5688
+ }
5689
+ if (unresolved) resolveDeclarationsSync(ds.entryPoint, cache, unresolved);
5690
+ }
4094
5691
  const basePrefixes = /* @__PURE__ */ new Set();
5692
+ const baseProperties = /* @__PURE__ */ new Set();
4095
5693
  const variantClasses = [];
4096
5694
  for (const cls of classes) {
4097
5695
  const variants = extractVariants(cls);
4098
5696
  const prefix = getUtilityPrefix(extractUtility(cls));
4099
- if (variants.some((v) => watchedVariants.has(v))) {
4100
- const variant = variants.find((v) => watchedVariants.has(v));
4101
- variantClasses.push({
4102
- cls,
5697
+ const properties = cache ? cache.getCssProperties(bareOf(cls)) : [];
5698
+ const variant = variants.find((v) => watchedVariants.has(v));
5699
+ if (variant !== void 0) variantClasses.push({
5700
+ cls,
5701
+ variant,
5702
+ prefix,
5703
+ properties
5704
+ });
5705
+ else {
5706
+ basePrefixes.add(prefix);
5707
+ for (const property of properties) baseProperties.add(property);
5708
+ }
5709
+ }
5710
+ for (const { cls, variant, prefix, properties } of variantClasses) {
5711
+ if (basePrefixes.has(prefix)) continue;
5712
+ if (properties.some((property) => baseProperties.has(property))) continue;
5713
+ context.report({
5714
+ node: loc.node,
5715
+ messageId: "missingBase",
5716
+ data: {
5717
+ className: cls,
4103
5718
  variant,
4104
5719
  prefix
4105
- });
4106
- } else basePrefixes.add(prefix);
5720
+ }
5721
+ });
4107
5722
  }
4108
- for (const { cls, variant, prefix } of variantClasses) if (!basePrefixes.has(prefix)) context.report({
4109
- node: loc.node,
4110
- messageId: "missingBase",
4111
- data: {
4112
- className: cls,
4113
- variant,
4114
- prefix
4115
- }
4116
- });
4117
5723
  }
4118
5724
  }
4119
5725
  return createExtractorVisitors(context, check);
4120
5726
  }
4121
5727
  });
4122
5728
  //#endregion
5729
+ //#region src/utils/color-literal.ts
5730
+ /**
5731
+ * Does this CSS value contain a hardcoded color literal, anywhere in it?
5732
+ *
5733
+ * `no-hardcoded-colors` used to answer that with `^`-anchored regexes over the
5734
+ * whole value, which only ever matched a value that IS a color. Every real
5735
+ * shorthand slipped through: `shadow-[0_1px_2px_#000]` carries a hardcoded black
5736
+ * that the rule promised to catch and didn't. Anchoring also forced a companion
5737
+ * list of "color-bearing utility prefixes" to keep the match plausible, and that
5738
+ * list drifted from Tailwind (it has `ring` but not `inset-ring`, `shadow` but not
5739
+ * `inset-shadow`, and no way to spell an arbitrary property like `[color:#f00]`).
5740
+ *
5741
+ * Scanning the value instead of anchoring to it drops both problems: the value
5742
+ * carries the color or it doesn't, whatever utility it is attached to.
5743
+ *
5744
+ * Two things must NOT count, and they are why this is a scanner rather than a
5745
+ * regex:
5746
+ * - quoted strings — `content-['#fff']` is the text `#fff`, not a color;
5747
+ * - `url()` contents — `fill-[url(#gradient)]` references an SVG node by id, the
5748
+ * single most common `#` in a Tailwind class that isn't a color.
5749
+ *
5750
+ * The notation set is exactly the one the rule documents (hex + the CSS color
5751
+ * functions). Named colors (`bg-[red]`) are deliberately absent: they were never
5752
+ * covered, and `currentColor`/`transparent`/`inherit` make that a separate
5753
+ * judgement call rather than a scan.
5754
+ */
5755
+ /** CSS color functions. `color-mix` is absent on purpose: its arguments are scanned. */
5756
+ const COLOR_FUNCTIONS = /* @__PURE__ */ new Set([
5757
+ "rgb",
5758
+ "rgba",
5759
+ "hsl",
5760
+ "hsla",
5761
+ "hwb",
5762
+ "lab",
5763
+ "lch",
5764
+ "oklab",
5765
+ "oklch",
5766
+ "color"
5767
+ ]);
5768
+ /** Hex digit counts CSS accepts: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`. */
5769
+ const HEX_LENGTHS = /* @__PURE__ */ new Set([
5770
+ 3,
5771
+ 4,
5772
+ 6,
5773
+ 8
5774
+ ]);
5775
+ function isHexDigit(ch) {
5776
+ return ch >= "0" && ch <= "9" || ch >= "a" && ch <= "f" || ch >= "A" && ch <= "F";
5777
+ }
5778
+ /**
5779
+ * `-` belongs to the identifier so `color-mix(` is not read as `color(`. `_` does
5780
+ * NOT: in a Tailwind arbitrary value an underscore stands for a space, so
5781
+ * `0_0_4px_rgb(…)` has to break into words or the function name never surfaces.
5782
+ */
5783
+ function isIdentChar(ch) {
5784
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "-";
5785
+ }
5786
+ function isIdentStart(ch) {
5787
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
5788
+ }
5789
+ /** Index just past the closing quote (or end of input on an unterminated string). */
5790
+ function skipQuoted(value, start) {
5791
+ const quote = value[start];
5792
+ let i = start + 1;
5793
+ while (i < value.length) {
5794
+ if (value[i] === "\\") {
5795
+ i += 2;
5796
+ continue;
5797
+ }
5798
+ if (value[i] === quote) return i + 1;
5799
+ i++;
5800
+ }
5801
+ return value.length;
5802
+ }
5803
+ /** Index just past the matching `)`, given `open` pointing at a `(`. */
5804
+ function skipBalanced(value, open) {
5805
+ let depth = 0;
5806
+ let i = open;
5807
+ while (i < value.length) {
5808
+ const ch = value[i];
5809
+ if (ch === "\"" || ch === "'") {
5810
+ i = skipQuoted(value, i);
5811
+ continue;
5812
+ }
5813
+ if (ch === "(") depth++;
5814
+ else if (ch === ")") {
5815
+ depth--;
5816
+ if (depth === 0) return i + 1;
5817
+ }
5818
+ i++;
5819
+ }
5820
+ return value.length;
5821
+ }
5822
+ function containsColorLiteral(value) {
5823
+ let i = 0;
5824
+ while (i < value.length) {
5825
+ const ch = value[i];
5826
+ if (ch === "\"" || ch === "'") {
5827
+ i = skipQuoted(value, i);
5828
+ continue;
5829
+ }
5830
+ if (ch === "#") {
5831
+ let end = i + 1;
5832
+ while (end < value.length && isHexDigit(value[end])) end++;
5833
+ if (HEX_LENGTHS.has(end - i - 1)) return true;
5834
+ i = end > i + 1 ? end : i + 1;
5835
+ continue;
5836
+ }
5837
+ if (isIdentStart(ch)) {
5838
+ const start = i;
5839
+ while (i < value.length && isIdentChar(value[i])) i++;
5840
+ if (value[i] !== "(") continue;
5841
+ const name = value.slice(start, i).toLowerCase();
5842
+ if (name === "url") {
5843
+ i = skipBalanced(value, i);
5844
+ continue;
5845
+ }
5846
+ if (COLOR_FUNCTIONS.has(name)) return true;
5847
+ continue;
5848
+ }
5849
+ i++;
5850
+ }
5851
+ return false;
5852
+ }
5853
+ //#endregion
4123
5854
  //#region src/rules/no-hardcoded-colors.ts
4124
- const COLOR_UTILITY_PREFIXES = [
4125
- "bg",
4126
- "text",
4127
- "border",
4128
- "border-t",
4129
- "border-b",
4130
- "border-l",
4131
- "border-r",
4132
- "border-s",
4133
- "border-e",
4134
- "border-x",
4135
- "border-y",
4136
- "outline",
4137
- "ring",
4138
- "ring-offset",
4139
- "shadow",
4140
- "accent",
4141
- "caret",
4142
- "fill",
4143
- "stroke",
4144
- "decoration",
4145
- "divide",
4146
- "placeholder",
4147
- "from",
4148
- "via",
4149
- "to"
4150
- ];
4151
- const HEX_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
4152
- const RGB_RE = /^rgba?\s*\(/;
4153
- const HSL_RE = /^hsla?\s*\(/;
4154
- const OKLCH_RE = /^oklch\s*\(/;
4155
- const OKLAB_RE = /^oklab\s*\(/;
4156
- const LCH_RE = /^lch\s*\(/;
4157
- const LAB_RE = /^lab\s*\(/;
4158
- const HWB_RE = /^hwb\s*\(/;
4159
- const COLOR_RE = /^color\s*\(/;
4160
5855
  const VAR_REF_RE = /var\(\s*--[\w-]+/i;
5856
+ /**
5857
+ * Does the arbitrary value the user wrote carry a hardcoded colour?
5858
+ *
5859
+ * This used to be a set of `^`-anchored regexes plus a list of "colour-bearing
5860
+ * utility prefixes", and both halves leaked. The anchoring meant only a value
5861
+ * that IS a colour matched, so `shadow-[0_1px_2px_#000]` passed. The prefix list
5862
+ * had `ring` but not `inset-ring`, `shadow` but not `inset-shadow`, and no way to
5863
+ * spell an arbitrary property at all (`[color:#f00]`, `[--brand:#f00]`).
5864
+ *
5865
+ * Neither is needed: the value carries the colour or it doesn't, whatever utility
5866
+ * it is attached to. `containsColorLiteral` skips quoted strings and `url()`
5867
+ * contents, which is what keeps `content-['#fff']` and `fill-[url(#gradient)]` out.
5868
+ */
4161
5869
  function isHardcodedColor(value) {
4162
5870
  const trimmed = value.trim();
4163
5871
  if (VAR_REF_RE.test(trimmed)) return false;
4164
- return HEX_RE.test(trimmed) || RGB_RE.test(trimmed) || HSL_RE.test(trimmed) || OKLCH_RE.test(trimmed) || OKLAB_RE.test(trimmed) || LCH_RE.test(trimmed) || LAB_RE.test(trimmed) || HWB_RE.test(trimmed) || COLOR_RE.test(trimmed);
4165
- }
4166
- function isColorUtility(utility) {
4167
- for (const prefix of COLOR_UTILITY_PREFIXES) if (utility === prefix || utility.startsWith(`${prefix}-`)) return true;
4168
- return false;
5872
+ return containsColorLiteral(trimmed);
4169
5873
  }
4170
5874
  const noHardcodedColors = defineRule({
4171
5875
  meta: {
@@ -4191,8 +5895,6 @@ const noHardcodedColors = defineRule({
4191
5895
  for (const cls of classes) {
4192
5896
  if (allowlist.has(cls)) continue;
4193
5897
  if (!hasArbitraryValue(cls)) continue;
4194
- const utility = splitImportant(extractUtility(cls)).bare;
4195
- if (!isColorUtility(utility)) continue;
4196
5898
  const value = getArbitraryValue(cls);
4197
5899
  if (!value) continue;
4198
5900
  if (isHardcodedColor(value)) context.report({
@@ -4212,11 +5914,23 @@ const noContradictingVariants = defineRule({
4212
5914
  meta: {
4213
5915
  type: "suggestion",
4214
5916
  docs: { description: "Disallow variant-prefixed classes that are redundant because the base class already applies unconditionally" },
4215
- schema: [],
5917
+ schema: [{
5918
+ type: "object",
5919
+ properties: { entryPoint: { type: "string" } },
5920
+ additionalProperties: false
5921
+ }],
5922
+ defaultOptions: [{}],
4216
5923
  messages: { redundantVariant: "\"{{variantClass}}\" is redundant because \"{{baseClass}}\" already applies unconditionally." }
4217
5924
  },
4218
5925
  createOnce(context) {
5926
+ const getDS = createLazyLoader(context);
5927
+ function variantFactsLookup() {
5928
+ const ds = softGetDS(getDS);
5929
+ if (!ds) return () => void 0;
5930
+ return (variant) => ds.cache.getVariantFacts(variant);
5931
+ }
4219
5932
  function check(locations) {
5933
+ const factsFor = variantFactsLookup();
4220
5934
  for (const loc of locations) {
4221
5935
  const classes = splitClasses(loc.value);
4222
5936
  const baseUtilities = /* @__PURE__ */ new Set();
@@ -4224,7 +5938,7 @@ const noContradictingVariants = defineRule({
4224
5938
  for (const cls of classes) {
4225
5939
  const variants = extractVariants(cls);
4226
5940
  if (variants.length === 0) continue;
4227
- if (variants.some(changesTarget)) continue;
5941
+ if (variants.some((v) => changesTarget(v, factsFor(v)))) continue;
4228
5942
  const utility = extractUtility(cls);
4229
5943
  if (baseUtilities.has(utility)) context.report({
4230
5944
  node: loc.node,
@@ -4360,15 +6074,9 @@ const consistentVariantOrder = defineRule({
4360
6074
  const priorityByEntry = /* @__PURE__ */ new Map();
4361
6075
  const prefixByEntry = /* @__PURE__ */ new Map();
4362
6076
  function resolveForFile() {
4363
- let dsCache = null;
4364
- let entryKey = "";
4365
- try {
4366
- const ds = getDS();
4367
- dsCache = ds.cache;
4368
- entryKey = ds.entryPoint;
4369
- } catch (err) {
4370
- if (!isFatalError(err)) throw err;
4371
- }
6077
+ const ds = softGetDS(getDS);
6078
+ const dsCache = ds ? ds.cache : null;
6079
+ const entryKey = ds ? ds.entryPoint : "";
4372
6080
  let priorityOf = priorityByEntry.get(entryKey);
4373
6081
  if (!priorityOf) {
4374
6082
  priorityOf = buildPriority(getOptions().order, dsCache);
@@ -4381,11 +6089,12 @@ const consistentVariantOrder = defineRule({
4381
6089
  }
4382
6090
  return {
4383
6091
  priorityOf,
4384
- prefix
6092
+ prefix,
6093
+ factsFor: dsCache ? (variant) => dsCache.getVariantFacts(variant) : () => void 0
4385
6094
  };
4386
6095
  }
4387
6096
  function reorderClass(cls) {
4388
- const { priorityOf, prefix } = resolveForFile();
6097
+ const { priorityOf, prefix, factsFor } = resolveForFile();
4389
6098
  let pfx = "";
4390
6099
  let body = cls;
4391
6100
  if (prefix && cls.startsWith(prefix + ":")) {
@@ -4396,7 +6105,7 @@ const consistentVariantOrder = defineRule({
4396
6105
  if (variants.length < 2) return null;
4397
6106
  const pseudo = [];
4398
6107
  const rest = [];
4399
- for (const v of variants) if (isPseudoElementVariant(v)) pseudo.push(v);
6108
+ for (const v of variants) if (isPseudoElementVariant(v, factsFor(v))) pseudo.push(v);
4400
6109
  else rest.push(v);
4401
6110
  const reorderedRest = [];
4402
6111
  let segment = [];
@@ -4406,7 +6115,7 @@ const consistentVariantOrder = defineRule({
4406
6115
  reorderedRest.push(...segment);
4407
6116
  segment = [];
4408
6117
  };
4409
- for (const v of rest) if (isSelectorBarrier(v)) {
6118
+ for (const v of rest) if (isSelectorBarrier(v, factsFor(v))) {
4410
6119
  flushSegment();
4411
6120
  reorderedRest.push(v);
4412
6121
  } else segment.push(v);
@@ -4672,6 +6381,9 @@ const plugin = definePlugin({
4672
6381
  if (!match) return [];
4673
6382
  const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
4674
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 [];
4675
6387
  const namedEquivalent = cache.getNamedEquivalent(bareUtility);
4676
6388
  if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
4677
6389
  return [{