oxlint-tailwindcss 1.3.4 → 1.4.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.72.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,
@@ -779,11 +779,13 @@ function reattachImportant(bare, position) {
779
779
  return bare;
780
780
  }
781
781
  /**
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).
782
+ * Pseudo-element variants, as a static fallback for when no design system is
783
+ * configured. They select a generated box (`::before`, `::marker`, …) rather than
784
+ * the element itself, so they must sit innermost in the variant chain (closest to
785
+ * the utility).
786
+ *
787
+ * Prefer the derived facts: this list cannot know a project's own variants, and
788
+ * `consistent-variant-order` is DS-optional by design, so both paths must work.
787
789
  */
788
790
  const PSEUDO_ELEMENT_VARIANTS = /* @__PURE__ */ new Set([
789
791
  "before",
@@ -797,32 +799,135 @@ const PSEUDO_ELEMENT_VARIANTS = /* @__PURE__ */ new Set([
797
799
  "first-letter",
798
800
  "details-content"
799
801
  ]);
800
- function isPseudoElementVariant(variant) {
802
+ function isPseudoElementVariant(variant, facts) {
803
+ if (facts) return facts.pseudoElement === true;
801
804
  return PSEUDO_ELEMENT_VARIANTS.has(variant);
802
805
  }
803
806
  /**
804
807
  * 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-[…]`).
808
+ * element than the ones around them — child (`*`), descendant (`**`), arbitrary
809
+ * selectors (`[&>svg]`), compound child selectors (`*:data-[…]`), and — only
810
+ * visible in the generated selector — ancestor/sibling variants like
811
+ * `group-hover` and `peer-checked`.
807
812
  *
808
813
  * Unlike pseudo-elements, these are NOT free to move to the end of the chain:
809
814
  * `hover:*:flex` (`&:hover > *`) and `*:hover:flex` (`& > *:hover`) target
810
- * different elements. `consistent-variant-order` treats them as hard
815
+ * different elements, and `peer-checked:group-hover:*` is not
816
+ * `group-hover:peer-checked:*`. `consistent-variant-order` treats them as hard
811
817
  * reordering barriers — variants never cross them.
818
+ *
819
+ * The syntactic checks stay as the fallback, and also as a floor: an arbitrary
820
+ * selector is a barrier whether or not the design system enumerated it.
812
821
  */
813
- function isSelectorBarrier(variant) {
822
+ function isSelectorBarrier(variant, facts) {
814
823
  if (variant === "*" || variant === "**") return true;
815
824
  if (variant.startsWith("[") && variant.endsWith("]")) return true;
816
825
  if (variant.startsWith("*:")) return true;
817
- return false;
826
+ return facts?.structural === true;
818
827
  }
819
828
  /**
820
829
  * Whether a variant changes the selector target (pseudo-element OR selector
821
830
  * barrier). Such variants don't impose a condition on the same element, so they
822
831
  * can't make a variant class contradict/duplicate a base class.
823
832
  */
824
- function changesTarget(variant) {
825
- return isPseudoElementVariant(variant) || isSelectorBarrier(variant);
833
+ function changesTarget(variant, facts) {
834
+ return isPseudoElementVariant(variant, facts) || isSelectorBarrier(variant, facts);
835
+ }
836
+ //#endregion
837
+ //#region src/design-system/css-declarations.ts
838
+ const EMPTY_DECLS = [];
839
+ const EMPTY_VARS = [];
840
+ /** Splits a scope token into its decoded parts. Unknown tokens degrade to `element`. */
841
+ function parseScopeToken(token) {
842
+ const conditional = token.startsWith("@");
843
+ const body = conditional ? token.slice(1) : token;
844
+ if (body === "") return {
845
+ scope: "element",
846
+ pseudo: "",
847
+ conditional
848
+ };
849
+ if (body === ">") return {
850
+ scope: "descendant",
851
+ pseudo: "",
852
+ conditional
853
+ };
854
+ if (body.startsWith("::")) return {
855
+ scope: "pseudo",
856
+ pseudo: body,
857
+ conditional
858
+ };
859
+ return {
860
+ scope: "element",
861
+ pseudo: "",
862
+ conditional
863
+ };
864
+ }
865
+ /**
866
+ * Builds a decoder bound to one index. The returned function turns a packed
867
+ * `byClass` entry into declarations, memoizing each table entry the first time
868
+ * it is touched — a linted file mentions hundreds of classes, not 23 000.
869
+ */
870
+ function createDeclarationDecoder(index) {
871
+ const pure = new Set(index.pureValues);
872
+ const decoded = Array.from({ length: index.table.length });
873
+ function varNames(map, valueId) {
874
+ const ids = map[String(valueId)];
875
+ if (!ids || ids.length === 0) return EMPTY_VARS;
876
+ const out = [];
877
+ for (const id of ids) {
878
+ const name = index.vars[id];
879
+ if (name !== void 0) out.push(name);
880
+ }
881
+ return out;
882
+ }
883
+ function declAt(declId) {
884
+ const cached = decoded[declId];
885
+ if (cached) return cached;
886
+ const entry = index.table[declId];
887
+ if (entry === void 0) return void 0;
888
+ const first = entry.indexOf("|");
889
+ const second = entry.indexOf("|", first + 1);
890
+ if (first < 0 || second < 0) return void 0;
891
+ const scopeId = parseInt(entry.slice(0, first), 36);
892
+ const propId = parseInt(entry.slice(first + 1, second), 36);
893
+ const valueId = parseInt(entry.slice(second + 1), 36);
894
+ const prop = index.props[propId];
895
+ const value = index.values[valueId];
896
+ if (prop === void 0 || value === void 0) return void 0;
897
+ const { scope, pseudo, conditional } = parseScopeToken(index.scopes[scopeId] ?? "");
898
+ const decl = {
899
+ prop,
900
+ value,
901
+ valueId,
902
+ scope,
903
+ pseudo,
904
+ conditional,
905
+ readsVars: varNames(index.valueVars, valueId),
906
+ readsFallbackVars: varNames(index.valueFallbackVars, valueId),
907
+ pureVarRead: pure.has(valueId)
908
+ };
909
+ decoded[declId] = decl;
910
+ return decl;
911
+ }
912
+ return function decode(packed) {
913
+ if (!packed) return EMPTY_DECLS;
914
+ const out = [];
915
+ let start = 0;
916
+ for (let i = 0; i <= packed.length; i++) if (i === packed.length || packed[i] === ",") {
917
+ if (i > start) {
918
+ const decl = declAt(parseInt(packed.slice(start, i), 36));
919
+ if (decl) out.push(decl);
920
+ }
921
+ start = i + 1;
922
+ }
923
+ return out;
924
+ };
925
+ }
926
+ /** Shape check for a value read back from the disk cache. */
927
+ function isCssDeclarationIndex(value) {
928
+ if (typeof value !== "object" || value === null) return false;
929
+ const i = value;
930
+ 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
931
  }
827
932
  //#endregion
828
933
  //#region src/utils/floating-point.ts
@@ -841,18 +946,27 @@ function roundRemValue(className) {
841
946
  }
842
947
  //#endregion
843
948
  //#region src/design-system/cache.ts
949
+ const EMPTY_DECLARATIONS = [];
844
950
  var DesignSystemCache = class DesignSystemCache {
845
951
  canonicalMap = /* @__PURE__ */ new Map();
846
952
  validitySet = /* @__PURE__ */ new Set();
847
953
  orderMap = /* @__PURE__ */ new Map();
848
- cssPropsMap = /* @__PURE__ */ new Map();
954
+ declIndex = null;
955
+ decodeDecls = null;
956
+ declMemo = /* @__PURE__ */ new Map();
957
+ propsMemo = /* @__PURE__ */ new Map();
958
+ partialSet = /* @__PURE__ */ new Set();
959
+ valueIdByText = null;
849
960
  variantOrderMap = /* @__PURE__ */ new Map();
961
+ variantFactsMap = /* @__PURE__ */ new Map();
850
962
  arbitraryEquivMap = /* @__PURE__ */ new Map();
851
963
  _validClasses = [];
852
964
  _knownPrefixes = null;
853
965
  _maxOrder = 0n;
854
966
  _prefix = "";
855
967
  componentSet = /* @__PURE__ */ new Set();
968
+ themeRefs = /* @__PURE__ */ new Map();
969
+ definedVarSet = /* @__PURE__ */ new Set();
856
970
  static fromPrecomputed(data) {
857
971
  const cache = new DesignSystemCache();
858
972
  cache._validClasses = data.validClasses;
@@ -863,12 +977,22 @@ var DesignSystemCache = class DesignSystemCache {
863
977
  cache.orderMap.set(cls, order);
864
978
  if (order > cache._maxOrder) cache._maxOrder = order;
865
979
  }
866
- for (const [cls, props] of Object.entries(data.cssProps)) cache.cssPropsMap.set(cls, props);
980
+ if (data.cssDeclarations) {
981
+ cache.declIndex = data.cssDeclarations;
982
+ cache.decodeDecls = createDeclarationDecoder(data.cssDeclarations);
983
+ for (const cls of data.cssDeclarations.partial ?? []) cache.partialSet.add(cls);
984
+ }
867
985
  if (data.variantOrder) for (const [name, index] of Object.entries(data.variantOrder)) cache.variantOrderMap.set(name, index);
986
+ for (const [name, facts] of Object.entries(data.variantFacts ?? {})) cache.variantFactsMap.set(name, {
987
+ pseudoElement: facts.p === 1,
988
+ structural: facts.s === 1
989
+ });
868
990
  if (data.componentClasses) for (const cls of data.componentClasses) {
869
991
  cache.validitySet.add(cls);
870
992
  cache.componentSet.add(cls);
871
993
  }
994
+ for (const name of data.definedVars ?? []) cache.definedVarSet.add(name);
995
+ if (data.themeRefs) for (const [name, refs] of Object.entries(data.themeRefs)) cache.themeRefs.set(name, refs);
872
996
  cache._prefix = data.prefix ?? "";
873
997
  if (data.arbitraryEquivalents) for (const [arb, named] of Object.entries(data.arbitraryEquivalents)) cache.arbitraryEquivMap.set(arb, named);
874
998
  return cache;
@@ -1057,15 +1181,151 @@ var DesignSystemCache = class DesignSystemCache {
1057
1181
  const bucketSize = this._maxOrder + 1n;
1058
1182
  return BigInt(firstPriority) * 1000n * bucketSize + BigInt(subPriority) * bucketSize + baseOrder;
1059
1183
  }
1184
+ /**
1185
+ * Whether the stylesheet order for this exact class is known, as opposed to
1186
+ * approximated from a prefix sibling. Callers that name a winner must not do
1187
+ * so from an approximation: `w-[10px]` and `w-[20px]` both borrow the order of
1188
+ * the first `w-*` class, which says nothing about their real positions.
1189
+ */
1190
+ hasExactOrder(className) {
1191
+ const key = this.stripProjectPrefix(className);
1192
+ if (this.orderMap.get(key) != null) return true;
1193
+ const { bare, position } = splitImportant(key);
1194
+ return position !== null && this.orderMap.get(bare) != null;
1195
+ }
1060
1196
  getClassOrder(classes) {
1061
1197
  return classes.map((cls) => [cls, this.getOrder(cls)]);
1062
1198
  }
1199
+ /**
1200
+ * Every declaration the class emits, in emission order, not deduplicated.
1201
+ * Includes declarations on pseudo-elements and (for classes that style only
1202
+ * their descendants, like `space-x-*`) on descendants — each tagged with its
1203
+ * scope, so callers never mistake one box for another.
1204
+ */
1205
+ getCssDeclarations(className) {
1206
+ const key = this.stripProjectPrefix(className);
1207
+ const memo = this.declMemo.get(key);
1208
+ if (memo) return memo;
1209
+ const byClass = this.declIndex?.byClass;
1210
+ let packed = byClass?.[key];
1211
+ if (packed === void 0) {
1212
+ const { bare, position } = splitImportant(key);
1213
+ if (position) packed = byClass?.[bare];
1214
+ }
1215
+ const decoded = this.decodeDecls?.(packed) ?? EMPTY_DECLARATIONS;
1216
+ this.declMemo.set(key, decoded);
1217
+ return decoded;
1218
+ }
1219
+ /**
1220
+ * Adds declarations resolved at lint time (for classes the precompute never
1221
+ * saw — arbitrary values, slash modifiers, off-scale numbers) and memoizes
1222
+ * them like any other class.
1223
+ *
1224
+ * Values are interned against the SAME table the precompute filled, which is
1225
+ * the point: `p-4`'s value id has to be comparable with `p-[1rem]`'s, or the
1226
+ * two could never be told apart from a genuine conflict.
1227
+ */
1228
+ internDeclarations(className, raws, valueFacts) {
1229
+ const index = this.declIndex;
1230
+ if (!index) return EMPTY_DECLARATIONS;
1231
+ if (!this.valueIdByText) this.valueIdByText = new Map(index.values.map((value, id) => [value, id]));
1232
+ const decls = [];
1233
+ let hasElement = false;
1234
+ let hasDescendant = false;
1235
+ let hasConditional = false;
1236
+ for (const [scopeToken, prop, value] of raws) {
1237
+ let valueId = this.valueIdByText.get(value);
1238
+ if (valueId === void 0) {
1239
+ valueId = index.values.length;
1240
+ index.values.push(value);
1241
+ this.valueIdByText.set(value, valueId);
1242
+ }
1243
+ const facts = valueFacts[value];
1244
+ const { scope, pseudo, conditional } = parseScopeToken(scopeToken);
1245
+ if (conditional) hasConditional = true;
1246
+ else if (scope === "element") hasElement = true;
1247
+ else if (scope === "descendant") hasDescendant = true;
1248
+ decls.push({
1249
+ prop,
1250
+ value,
1251
+ valueId,
1252
+ scope,
1253
+ pseudo,
1254
+ conditional,
1255
+ readsVars: facts?.p ?? [],
1256
+ readsFallbackVars: facts?.f ?? [],
1257
+ pureVarRead: facts?.u ?? false
1258
+ });
1259
+ }
1260
+ const key = this.stripProjectPrefix(className);
1261
+ if (hasConditional || hasElement && hasDescendant) this.partialSet.add(key);
1262
+ this.declMemo.set(key, decls);
1263
+ this.propsMemo.delete(key);
1264
+ return decls;
1265
+ }
1266
+ /**
1267
+ * True when the class emits CSS we deliberately did not model in full
1268
+ * (descendant rules alongside its own, or `@media`/`@supports` blocks). Such a
1269
+ * class must never be reported as redundant.
1270
+ */
1271
+ isPartial(className) {
1272
+ return this.partialSet.has(this.stripProjectPrefix(className));
1273
+ }
1274
+ /**
1275
+ * Property names the class declares on its OWN box, unconditionally.
1276
+ * Deduplicated, in emission order.
1277
+ */
1063
1278
  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 [];
1279
+ const key = this.stripProjectPrefix(className);
1280
+ const memo = this.propsMemo.get(key);
1281
+ if (memo) return memo;
1282
+ const seen = /* @__PURE__ */ new Set();
1283
+ const props = [];
1284
+ for (const decl of this.getCssDeclarations(key)) {
1285
+ if (decl.scope !== "element" || decl.conditional) continue;
1286
+ if (seen.has(decl.prop)) continue;
1287
+ seen.add(decl.prop);
1288
+ props.push(decl.prop);
1289
+ }
1290
+ this.propsMemo.set(key, props);
1291
+ return props;
1292
+ }
1293
+ /** Strips the Tailwind project prefix (`tw:flex` → `flex`), if configured. */
1294
+ stripProjectPrefix(className) {
1295
+ if (this._prefix && className.startsWith(this._prefix + ":")) return className.slice(this._prefix.length + 1);
1296
+ return className;
1297
+ }
1298
+ /**
1299
+ * Whether `varName` resolves to `target` through theme indirection.
1300
+ *
1301
+ * `@theme inline { --color-primary: var(--primary) }` makes `bg-primary` and
1302
+ * `bg-(--primary)` the same declaration; a literal `--color-primary: oklch(…)`
1303
+ * makes them different colours. Only the theme table can tell those apart.
1304
+ */
1305
+ themeVarResolvesTo(varName, target, depth = 4) {
1306
+ if (varName === target) return true;
1307
+ if (depth <= 0) return false;
1308
+ const refs = this.themeRefs.get(varName);
1309
+ if (!refs) return false;
1310
+ return refs.some((ref) => this.themeVarResolvesTo(ref, target, depth - 1));
1311
+ }
1312
+ /** Whether the project defines this custom property (theme or plain CSS). */
1313
+ definesVar(varName) {
1314
+ return this.definedVarSet.has(varName) || this.themeRefs.has(varName);
1315
+ }
1316
+ /**
1317
+ * What the variant's selector does, derived from the design system. `undefined`
1318
+ * means "no information" — the caller falls back to its static predicates,
1319
+ * which is what keeps the variant rules working without an entry point.
1320
+ *
1321
+ * Compound variants (`group-hover/name`, `peer-checked`) resolve through the
1322
+ * same normalisation the priority lookup uses.
1323
+ */
1324
+ getVariantFacts(variant) {
1325
+ const direct = this.variantFactsMap.get(variant);
1326
+ if (direct) return direct;
1327
+ const slash = variant.indexOf("/");
1328
+ if (slash > 0) return this.variantFactsMap.get(variant.slice(0, slash));
1069
1329
  }
1070
1330
  getVariantPriority(variant) {
1071
1331
  return this.variantOrderMap.get(variant) ?? null;
@@ -1228,6 +1488,181 @@ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPat
1228
1488
  *
1229
1489
  * For arbitrary values (bg-[#123]) that aren't in the class list, we use heuristics.
1230
1490
  */
1491
+ /**
1492
+ * Declaration extractor, as source text, interpolated into PRECOMPUTE_SCRIPT.
1493
+ *
1494
+ * It lives in its own constant for two reasons: the benchmark in
1495
+ * `tests/benchmarks/precompute-phases.test.ts` used to keep a hand-copied
1496
+ * duplicate of the extractor that silently drifted from the real one, and it is
1497
+ * interpolated (not concatenated at runtime), so its text still feeds the
1498
+ * `CACHE_KEY` md5 and any edit here invalidates the disk cache automatically.
1499
+ *
1500
+ * Exports (in the worker scope): `walkDeclarations`, `scanVarReads`,
1501
+ * `isPureVarRead`.
1502
+ */
1503
+ const DECL_EXTRACTOR_SOURCE = `
1504
+ // One declaration per line, '{' closing the selector line, '}' alone — the
1505
+ // shape candidatesToCss pretty-prints. Verified against every fixture: zero
1506
+ // unparsed declaration lines.
1507
+ const DECL_RE = /^([\\w-]+)\\s*:\\s*(.*?)\\s*;?$/;
1508
+
1509
+ // Class-name characters, plus '\\\\' because escaped selectors continue the name
1510
+ // ('.w-1\\\\/2' must not be matched by the token '.w-1').
1511
+ function isNameChar(c) {
1512
+ if (c === undefined) return false;
1513
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
1514
+ || c === '-' || c === '_' || c === '\\\\';
1515
+ }
1516
+
1517
+ // Classify what follows the class token inside a selector:
1518
+ // '::name' → the declaration styles that pseudo-element's box
1519
+ // '>' → a combinator intervenes, so the class is not the subject
1520
+ // '' → the element's own box (pseudo-CLASSES land here)
1521
+ // The combinator scan is paren-aware: tw-animate-css emits
1522
+ // '&:where(:dir(ltr), [dir="ltr"], [dir="ltr"]*)', whose spaces and commas sit
1523
+ // inside :where(). A naive "is there a space" test would mislabel 92 rules as
1524
+ // descendant and silently stop reporting on the slide-in-* family.
1525
+ function classifyAfter(after) {
1526
+ if (after.startsWith('::')) {
1527
+ let e = 2;
1528
+ while (e < after.length && isNameChar(after[e]) && after[e] !== '\\\\') e++;
1529
+ return after.slice(0, e);
1530
+ }
1531
+ let depth = 0;
1532
+ for (let x = 0; x < after.length; x++) {
1533
+ const ch = after[x];
1534
+ if (ch === '(') depth++;
1535
+ else if (ch === ')') { if (depth > 0) depth--; }
1536
+ else if (depth === 0) {
1537
+ if (ch === '>' || ch === '+' || ch === '~' || ch === ' ' || ch === '\\t') return '>';
1538
+ if (ch === ',') break;
1539
+ }
1540
+ }
1541
+ return '';
1542
+ }
1543
+
1544
+ // Find the token as a COMPLETE compound ('.rounded' must not match inside
1545
+ // '.rounded-lg'). Returns null when the token is absent, which the caller
1546
+ // treats as element scope: that is today's behaviour for selectors we cannot
1547
+ // attribute, and widening it to 'descendant' would blind the rule.
1548
+ function classifyTopLevel(sel, token) {
1549
+ let from = 0;
1550
+ for (;;) {
1551
+ const i = sel.indexOf(token, from);
1552
+ if (i < 0) return null;
1553
+ if (!isNameChar(sel[i + token.length])) return classifyAfter(sel.slice(i + token.length));
1554
+ from = i + 1;
1555
+ }
1556
+ }
1557
+
1558
+ // Nested block (CSS nesting). A selector that does not start with '&' is
1559
+ // implicitly '& <sel>', i.e. a descendant — that is what keeps prose's
1560
+ // ':where(p)' rules out of the element's declaration set.
1561
+ function classifyNested(sel) {
1562
+ if (sel[0] !== '&') return '>';
1563
+ return classifyAfter(sel.slice(1));
1564
+ }
1565
+
1566
+ // Tailwind emits the same value two ways: 'slide-in-from-left' declares
1567
+ // '-100%' and 'slide-in-from-left-full' declares 'calc(1 * -100%)'. Same
1568
+ // computed value, different text — and a text comparison would call that a
1569
+ // conflict. Only a SINGLE numeric term is unwrapped, so 'calc(1 * 2px + 3px)'
1570
+ // (where the multiplication is part of a larger expression) is left alone.
1571
+ const CALC_ONE_LEFT = /^calc\\(\\s*1\\s*\\*\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+)[a-z%]*)\\s*\\)$/;
1572
+ const CALC_ONE_RIGHT = /^calc\\(\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+)[a-z%]*)\\s*\\*\\s*1\\s*\\)$/;
1573
+ function normalizeDeclValue(value) {
1574
+ const trimmed = value.trim();
1575
+ const m = CALC_ONE_LEFT.exec(trimmed) || CALC_ONE_RIGHT.exec(trimmed);
1576
+ return m ? m[1] : trimmed;
1577
+ }
1578
+
1579
+ function walkDeclarations(cssText, className, sink) {
1580
+ const token = '.' + className.replace(/([^\\w-])/g, '\\\\$1');
1581
+ const stack = [];
1582
+ let skipDepth = 0;
1583
+ const lines = cssText.split('\\n');
1584
+ for (let li = 0; li < lines.length; li++) {
1585
+ const line = lines[li].trim();
1586
+ if (line === '') continue;
1587
+ if (line === '}') { if (skipDepth > 0) skipDepth--; else stack.pop(); continue; }
1588
+ if (line.charCodeAt(line.length - 1) === 123 /* { */) {
1589
+ if (skipDepth > 0) { skipDepth++; continue; }
1590
+ const sel = line.slice(0, -1).trim();
1591
+ // @property blocks describe a variable, they don't style anything: skip
1592
+ // the whole block (that also drops syntax/inherits/initial-value).
1593
+ if (sel.startsWith('@property')) { skipDepth++; continue; }
1594
+ stack.push(sel);
1595
+ continue;
1596
+ }
1597
+ if (skipDepth > 0) continue;
1598
+ const m = DECL_RE.exec(line);
1599
+ if (!m) continue;
1600
+ // Resolve the scope from the open block stack.
1601
+ let conditional = false, scope = '', seenSubject = false;
1602
+ for (let k = 0; k < stack.length; k++) {
1603
+ const sel = stack[k];
1604
+ if (sel.charCodeAt(0) === 64 /* @ */) { conditional = true; continue; }
1605
+ if (!seenSubject) {
1606
+ seenSubject = true;
1607
+ const top = classifyTopLevel(sel, token);
1608
+ scope = top === null ? '' : top;
1609
+ } else {
1610
+ const inner = classifyNested(sel);
1611
+ if (inner === '>') scope = '>';
1612
+ else if (inner !== '' && scope !== '>') scope = inner;
1613
+ }
1614
+ }
1615
+ sink((conditional ? '@' : '') + scope, m[1], normalizeDeclValue(m[2]));
1616
+ }
1617
+ }
1618
+
1619
+ // Custom properties a value reads. 'primary' means "not inside another var()'s
1620
+ // fallback" — NOT "at paren depth 0": the vars inside linear-gradient(...) are
1621
+ // primary reads. Fallback reads are reported separately because a fallback is a
1622
+ // last resort, not the composition channel.
1623
+ function scanVarReads(value) {
1624
+ const primary = [], fallback = [];
1625
+ function walk(s, inFallback) {
1626
+ let i = 0;
1627
+ for (;;) {
1628
+ const at = s.indexOf('var(', i);
1629
+ if (at < 0) break;
1630
+ let d = 1, j = at + 4;
1631
+ while (j < s.length && d > 0) { if (s[j] === '(') d++; else if (s[j] === ')') d--; j++; }
1632
+ const inner = s.slice(at + 4, j - 1);
1633
+ let c = 0, comma = -1;
1634
+ for (let x = 0; x < inner.length; x++) {
1635
+ if (inner[x] === '(') c++;
1636
+ else if (inner[x] === ')') c--;
1637
+ else if (inner[x] === ',' && c === 0) { comma = x; break; }
1638
+ }
1639
+ const name = (comma < 0 ? inner : inner.slice(0, comma)).trim();
1640
+ if (name.startsWith('--')) (inFallback ? fallback : primary).push(name);
1641
+ if (comma >= 0) walk(inner.slice(comma + 1), true);
1642
+ i = j;
1643
+ }
1644
+ }
1645
+ walk(value, false);
1646
+ return [[...new Set(primary)], [...new Set(fallback)]];
1647
+ }
1648
+
1649
+ // A value is a pure var() read when, with every balanced var(...) group removed,
1650
+ // only separators remain. 'var(--tw-scale-x) var(--tw-scale-y)' is pure;
1651
+ // 'translateZ(0) var(--tw-rotate-x,)' is not (it contributes a value of its own).
1652
+ function isPureVarRead(value) {
1653
+ let rest = '', i = 0;
1654
+ while (i < value.length) {
1655
+ if (value.startsWith('var(', i)) {
1656
+ let d = 1, j = i + 4;
1657
+ while (j < value.length && d > 0) { if (value[j] === '(') d++; else if (value[j] === ')') d--; j++; }
1658
+ i = j;
1659
+ continue;
1660
+ }
1661
+ rest += value[i++];
1662
+ }
1663
+ return /^[\\s,]*$/.test(rest);
1664
+ }
1665
+ `;
1231
1666
  const PRECOMPUTE_SCRIPT = `
1232
1667
  // Runs as a worker_thread (NOT a forked child process). Inputs arrive via
1233
1668
  // workerData; the result is written straight to the disk cache and completion
@@ -1337,6 +1772,8 @@ function extractComponentClasses(cssPath, baseDir) {
1337
1772
  return [...new Set(result)];
1338
1773
  }
1339
1774
 
1775
+ ${DECL_EXTRACTOR_SOURCE}
1776
+
1340
1777
  async function main() {
1341
1778
  const cssPath = WD_CSS_PATH;
1342
1779
  const css = readFileSync(cssPath, 'utf-8');
@@ -1362,10 +1799,21 @@ async function main() {
1362
1799
 
1363
1800
  // Validity: which classes produce CSS. Validate the prefixed form, but keep
1364
1801
  // cssResults aligned positionally to the unprefixed classNames so the later
1365
- // cssProps / arbitraryEquivalents phases keep indexing by position.
1802
+ // declarations / arbitraryEquivalents phases keep indexing by position.
1366
1803
  const cssResults = ds.candidatesToCss(classNames.map(pfx));
1367
1804
  const validClasses = classNames.filter((_, i) => cssResults[i] != null);
1368
1805
 
1806
+ // className → its emitted CSS, for the declarations phase. Every phase that
1807
+ // validates extra candidates feeds this map, so classes recovered outside
1808
+ // getClassList() (bare utilities like \`rounded\`, negatives like \`-col-1\`,
1809
+ // legacy v3 spellings) get declarations too. They used to be pushed into
1810
+ // validClasses with their CSS thrown away, which left ~300 valid classes
1811
+ // invisible to no-conflicting-classes (\`rounded rounded-lg\` never reported).
1812
+ const declCss = {};
1813
+ for (let i = 0; i < classNames.length; i++) {
1814
+ if (cssResults[i] != null) declCss[classNames[i]] = cssResults[i];
1815
+ }
1816
+
1369
1817
  // Expand: validate extra candidates not in getClassList() but valid in v4
1370
1818
  const validSet = new Set(validClasses);
1371
1819
  const knownPrefixes = new Set();
@@ -1383,7 +1831,7 @@ async function main() {
1383
1831
  // utilities; their functional bases enumerate values but omit \`none\`.
1384
1832
  // - \`max-w-screen\` (\`max-width: 100vw\`).
1385
1833
  // 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
1834
+ // emit them) and their CSS is captured so the declarations phase below treats them
1387
1835
  // exactly like their getClassList siblings — otherwise no-conflicting-classes
1388
1836
  // would flag \`@container @container-normal\` but silently accept
1389
1837
  // \`@container @container-size\`. Named forms (\`@container-size/main\`) are covered
@@ -1394,14 +1842,13 @@ async function main() {
1394
1842
  'backdrop-filter-none',
1395
1843
  'max-w-screen',
1396
1844
  ].filter((c) => !validSet.has(c));
1397
- const staticExtraCss = {};
1398
1845
  if (staticExtras.length > 0) {
1399
1846
  const staticResults = ds.candidatesToCss(staticExtras.map(pfx));
1400
1847
  for (let i = 0; i < staticExtras.length; i++) {
1401
1848
  if (staticResults[i] != null) {
1402
1849
  validClasses.push(staticExtras[i]);
1403
1850
  validSet.add(staticExtras[i]);
1404
- staticExtraCss[staticExtras[i]] = staticResults[i];
1851
+ declCss[staticExtras[i]] = staticResults[i];
1405
1852
  }
1406
1853
  }
1407
1854
  }
@@ -1423,6 +1870,7 @@ async function main() {
1423
1870
  if (extraResults[i] != null) {
1424
1871
  validClasses.push(extraCandidates[i]);
1425
1872
  validSet.add(extraCandidates[i]);
1873
+ declCss[extraCandidates[i]] = extraResults[i];
1426
1874
  }
1427
1875
  }
1428
1876
  }
@@ -1444,6 +1892,7 @@ async function main() {
1444
1892
  if (negResults[i] != null && !validSet.has(negativeProbes[i])) {
1445
1893
  validClasses.push(negativeProbes[i]);
1446
1894
  validSet.add(negativeProbes[i]);
1895
+ declCss[negativeProbes[i]] = negResults[i];
1447
1896
  }
1448
1897
  }
1449
1898
  }
@@ -1520,6 +1969,7 @@ async function main() {
1520
1969
  // Mark as valid so no-unknown-classes doesn't flag legacy spellings.
1521
1970
  validClasses.push(cls);
1522
1971
  validSet.add(cls);
1972
+ declCss[cls] = legacyCssResults[i];
1523
1973
  }
1524
1974
  }
1525
1975
 
@@ -1534,108 +1984,126 @@ async function main() {
1534
1984
  if (val !== null) order[unpfx(name)] = val.toString();
1535
1985
  }
1536
1986
 
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']);
1987
+ // CSS declarations per class, interned. The walker, the scope grammar and the
1988
+ // var-read scanner live in DECL_EXTRACTOR_SOURCE above (shared with the
1989
+ // benchmark so the two can no longer drift).
1990
+ const scopeIds = new Map([['', 0]]);
1991
+ const scopeTable = [''];
1992
+ const propIds = new Map();
1993
+ const propTable = [];
1994
+ const valueIds = new Map();
1995
+ const valueTable = [];
1996
+ const declFreq = new Map();
1997
+ const perClass = {};
1998
+ const partial = [];
1543
1999
 
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
- }
2000
+ for (const cls in declCss) {
2001
+ // Collect first, intern after, so the descendant-scope decision below can
2002
+ // look at the whole class.
2003
+ const raw = [];
2004
+ let hasElement = false, hasDescendant = false, hasConditional = false;
2005
+ walkDeclarations(declCss[cls], pfx(cls), (scopeTok, prop, value) => {
2006
+ raw.push([scopeTok, prop, value]);
2007
+ const conditional = scopeTok.charCodeAt(0) === 64;
2008
+ const body = conditional ? scopeTok.slice(1) : scopeTok;
2009
+ if (conditional) hasConditional = true;
2010
+ if (body === '') hasElement = true;
2011
+ else if (body === '>') hasDescendant = true;
2012
+ });
1560
2013
 
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
- }
2014
+ // A class whose CSS styles BOTH itself and its descendants (\`prose\` and its
2015
+ // dozens of \`:where(p)\` rules) only advertises what it puts on the element:
2016
+ // comparing descendant declarations would turn every \`prose prose-sm\` into
2017
+ // ~40 conflicts. Classes that style ONLY descendants (\`space-x-*\`,
2018
+ // \`divide-*\`) keep them — that is what makes \`space-x-4 space-x-2\` a
2019
+ // conflict while \`ms-2 space-x-4\` is not. Pseudo-elements are always kept:
2020
+ // they are a distinct box and there are few of them.
2021
+ const dropDescendants = hasElement && hasDescendant;
2022
+ // Anything we deliberately did not model. A class in here must never be
2023
+ // called redundant: \`container\` looks like a plain \`width: 100%\` because its
2024
+ // breakpoint \`max-width\`es live in @media, so "remove it" would be wrong.
2025
+ if (dropDescendants || hasConditional) partial.push(cls);
1584
2026
 
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
- }
2027
+ const keys = [];
2028
+ for (let r = 0; r < raw.length; r++) {
2029
+ const scopeTok = raw[r][0], prop = raw[r][1], value = raw[r][2];
2030
+ const body = scopeTok.charCodeAt(0) === 64 ? scopeTok.slice(1) : scopeTok;
2031
+ if (dropDescendants && body === '>') continue;
2032
+ let s = scopeIds.get(scopeTok);
2033
+ if (s === undefined) { s = scopeTable.length; scopeTable.push(scopeTok); scopeIds.set(scopeTok, s); }
2034
+ let p = propIds.get(prop);
2035
+ if (p === undefined) { p = propTable.length; propTable.push(prop); propIds.set(prop, p); }
2036
+ let v = valueIds.get(value);
2037
+ if (v === undefined) { v = valueTable.length; valueTable.push(value); valueIds.set(value, v); }
2038
+ const key = s + '|' + p + '|' + v;
2039
+ declFreq.set(key, (declFreq.get(key) || 0) + 1);
2040
+ keys.push(key);
1612
2041
  }
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)];
2042
+ // Kept in emission order and NOT deduplicated: a class that declares the
2043
+ // same property twice (bg-linear-to-r does, once plainly and once inside
2044
+ // @supports) keeps both. Within one block the LAST one wins, which is CSS
2045
+ // semantics — the consumer applies that, the data keeps everything.
2046
+ if (keys.length > 0) perClass[cls] = keys;
1619
2047
  }
1620
2048
 
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;
2049
+ // Hottest declarations get the shortest base36 ids. Ties break on the key so
2050
+ // the artifact stays byte-reproducible for a given design system.
2051
+ const sortedKeys = [...declFreq.keys()].sort((a, b) => {
2052
+ const d = declFreq.get(b) - declFreq.get(a);
2053
+ return d !== 0 ? d : (a < b ? -1 : a > b ? 1 : 0);
2054
+ });
2055
+ const declIds = new Map();
2056
+ const table = [];
2057
+ for (let i = 0; i < sortedKeys.length; i++) {
2058
+ declIds.set(sortedKeys[i], i);
2059
+ const parts = sortedKeys[i].split('|');
2060
+ table.push(
2061
+ Number(parts[0]).toString(36) + '|' + Number(parts[1]).toString(36) + '|' + Number(parts[2]).toString(36)
2062
+ );
2063
+ }
2064
+ const byClass = {};
2065
+ for (const cls in perClass) {
2066
+ const ids = perClass[cls];
2067
+ let packed = '';
2068
+ for (let i = 0; i < ids.length; i++) {
2069
+ packed += (i === 0 ? '' : ',') + declIds.get(ids[i]).toString(36);
1627
2070
  }
2071
+ byClass[cls] = packed;
1628
2072
  }
1629
2073
 
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;
2074
+ // Which variables a value reads is a property of the VALUE, so it is computed
2075
+ // once per interned value (~2.7k) instead of once per declaration (~55k).
2076
+ const varIds = new Map();
2077
+ const varTable = [];
2078
+ const valueVars = {};
2079
+ const valueFallbackVars = {};
2080
+ const pureValues = [];
2081
+ function internVar(name) {
2082
+ let id = varIds.get(name);
2083
+ if (id === undefined) { id = varTable.length; varTable.push(name); varIds.set(name, id); }
2084
+ return id;
2085
+ }
2086
+ for (let v = 0; v < valueTable.length; v++) {
2087
+ const reads = scanVarReads(valueTable[v]);
2088
+ if (reads[0].length > 0) valueVars[v] = reads[0].map(internVar);
2089
+ if (reads[1].length > 0) valueFallbackVars[v] = reads[1].map(internVar);
2090
+ if (isPureVarRead(valueTable[v])) pureValues.push(v);
1636
2091
  }
1637
2092
 
1638
- // Variant ordering from the design system
2093
+ const cssDeclarations = {
2094
+ partial,
2095
+ scopes: scopeTable,
2096
+ props: propTable,
2097
+ values: valueTable,
2098
+ vars: varTable,
2099
+ valueVars,
2100
+ valueFallbackVars,
2101
+ pureValues,
2102
+ table,
2103
+ byClass,
2104
+ };
2105
+
2106
+ // Variant ordering from the design system.
1639
2107
  const variantOrder = {};
1640
2108
  const variants = ds.getVariants();
1641
2109
  for (let i = 0; i < variants.length; i++) {
@@ -1644,6 +2112,54 @@ async function main() {
1644
2112
  }
1645
2113
  }
1646
2114
 
2115
+ // What each variant DOES to the selector, so the variant rules can stop
2116
+ // guessing from a list of names — the list cannot know a project's own
2117
+ // \`@custom-variant\`.
2118
+ //
2119
+ // Derived by compiling a probe utility and reading the emitted selector, NOT
2120
+ // from \`variant.selectors()\`: that returns '&'-relative strings, comes back
2121
+ // empty for \`before\`/\`after\`, and reports \`group\`/\`peer\` as arbitrary with no
2122
+ // selectors at all. Compiling is the same mechanism the declaration extractor
2123
+ // already trusts, and \`walkDeclarations\` already classifies exactly what we
2124
+ // need — the scope of each emitted declaration.
2125
+ //
2126
+ // Functional variants (\`group-*\`, \`peer-*\`, \`data-*\`, \`nth-*\`) are skipped:
2127
+ // probing them would need a value, and none of them retargets the selector.
2128
+ // Measured in Tailwind 4.3.3: \`group-hover\`/\`peer-checked\` compile to
2129
+ // \`&:is(:where(.group):hover *)\` — an \`:is()\` on the element itself — so two of
2130
+ // them in either order produce equivalent selectors and neither is a
2131
+ // reordering barrier.
2132
+ const variantFacts = {};
2133
+ const probeNames = [];
2134
+ for (let i = 0; i < variants.length; i++) {
2135
+ const v = variants[i];
2136
+ if (v.isArbitrary) continue;
2137
+ if (v.values && v.values.length > 0) continue;
2138
+ probeNames.push(v.name);
2139
+ }
2140
+ if (probeNames.length > 0) {
2141
+ const probeClasses = probeNames.map((n) => n + ':flex');
2142
+ const probeCss = ds.candidatesToCss(probeClasses.map(pfx));
2143
+ for (let i = 0; i < probeNames.length; i++) {
2144
+ if (!probeCss[i]) continue;
2145
+ let pseudo = false, structural = false;
2146
+ walkDeclarations(probeCss[i], pfx(probeClasses[i]), (scopeTok) => {
2147
+ const body = scopeTok.charCodeAt(0) === 64 ? scopeTok.slice(1) : scopeTok;
2148
+ if (body.startsWith('::')) pseudo = true;
2149
+ else if (body === '>') structural = true;
2150
+ });
2151
+ // A variant that styles a generated box is a pseudo-element variant even
2152
+ // when it ALSO reaches descendants' boxes (\`marker\` emits both
2153
+ // \`& ::marker\` and \`&::marker\`): it belongs innermost, not treated as a
2154
+ // reordering barrier.
2155
+ if (pseudo) {
2156
+ variantFacts[probeNames[i]] = { p: 1 };
2157
+ } else if (structural) {
2158
+ variantFacts[probeNames[i]] = { s: 1 };
2159
+ }
2160
+ }
2161
+ }
2162
+
1647
2163
  // Component classes from @layer components
1648
2164
  const componentClasses = extractComponentClasses(cssPath, base);
1649
2165
 
@@ -1704,7 +2220,28 @@ async function main() {
1704
2220
  }
1705
2221
  }
1706
2222
 
1707
- const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents, prefix });
2223
+ // Theme variables that dereference to another custom property. Only the
2224
+ // referencing ones are stored (~a handful), and the reference list reuses the
2225
+ // same balanced scanner the declaration values go through.
2226
+ // Custom properties the project defines. The entry file covers the standard
2227
+ // ':root { --x: ... }' pattern; definitions inside @imported files are not
2228
+ // scanned, so an unseen definition reads as "undefined" — which only ever makes
2229
+ // prefer-theme-tokens more willing to suggest, never less accurate about a
2230
+ // definition it can see.
2231
+ const definedVars = [...new Set(css.match(/--[\\w-]+(?=\\s*:)/g) || [])];
2232
+
2233
+ const themeRefs = {};
2234
+ if (ds.theme && typeof ds.theme.entries === 'function') {
2235
+ for (const [name, entry] of ds.theme.entries()) {
2236
+ const value = entry && typeof entry.value === 'string' ? entry.value : '';
2237
+ if (!value.includes('var(')) continue;
2238
+ const reads = scanVarReads(value);
2239
+ const all = [...new Set([...reads[0], ...reads[1]])];
2240
+ if (all.length > 0) themeRefs[name] = all;
2241
+ }
2242
+ }
2243
+
2244
+ const json = JSON.stringify({ validClasses, canonical, order, cssDeclarations, variantOrder, variantFacts, componentClasses, arbitraryEquivalents, themeRefs, definedVars, prefix });
1708
2245
  // Atomic write: write to a unique temp path then rename, so a peer isolate
1709
2246
  // busy-waiting on the cache file never observes a half-written JSON.
1710
2247
  writeFileSync(WD_TMP_PATH, json);
@@ -1789,6 +2326,19 @@ function getContentCachePath(contentHash) {
1789
2326
  return (0, node_path.join)(CACHE_DIR, `${contentHash}.json`);
1790
2327
  }
1791
2328
  /**
2329
+ * The on-disk cache artifacts for a CSS entry point: the precomputed `json`
2330
+ * and the coordination `lock`. Exposed for tests that exercise the
2331
+ * cold-cache precompute coordination (issue #24).
2332
+ */
2333
+ function cacheArtifactPaths(cssPath) {
2334
+ const resolved = (0, node_path.resolve)(cssPath);
2335
+ const hash = computeContentHash(hashableContent(resolved, (0, node_fs.readFileSync)(resolved, "utf-8")));
2336
+ return {
2337
+ json: getContentCachePath(hash),
2338
+ lock: (0, node_path.join)(CACHE_DIR, `${hash}.lock`)
2339
+ };
2340
+ }
2341
+ /**
1792
2342
  * Minimal shape check for a cache payload. Guards against (a) a poisoned file
1793
2343
  * planted by a local attacker and (b) a corrupt/half-written or version-skewed
1794
2344
  * file. A `{}` that is valid JSON but missing fields would otherwise blow up
@@ -1800,7 +2350,7 @@ function isPrecomputedData(data) {
1800
2350
  if (typeof data !== "object" || data === null) return false;
1801
2351
  const d = data;
1802
2352
  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);
2353
+ 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
2354
  }
1805
2355
  function tryReadCache(cachePath) {
1806
2356
  const raw = tryReadRawCache(cachePath);
@@ -1833,7 +2383,7 @@ function lockAgeMs(lockPath) {
1833
2383
  return Number.POSITIVE_INFINITY;
1834
2384
  }
1835
2385
  }
1836
- function tryUnlink(path) {
2386
+ function tryUnlink$1(path) {
1837
2387
  try {
1838
2388
  (0, node_fs.unlinkSync)(path);
1839
2389
  } catch {}
@@ -1846,14 +2396,14 @@ function tryUnlink(path) {
1846
2396
  * exists to prevent, #24). `renameSync` moves the file atomically: only one
1847
2397
  * waiter wins the move; the loser gets ENOENT and loops back to re-check.
1848
2398
  */
1849
- function reclaimStaleLock(lockPath) {
2399
+ function reclaimStaleLock$1(lockPath) {
1850
2400
  const reclaimPath = `${lockPath}.reclaim.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
1851
2401
  try {
1852
2402
  (0, node_fs.renameSync)(lockPath, reclaimPath);
1853
2403
  } catch {
1854
2404
  return;
1855
2405
  }
1856
- tryUnlink(reclaimPath);
2406
+ tryUnlink$1(reclaimPath);
1857
2407
  }
1858
2408
  /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1859
2409
  const PRECOMPUTE_SIGNAL_INDEX = 2;
@@ -1892,6 +2442,11 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1892
2442
  const errLengthView = new DataView(sharedBuffer, 16, 4);
1893
2443
  const errDataArea = new Uint8Array(sharedBuffer, 20);
1894
2444
  const tmpPath = `${cachePath}.tmp.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
2445
+ try {
2446
+ new Function(PRECOMPUTE_SCRIPT);
2447
+ } catch (cause) {
2448
+ throw precomputeLoadError(resolvedPath, cause);
2449
+ }
1895
2450
  let worker;
1896
2451
  try {
1897
2452
  worker = new node_worker_threads.Worker(PRECOMPUTE_SCRIPT, {
@@ -1915,7 +2470,7 @@ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeo
1915
2470
  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
2471
  }
1917
2472
  } finally {
1918
- tryUnlink(tmpPath);
2473
+ tryUnlink$1(tmpPath);
1919
2474
  worker.terminate();
1920
2475
  }
1921
2476
  }
@@ -1957,18 +2512,18 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1957
2512
  lockFd = (0, node_fs.openSync)(lockPath, "wx");
1958
2513
  } catch (cause) {
1959
2514
  if (cause.code === "EEXIST") {
1960
- if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock(lockPath);
2515
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) reclaimStaleLock$1(lockPath);
1961
2516
  else syncSleep(LOCK_POLL_MS);
1962
2517
  continue;
1963
2518
  }
1964
2519
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1965
2520
  }
1966
2521
  try {
1967
- tryUnlink(cachePath);
2522
+ tryUnlink$1(cachePath);
1968
2523
  return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1969
2524
  } finally {
1970
2525
  (0, node_fs.closeSync)(lockFd);
1971
- tryUnlink(lockPath);
2526
+ tryUnlink$1(lockPath);
1972
2527
  }
1973
2528
  }
1974
2529
  }
@@ -2485,15 +3040,12 @@ const noDeprecatedClasses = defineRule({
2485
3040
  defaultOptions: [{}],
2486
3041
  messages: {
2487
3042
  deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
2488
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2489
- ...DS_UNAVAILABLE_MESSAGE
3043
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2490
3044
  }
2491
3045
  },
2492
3046
  createOnce(context) {
2493
- const getDS = createLazyLoader(context);
2494
3047
  function check(locations) {
2495
3048
  if (locations.length === 0) return;
2496
- if (!safeGetDS(getDS, context, locations[0].node)) return;
2497
3049
  for (const loc of locations) {
2498
3050
  const split = splitClassesWithSeparators(loc.value);
2499
3051
  const offending = split.classes.flatMap((cls) => {
@@ -2637,192 +3189,6 @@ const noUnknownClasses = defineRule({
2637
3189
  }
2638
3190
  });
2639
3191
  //#endregion
2640
- //#region src/rules/no-conflicting-classes/spec.ts
2641
- const COMPLEMENTARY_GROUPS = [
2642
- {
2643
- pattern: /^(from|via|to)-/,
2644
- reason: "Gradient stops (`from-*`, `via-*`, `to-*`) share `--tw-gradient-stops`; different prefixes compose, same prefix conflicts."
2645
- },
2646
- {
2647
- pattern: /^(transition|duration|ease|delay)(?:-|$)/,
2648
- reason: "`transition-*` composes with `duration-*`, `ease-*`, `delay-*` — `transition-all` itself has no `--tw-*` vars so the heuristic misses it."
2649
- },
2650
- {
2651
- pattern: /^-?(translate|scale|rotate|skew)-/,
2652
- reason: "Transform axes (translate / scale / rotate / skew) compose into a single `transform`; the overlap is not captured in `cssProps`."
2653
- },
2654
- {
2655
- pattern: /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
2656
- reason: "Mask gradients: different families (e.g. `mask-linear-*` vs `mask-radial-*`) or roles (`from`/`via`/`to`/`at`) compose; same family+role conflicts."
2657
- },
2658
- {
2659
- pattern: /^prose(?:-|$)/,
2660
- reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
2661
- }
2662
- ];
2663
- const COMPOSITION_PAIRS = [
2664
- {
2665
- a: /^text-/,
2666
- b: /^leading-/,
2667
- reason: "`text-*` sets line-height via its size token; `leading-*` overrides it."
2668
- },
2669
- {
2670
- a: /^text-/,
2671
- b: /^tracking-/,
2672
- reason: "`text-*` may set letter-spacing via its size token; `tracking-*` overrides it."
2673
- },
2674
- {
2675
- a: /^border(?:-[0-9]|$)/,
2676
- b: /^border-(?:solid|dashed|dotted|double|hidden|none)$/,
2677
- reason: "`border-*` (width) composes with `border-{solid,dashed,…}` (style)."
2678
- },
2679
- {
2680
- a: /^divide-/,
2681
- b: /^border(?:-[trblxyse])?-/,
2682
- reason: "`divide-*` styles direct children; `border-*` styles the element itself."
2683
- },
2684
- {
2685
- a: /^prose(?:-|$)/,
2686
- b: /^max-w-/,
2687
- reason: "`prose` sets a default max-width; `max-w-*` overrides it."
2688
- },
2689
- {
2690
- a: /^animate-in$/,
2691
- b: /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/,
2692
- reason: "`animate-in` initializes all `--tw-enter-*` vars; `*-in` modifiers each override one. (`tailwindcss-animate` / `tw-animate-css`.)"
2693
- },
2694
- {
2695
- a: /^animate-out$/,
2696
- b: /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/,
2697
- reason: "`animate-out` initializes all `--tw-exit-*` vars; `*-out` modifiers each override one."
2698
- },
2699
- {
2700
- a: /^mask-(?:add|subtract|intersect|exclude)$/,
2701
- b: /^-?mask-(?:linear|radial|conic|[trblxy])-/,
2702
- reason: "`mask-{add,subtract,intersect,exclude}` are mask-composite modes that compose with mask-gradient utilities."
2703
- }
2704
- ];
2705
- //#endregion
2706
- //#region src/rules/no-conflicting-classes.ts
2707
- /**
2708
- * Two utilities compose via CSS custom properties if both define their own
2709
- * --tw-* properties that don't overlap — they each contribute to a shared
2710
- * shorthand (e.g. `shadow` and `ring` both end up in `box-shadow` via
2711
- * different intermediate vars).
2712
- */
2713
- function isCompositionViaCssVars(propsA, propsB) {
2714
- const customA = propsA.filter((p) => p.startsWith("--"));
2715
- const customB = propsB.filter((p) => p.startsWith("--"));
2716
- if (customA.length === 0 || customB.length === 0) return false;
2717
- return !customA.some((p) => customB.includes(p));
2718
- }
2719
- /**
2720
- * Detect a narrowing override: the later class's CSS properties are a strict
2721
- * subset of the earlier class's, so the later class refines one of the
2722
- * shorthand's properties (size-4 h-6, rounded-t-lg rounded-tl-sm, truncate
2723
- * text-clip). Direction-sensitive: the inverse means the wider later class
2724
- * clobbers a prior narrower override.
2725
- */
2726
- function isNarrowingOverride(propsEarlier, propsLater) {
2727
- if (propsLater.length === 0 || propsLater.length >= propsEarlier.length) return false;
2728
- const setEarlier = new Set(propsEarlier);
2729
- return propsLater.every((p) => setEarlier.has(p));
2730
- }
2731
- /**
2732
- * Returns true if two classes (within the same variant) should NOT be reported
2733
- * as conflicting despite sharing CSS properties. Pure: regex tables are passed
2734
- * in (or default to the module-level constants).
2735
- */
2736
- function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
2737
- if (isCompositionViaCssVars(propsA, propsB)) return true;
2738
- if (isNarrowingOverride(propsA, propsB)) return true;
2739
- const ua = splitImportant(extractUtility(a)).bare;
2740
- const ub = splitImportant(extractUtility(b)).bare;
2741
- const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
2742
- for (const { pattern: re } of groups) {
2743
- const ma = ua.match(re);
2744
- const mb = ub.match(re);
2745
- if (!ma || !mb) continue;
2746
- if (ma[1] === void 0) return true;
2747
- if (ma[1] !== mb[1]) return true;
2748
- }
2749
- const pairs = rules.compositionPairs !== void 0 ? rules.compositionPairs.map(([a, b]) => ({
2750
- a,
2751
- b
2752
- })) : COMPOSITION_PAIRS;
2753
- for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
2754
- return false;
2755
- }
2756
- const noConflictingClasses = defineRule({
2757
- meta: {
2758
- type: "problem",
2759
- docs: { description: "Disallow Tailwind CSS classes that generate conflicting CSS properties" },
2760
- schema: [{
2761
- type: "object",
2762
- properties: { entryPoint: { type: "string" } },
2763
- additionalProperties: false
2764
- }],
2765
- defaultOptions: [{}],
2766
- messages: {
2767
- conflict: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
2768
- ...DS_UNAVAILABLE_MESSAGE
2769
- }
2770
- },
2771
- createOnce(context) {
2772
- const getDS = createLazyLoader(context);
2773
- function check(locations) {
2774
- if (locations.length === 0) return;
2775
- const ds = safeGetDS(getDS, context, locations[0].node);
2776
- if (!ds) return;
2777
- const { cache } = ds;
2778
- for (const loc of locations) {
2779
- const classes = splitClasses(loc.value);
2780
- if (classes.length < 2) continue;
2781
- const byVariant = /* @__PURE__ */ new Map();
2782
- for (const cls of classes) {
2783
- const variant = getVariantPrefix(cls);
2784
- const existing = byVariant.get(variant) ?? [];
2785
- existing.push(cls);
2786
- byVariant.set(variant, existing);
2787
- }
2788
- for (const [, variantClasses] of byVariant) {
2789
- if (variantClasses.length < 2) continue;
2790
- const propsMap = /* @__PURE__ */ new Map();
2791
- for (const cls of variantClasses) {
2792
- const props = cache.getCssProperties(splitImportant(extractUtility(cls)).bare);
2793
- propsMap.set(cls, props);
2794
- }
2795
- for (let i = 0; i < variantClasses.length; i++) {
2796
- const classA = variantClasses[i];
2797
- const propsA = propsMap.get(classA) ?? [];
2798
- for (let j = i + 1; j < variantClasses.length; j++) {
2799
- const classB = variantClasses[j];
2800
- if (classA === classB) continue;
2801
- const propsB = propsMap.get(classB) ?? [];
2802
- if (shouldSkipPair(classA, classB, propsA, propsB)) continue;
2803
- const propsBSet = new Set(propsB);
2804
- const overlap = propsA.filter((p) => propsBSet.has(p));
2805
- if (overlap.length > 0) {
2806
- const propList = overlap.length <= 3 ? `"${overlap.join("\", \"")}"` : `${overlap.length} CSS properties`;
2807
- context.report({
2808
- node: loc.node,
2809
- messageId: "conflict",
2810
- data: {
2811
- classA,
2812
- classB,
2813
- properties: propList
2814
- }
2815
- });
2816
- }
2817
- }
2818
- }
2819
- }
2820
- }
2821
- }
2822
- return createExtractorVisitors(context, check);
2823
- }
2824
- });
2825
- //#endregion
2826
3192
  //#region src/design-system/ds-worker.ts
2827
3193
  /**
2828
3194
  * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
@@ -2846,6 +3212,7 @@ const LENGTH_OFFSET = HEADER_INTS * 4;
2846
3212
  const DATA_OFFSET = 20;
2847
3213
  const INIT_TIMEOUT = 6e4;
2848
3214
  const REQUEST_TIMEOUT = 3e4;
3215
+ const MAX_WORKERS = 8;
2849
3216
  /**
2850
3217
  * Build the worker script shared by `sort-service` and `canonicalize-service`.
2851
3218
  * Owns the entire SharedArrayBuffer protocol (offsets derived from the same
@@ -2855,8 +3222,9 @@ const REQUEST_TIMEOUT = 3e4;
2855
3222
  * the request loop. `handlerExpr` is a function expression `(ds, request) =>
2856
3223
  * result` — the only part that differs between services.
2857
3224
  */
2858
- function makeWorkerScript(handlerExpr) {
3225
+ function makeWorkerScript(handlerExpr, preamble = "") {
2859
3226
  return `
3227
+ ${preamble}
2860
3228
  const { workerData } = require('worker_threads');
2861
3229
  async function main() {
2862
3230
  const { sharedBuffer, cssPath } = workerData;
@@ -2928,16 +3296,14 @@ main().catch(() => {});
2928
3296
  }
2929
3297
  var DesignSystemWorker = class {
2930
3298
  opts;
2931
- ready = null;
2932
- lastError = null;
2933
- lastErrorCssPath = null;
3299
+ workers = /* @__PURE__ */ new Map();
3300
+ errors = /* @__PURE__ */ new Map();
2934
3301
  constructor(opts) {
2935
3302
  this.opts = opts;
2936
3303
  }
2937
3304
  /** Record an error as sticky for `cssPath` and return it for `throw`. */
2938
3305
  remember(cssPath, err) {
2939
- this.lastError = err;
2940
- this.lastErrorCssPath = cssPath;
3306
+ this.errors.set(cssPath, err);
2941
3307
  return err;
2942
3308
  }
2943
3309
  /**
@@ -2947,11 +3313,14 @@ var DesignSystemWorker = class {
2947
3313
  * cssPath rethrow without retrying.
2948
3314
  */
2949
3315
  ensure(cssPath) {
2950
- if (this.lastError && this.lastErrorCssPath === cssPath) throw this.lastError;
2951
- if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2952
- if (this.ready) this.cleanup();
2953
- this.lastError = null;
2954
- this.lastErrorCssPath = null;
3316
+ const sticky = this.errors.get(cssPath);
3317
+ if (sticky) throw sticky;
3318
+ const existing = this.workers.get(cssPath);
3319
+ if (existing) {
3320
+ this.workers.delete(cssPath);
3321
+ this.workers.set(cssPath, existing);
3322
+ return existing;
3323
+ }
2955
3324
  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."));
2956
3325
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2957
3326
  const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
@@ -2972,8 +3341,9 @@ var DesignSystemWorker = class {
2972
3341
  }
2973
3342
  worker.unref();
2974
3343
  worker.on("error", (err) => {
2975
- 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 });
2976
- this.lastErrorCssPath = cssPath;
3344
+ 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 }));
3345
+ const current = this.workers.get(cssPath);
3346
+ if (current && current.worker === worker) this.workers.delete(cssPath);
2977
3347
  });
2978
3348
  if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2979
3349
  this.terminateWorker(worker);
@@ -2985,14 +3355,26 @@ var DesignSystemWorker = class {
2985
3355
  this.terminateWorker(worker);
2986
3356
  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."));
2987
3357
  }
2988
- this.ready = {
3358
+ const state = {
2989
3359
  worker,
2990
3360
  controlArray,
2991
3361
  lengthView,
2992
3362
  dataArea,
2993
3363
  cssPath
2994
3364
  };
2995
- return this.ready;
3365
+ this.workers.set(cssPath, state);
3366
+ this.evictIfNeeded();
3367
+ return state;
3368
+ }
3369
+ /** Evict least-recently-used workers past the cap (#77). */
3370
+ evictIfNeeded() {
3371
+ while (this.workers.size > MAX_WORKERS) {
3372
+ const oldestKey = this.workers.keys().next().value;
3373
+ if (oldestKey === void 0) break;
3374
+ const oldest = this.workers.get(oldestKey);
3375
+ this.workers.delete(oldestKey);
3376
+ if (oldest) this.terminateWorker(oldest.worker);
3377
+ }
2996
3378
  }
2997
3379
  /**
2998
3380
  * Send a request to the worker and synchronously wait for the response.
@@ -3007,7 +3389,7 @@ var DesignSystemWorker = class {
3007
3389
  Atomics.store(state.controlArray, 0, 1);
3008
3390
  Atomics.notify(state.controlArray, 0);
3009
3391
  if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
3010
- this.cleanup();
3392
+ this.dropWorker(cssPath);
3011
3393
  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."));
3012
3394
  }
3013
3395
  const responseLen = state.lengthView.getUint32(0);
@@ -3017,33 +3399,553 @@ var DesignSystemWorker = class {
3017
3399
  try {
3018
3400
  parsed = JSON.parse(responseStr);
3019
3401
  } catch (cause) {
3020
- this.cleanup();
3402
+ this.dropWorker(cssPath);
3021
3403
  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 }));
3022
3404
  }
3023
3405
  if (parsed === null) {
3024
- this.cleanup();
3406
+ this.dropWorker(cssPath);
3025
3407
  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."));
3026
3408
  }
3027
3409
  return parsed;
3028
3410
  }
3029
3411
  reset() {
3030
- this.cleanup();
3031
- this.lastError = null;
3032
- this.lastErrorCssPath = null;
3033
- }
3034
- cleanup() {
3035
- if (this.ready) {
3036
- this.terminateWorker(this.ready.worker);
3037
- this.ready = null;
3412
+ for (const state of this.workers.values()) this.terminateWorker(state.worker);
3413
+ this.workers.clear();
3414
+ this.errors.clear();
3415
+ }
3416
+ /** Terminate and forget the worker for a single cssPath (on request failure). */
3417
+ dropWorker(cssPath) {
3418
+ const state = this.workers.get(cssPath);
3419
+ if (state) {
3420
+ this.workers.delete(cssPath);
3421
+ this.terminateWorker(state.worker);
3038
3422
  }
3039
3423
  }
3040
3424
  terminateWorker(worker) {
3041
3425
  try {
3426
+ worker.removeAllListeners("error");
3042
3427
  worker.terminate();
3043
3428
  } catch {}
3044
3429
  }
3045
3430
  };
3046
3431
  //#endregion
3432
+ //#region src/design-system/declaration-service.ts
3433
+ const declWorker = new DesignSystemWorker({
3434
+ workerScript: makeWorkerScript(`(ds, request) => {
3435
+ const decls = {};
3436
+ const values = {};
3437
+ // A prefixed design system only resolves the PREFIXED form (\`tw:p-[5px]\`), and
3438
+ // the host asks with prefix-free names — \`extractUtility\` strips the project
3439
+ // prefix along with the variants. Same invariant the precompute follows: apply
3440
+ // the prefix only when talking to the design system, key everything returned
3441
+ // prefix-free. Without this the service resolved NOTHING in a prefixed project,
3442
+ // so every user-written value went silently uncompared.
3443
+ const prefix = (ds.theme && ds.theme.prefix) || '';
3444
+ const pfx = (c) => (prefix && !c.startsWith(prefix + ':')) ? prefix + ':' + c : c;
3445
+ const css = ds.candidatesToCss(request.classes.map(pfx));
3446
+ for (let i = 0; i < request.classes.length; i++) {
3447
+ if (!css[i]) continue;
3448
+ const cls = request.classes[i];
3449
+ const list = [];
3450
+ // The selector carries the prefix, so the scope classifier needs the
3451
+ // prefixed name even though the result is keyed by the bare one.
3452
+ walkDeclarations(css[i], pfx(cls), (scope, prop, value) => {
3453
+ list.push([scope, prop, value]);
3454
+ if (!(value in values)) {
3455
+ const reads = scanVarReads(value);
3456
+ values[value] = { p: reads[0], f: reads[1], u: isPureVarRead(value) };
3457
+ }
3458
+ });
3459
+ if (list.length > 0) decls[cls] = list;
3460
+ }
3461
+ return { decls, values };
3462
+ }`, DECL_EXTRACTOR_SOURCE),
3463
+ serviceName: "declarations"
3464
+ });
3465
+ /**
3466
+ * Classes already asked about, per design-system CACHE — not per entry point. A
3467
+ * miss is remembered too: a class the design system produces no CSS for must not
3468
+ * be re-queried on every AST node it appears in.
3469
+ *
3470
+ * The lifetime has to match the cache's, because that is where the answers are
3471
+ * interned. Keyed by path, a rebuilt cache (an mtime bump in a long-lived editor
3472
+ * process, or `resetDesignSystem()`) inherited a fully-populated set and could
3473
+ * never re-learn: the rule went permanently blind to user-written values with no
3474
+ * diagnostic. A WeakMap also means there is nothing to reset.
3475
+ */
3476
+ const queried = /* @__PURE__ */ new WeakMap();
3477
+ function queriedFor(cache) {
3478
+ let set = queried.get(cache);
3479
+ if (!set) {
3480
+ set = /* @__PURE__ */ new Set();
3481
+ queried.set(cache, set);
3482
+ }
3483
+ return set;
3484
+ }
3485
+ /**
3486
+ * Resolve declarations for `classes` that the precompute doesn't know.
3487
+ *
3488
+ * Returns null when the service is unavailable, which the caller treats as "no
3489
+ * information" — the same posture as a class with no declarations, so a broken
3490
+ * worker degrades to today's silence rather than to wrong diagnostics. Real
3491
+ * failures still surface through the sticky error the worker records.
3492
+ */
3493
+ function resolveDeclarationsSync(cssPath, cache, classes) {
3494
+ const seen = queriedFor(cache);
3495
+ const pending = classes.filter((cls) => !seen.has(cls));
3496
+ if (pending.length === 0) return null;
3497
+ for (const cls of pending) seen.add(cls);
3498
+ try {
3499
+ return declWorker.callSync(cssPath, { classes: pending });
3500
+ } catch (error) {
3501
+ if (error instanceof SortServiceError) return null;
3502
+ throw error;
3503
+ }
3504
+ }
3505
+ //#endregion
3506
+ //#region src/rules/no-conflicting-classes/spec.ts
3507
+ const COMPLEMENTARY_GROUPS = [{
3508
+ pattern: /^prose(?:-|$)/,
3509
+ reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
3510
+ }];
3511
+ const COMPOSITION_PAIRS = [
3512
+ {
3513
+ a: /^prose(?:-|$)/,
3514
+ b: /^max-w-/,
3515
+ reason: "`prose` sets a default max-width; `max-w-*` overrides it."
3516
+ },
3517
+ {
3518
+ a: /^prose(?:-|$)/,
3519
+ b: /^(?:text-|leading-|tracking-)/,
3520
+ reason: "`prose` sets default typographic values on the element; `text-*`/`leading-*`/`tracking-*` override them."
3521
+ },
3522
+ {
3523
+ a: /^-?(?:space|divide)-[xy](?:-|$)/,
3524
+ b: /^(?:space|divide)-[xy]-reverse$/,
3525
+ reason: "`space-*`/`divide-*` write the reverse flag as its default; `*-reverse` flips it — the documented way to space a reversed flex row."
3526
+ },
3527
+ {
3528
+ a: /^mask-(?:add|subtract|intersect|exclude)$/,
3529
+ b: /^-?mask-(?:linear|radial|conic|[trblxy])-/,
3530
+ reason: "`mask-{add,subtract,intersect,exclude}` are mask-composite modes that compose with mask-gradient utilities."
3531
+ }
3532
+ ];
3533
+ //#endregion
3534
+ //#region src/rules/no-conflicting-classes/decide.ts
3535
+ /** Builds the comparison key. Same property on two different boxes never clashes. */
3536
+ function declKey(decl) {
3537
+ return decl.scope === "element" ? decl.prop : `${decl.pseudo || ">"}|${decl.prop}`;
3538
+ }
3539
+ /** The property name a key refers to, for the diagnostic message. */
3540
+ function keyProp(key) {
3541
+ const sep = key.lastIndexOf("|");
3542
+ return sep < 0 ? key : key.slice(sep + 1);
3543
+ }
3544
+ /** How to describe a key's box in the message; empty for the element itself. */
3545
+ function keyScopeLabel(key) {
3546
+ const sep = key.indexOf("|");
3547
+ if (sep < 0) return "";
3548
+ const scope = key.slice(0, sep);
3549
+ return scope === ">" ? "direct children" : scope;
3550
+ }
3551
+ const NO_INFO_VALUES = /* @__PURE__ */ new Set([
3552
+ "",
3553
+ "initial",
3554
+ "unset"
3555
+ ]);
3556
+ const CLOSURE_LIMIT = 64;
3557
+ function collectFacts(classes) {
3558
+ const groupWrites = /* @__PURE__ */ new Set();
3559
+ const effectiveWriter = /* @__PURE__ */ new Map();
3560
+ for (const cls of classes) for (const varName of cls.writes.keys()) {
3561
+ groupWrites.add(varName);
3562
+ const current = effectiveWriter.get(varName);
3563
+ if (current === void 0 || cls.order !== null && (current.order === null || cls.order > current.order)) effectiveWriter.set(varName, cls);
3564
+ }
3565
+ return {
3566
+ groupWrites,
3567
+ effectiveWriter
3568
+ };
3569
+ }
3570
+ /** Splits `!` off and reports whether the class was important. */
3571
+ function isImportant(className) {
3572
+ return splitImportant(className).position !== null;
3573
+ }
3574
+ /**
3575
+ * Which custom properties a value actually depends on.
3576
+ *
3577
+ * A `var()` fallback is dead once the variable is supplied, so fallback reads
3578
+ * only count when a direct read is missing from the group. Without this,
3579
+ * `text-sm` would appear to need `--text-sm--line-height` — a token no utility
3580
+ * writes — and its composition with `leading-6` would read as a conflict.
3581
+ */
3582
+ function neededVars(decl, groupWrites) {
3583
+ const needed = [...decl.readsVars];
3584
+ if (!needed.every((v) => groupWrites.has(v))) {
3585
+ for (const v of decl.readsFallbackVars) if (!needed.includes(v)) needed.push(v);
3586
+ }
3587
+ return needed;
3588
+ }
3589
+ /**
3590
+ * Does the winner's declaration still pull in the loser's contribution?
3591
+ *
3592
+ * Walks the winner's variable reads, expanding each through the group's
3593
+ * effective writer, and hits when that chain reaches the loser. This is what
3594
+ * covers `drop-shadow-xl drop-shadow-indigo-500` directly and the gradient
3595
+ * family (`from-*` → `--tw-gradient-via-stops` → `via-*`) transitively.
3596
+ */
3597
+ function winnerAbsorbsLoser(winnerDecl, loser, group) {
3598
+ const seen = /* @__PURE__ */ new Set();
3599
+ const frontier = [...winnerDecl.readsVars, ...winnerDecl.readsFallbackVars];
3600
+ let steps = 0;
3601
+ while (frontier.length > 0 && steps++ < CLOSURE_LIMIT) {
3602
+ const varName = frontier.pop();
3603
+ if (seen.has(varName)) continue;
3604
+ seen.add(varName);
3605
+ const writer = group.effectiveWriter.get(varName);
3606
+ if (writer === loser) return true;
3607
+ if (!writer) continue;
3608
+ const written = writer.decls.get(varName);
3609
+ if (written) frontier.push(...written.readsVars, ...written.readsFallbackVars);
3610
+ }
3611
+ return false;
3612
+ }
3613
+ /**
3614
+ * Was the loser's declaration only forwarding a value someone else supplies?
3615
+ *
3616
+ * `outline-2` declares `outline-style: var(--tw-outline-style)` — it carries no
3617
+ * value of its own, and `outline-solid` both writes that variable and declares
3618
+ * the property concretely. Losing the forwarding declaration changes nothing.
3619
+ *
3620
+ * The three guards matter:
3621
+ * - variables the loser writes ITSELF are excluded, so `transform-none
3622
+ * rotate-x-45` (whose `transform` forwards four variables nobody supplies)
3623
+ * stays a conflict;
3624
+ * - the winner must supply one of them, otherwise an unrelated class that simply
3625
+ * outranks a reader/writer pair would silence a real clobber;
3626
+ * - a loser that forwards nothing (empty set) is carrying its own contribution.
3627
+ */
3628
+ function loserOnlyForwards(loserDecl, loser, winner, group) {
3629
+ if (!loserDecl.pureVarRead) return false;
3630
+ const needed = neededVars(loserDecl, group.groupWrites).filter((v) => !loser.writes.has(v));
3631
+ if (needed.length === 0) return false;
3632
+ if (!needed.every((v) => group.groupWrites.has(v))) return false;
3633
+ return needed.some((v) => winner.writes.has(v));
3634
+ }
3635
+ /** Resolves which of the two classes wins the cascade. `!` beats stylesheet order. */
3636
+ function resolveWinner(a, b) {
3637
+ if (a.important !== b.important) return a.important ? {
3638
+ winner: a,
3639
+ loser: b,
3640
+ orderKnown: true
3641
+ } : {
3642
+ winner: b,
3643
+ loser: a,
3644
+ orderKnown: true
3645
+ };
3646
+ if (a.order === null || b.order === null || a.order === b.order) return {
3647
+ winner: b,
3648
+ loser: a,
3649
+ orderKnown: false
3650
+ };
3651
+ return a.order > b.order ? {
3652
+ winner: a,
3653
+ loser: b,
3654
+ orderKnown: true
3655
+ } : {
3656
+ winner: b,
3657
+ loser: a,
3658
+ orderKnown: true
3659
+ };
3660
+ }
3661
+ /** A custom property cleared to a value that says nothing. */
3662
+ function isReset(decl) {
3663
+ return decl.prop.startsWith("--") && NO_INFO_VALUES.has(decl.value.trim());
3664
+ }
3665
+ /**
3666
+ * Is clearing variables the whole point of this class?
3667
+ *
3668
+ * `blur-none` writes `--tw-blur: ` and then only forwards the filter chain;
3669
+ * `animate-in` clears `--tw-enter-*` but also declares real values of its own.
3670
+ * The first cannot afford to lose its reset, the second can.
3671
+ */
3672
+ function resetIsAllTheClassDoes(cls) {
3673
+ let sawSubstance = false;
3674
+ for (const decl of cls.decls.values()) {
3675
+ if (isReset(decl)) continue;
3676
+ if (decl.pureVarRead) continue;
3677
+ sawSubstance = true;
3678
+ break;
3679
+ }
3680
+ return !sawSubstance;
3681
+ }
3682
+ /** Does the surviving declaration reproduce what the other one contributed? */
3683
+ function composes(winnerDecl, winner, loserDecl, loser, group) {
3684
+ return winnerAbsorbsLoser(winnerDecl, loser, group) || loserOnlyForwards(loserDecl, loser, winner, group);
3685
+ }
3686
+ function decidePair(a, b, group) {
3687
+ const { winner, loser, orderKnown } = resolveWinner(a, b);
3688
+ const conflicts = [];
3689
+ const duplicates = [];
3690
+ for (const [key, loserDecl] of loser.decls) {
3691
+ const winnerDecl = winner.decls.get(key);
3692
+ if (!winnerDecl) continue;
3693
+ if (loser.ambiguousKeys.has(key) || winner.ambiguousKeys.has(key)) continue;
3694
+ if (loserDecl.valueId === winnerDecl.valueId) {
3695
+ duplicates.push(key);
3696
+ continue;
3697
+ }
3698
+ if (isReset(loserDecl) && !resetIsAllTheClassDoes(loser)) continue;
3699
+ if (composes(winnerDecl, winner, loserDecl, loser, group)) continue;
3700
+ if (!orderKnown && composes(loserDecl, loser, winnerDecl, winner, group)) continue;
3701
+ conflicts.push(key);
3702
+ }
3703
+ return {
3704
+ winner,
3705
+ loser,
3706
+ conflicts,
3707
+ duplicates,
3708
+ orderKnown
3709
+ };
3710
+ }
3711
+ /**
3712
+ * Which class (if any) is dead weight: every declaration it makes is also made,
3713
+ * identically, by the other one. A `partial` class is never named — its CSS is
3714
+ * only partly modelled, so "it adds nothing" would be a guess.
3715
+ */
3716
+ function redundantSide(verdict) {
3717
+ if (verdict.conflicts.length > 0 || verdict.duplicates.length === 0) return null;
3718
+ const dup = new Set(verdict.duplicates);
3719
+ const covered = (c) => c.decls.size > 0 && [...c.decls.keys()].every((k) => dup.has(k));
3720
+ if (!verdict.loser.partial && covered(verdict.loser)) return {
3721
+ loser: verdict.loser,
3722
+ winner: verdict.winner
3723
+ };
3724
+ if (!verdict.winner.partial && covered(verdict.winner)) return {
3725
+ loser: verdict.winner,
3726
+ winner: verdict.loser
3727
+ };
3728
+ return null;
3729
+ }
3730
+ //#endregion
3731
+ //#region src/rules/no-conflicting-classes.ts
3732
+ /**
3733
+ * Compiles the `allow` option.
3734
+ *
3735
+ * A bare pattern silences every pair involving a matching class; a two-element
3736
+ * pattern silences that specific combination. This is the supported way to teach
3737
+ * the rule about a stack we cannot derive — nobody should have to wait for a
3738
+ * release of this plugin to silence a combination their own plugins produce.
3739
+ */
3740
+ function compileAllow(allow) {
3741
+ const allowClasses = [];
3742
+ const allowPairs = [];
3743
+ for (const entry of allow ?? []) {
3744
+ if (typeof entry === "string") {
3745
+ allowClasses.push(entry);
3746
+ continue;
3747
+ }
3748
+ const [a, b] = compileRegexList(entry);
3749
+ if (a && b) allowPairs.push([a, b]);
3750
+ }
3751
+ return {
3752
+ allowClasses: compileRegexList(allowClasses),
3753
+ allowPairs
3754
+ };
3755
+ }
3756
+ /**
3757
+ * Returns true if two classes (within the same variant) should NOT be compared
3758
+ * at all, despite sharing CSS properties. Pure: regex tables are passed in (or
3759
+ * default to the module-level constants).
3760
+ *
3761
+ * These tables are the exception, not the mechanism: everything a comparison of
3762
+ * the generated CSS can decide is decided in `decide.ts`. What survives here is
3763
+ * plugin intent that no CSS comparison can see — see `spec.ts` for why each
3764
+ * entry cannot be derived.
3765
+ */
3766
+ function shouldSkipPair(a, b, rules = {}) {
3767
+ const ua = splitImportant(extractUtility(a)).bare;
3768
+ const ub = splitImportant(extractUtility(b)).bare;
3769
+ const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
3770
+ for (const { pattern: re } of groups) {
3771
+ const ma = ua.match(re);
3772
+ const mb = ub.match(re);
3773
+ if (!ma || !mb) continue;
3774
+ if (ma[1] === void 0) return true;
3775
+ if (ma[1] !== mb[1]) return true;
3776
+ }
3777
+ const pairs = rules.compositionPairs !== void 0 ? rules.compositionPairs.map(([a, b]) => ({
3778
+ a,
3779
+ b
3780
+ })) : COMPOSITION_PAIRS;
3781
+ for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
3782
+ return false;
3783
+ }
3784
+ /**
3785
+ * A class the precompute cannot have enumerated: the value is written by the
3786
+ * user, not by the design system's class list. Asking the design system about
3787
+ * these is what closes the false negatives — `p-4 p-[5px]` used to be silently
3788
+ * accepted while `p-4 p-6` reported.
3789
+ */
3790
+ function isUserValued(utility) {
3791
+ return utility.includes("[") || utility.includes("(") || utility.includes("/") || /-\d/.test(utility);
3792
+ }
3793
+ /** Whether the user's `allow` option silences this pair. */
3794
+ function isAllowed(a, b, allowClasses, allowPairs) {
3795
+ if (matchesAny(a, allowClasses) || matchesAny(b, allowClasses)) return true;
3796
+ return allowPairs.some(([reA, reB]) => reA.test(a) && reB.test(b) || reA.test(b) && reB.test(a));
3797
+ }
3798
+ /**
3799
+ * `"color"` / `"color", "width"` / `3 CSS properties`, naming the box when it
3800
+ * isn't the element. A pair can clash on several boxes at once (a plugin utility
3801
+ * that styles itself and a `::-webkit-scrollbar` pseudo-element), so the label
3802
+ * goes per property unless every property shares the same box.
3803
+ */
3804
+ function formatProperties(keys) {
3805
+ const scopes = new Set(keys.map(keyScopeLabel));
3806
+ if (scopes.size > 1) {
3807
+ const labelled = [...new Set(keys.map((key) => {
3808
+ const scope = keyScopeLabel(key);
3809
+ return scope ? `"${keyProp(key)}" (${scope})` : `"${keyProp(key)}"`;
3810
+ }))];
3811
+ return labelled.length <= 3 ? labelled.join(", ") : `${labelled.length} CSS properties`;
3812
+ }
3813
+ const props = [...new Set(keys.map(keyProp))];
3814
+ const list = props.length <= 3 ? `"${props.join("\", \"")}"` : `${props.length} CSS properties`;
3815
+ const scope = [...scopes][0];
3816
+ return scope ? `${list} (${scope})` : list;
3817
+ }
3818
+ const noConflictingClasses = defineRule({
3819
+ meta: {
3820
+ type: "problem",
3821
+ docs: { description: "Disallow Tailwind CSS classes that generate conflicting CSS properties" },
3822
+ schema: [{
3823
+ type: "object",
3824
+ properties: {
3825
+ entryPoint: { type: "string" },
3826
+ reportRedundant: { type: "boolean" },
3827
+ allow: {
3828
+ type: "array",
3829
+ items: { oneOf: [{ type: "string" }, {
3830
+ type: "array",
3831
+ items: { type: "string" },
3832
+ minItems: 2,
3833
+ maxItems: 2
3834
+ }] }
3835
+ }
3836
+ },
3837
+ additionalProperties: false
3838
+ }],
3839
+ defaultOptions: [{ reportRedundant: true }],
3840
+ messages: {
3841
+ 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.",
3842
+ conflictUnordered: "\"{{classA}}\" and \"{{classB}}\" both affect {{properties}}. Only one applies — which wins depends on the generated stylesheet order, not the attribute order. Remove one.",
3843
+ redundant: "\"{{loser}}\" has no effect: \"{{winner}}\" declares {{properties}} with the same value. Remove \"{{loser}}\".",
3844
+ ...DS_UNAVAILABLE_MESSAGE
3845
+ }
3846
+ },
3847
+ createOnce(context) {
3848
+ const getDS = createLazyLoader(context);
3849
+ const getOptions = createLazyOptions(context, (o) => ({
3850
+ reportRedundant: o?.reportRedundant ?? true,
3851
+ ...compileAllow(o?.allow)
3852
+ }));
3853
+ function check(locations) {
3854
+ if (locations.length === 0) return;
3855
+ const ds = safeGetDS(getDS, context, locations[0].node);
3856
+ if (!ds) return;
3857
+ const { cache } = ds;
3858
+ const { reportRedundant, allowClasses, allowPairs } = getOptions();
3859
+ for (const loc of locations) {
3860
+ const classes = splitClasses(loc.value);
3861
+ if (classes.length < 2) continue;
3862
+ const byVariant = /* @__PURE__ */ new Map();
3863
+ for (const cls of classes) {
3864
+ const variant = getVariantPrefix(cls);
3865
+ const existing = byVariant.get(variant) ?? [];
3866
+ existing.push(cls);
3867
+ byVariant.set(variant, existing);
3868
+ }
3869
+ for (const [, variantClasses] of byVariant) {
3870
+ if (variantClasses.length < 2) continue;
3871
+ const unknown = variantClasses.map((cls) => splitImportant(extractUtility(cls)).bare).filter((bare) => cache.getCssDeclarations(bare).length === 0 && isUserValued(bare));
3872
+ if (unknown.length > 0) {
3873
+ const resolved = resolveDeclarationsSync(ds.entryPoint, cache, unknown);
3874
+ if (resolved) for (const [cls, raws] of Object.entries(resolved.decls)) cache.internDeclarations(cls, raws, resolved.values);
3875
+ }
3876
+ const facts = variantClasses.map((cls) => {
3877
+ const utility = extractUtility(cls);
3878
+ const bare = splitImportant(utility).bare;
3879
+ const declarations = cache.getCssDeclarations(bare);
3880
+ const decls = /* @__PURE__ */ new Map();
3881
+ const writes = /* @__PURE__ */ new Map();
3882
+ const ambiguousKeys = /* @__PURE__ */ new Set();
3883
+ for (const decl of declarations) {
3884
+ if (decl.conditional) continue;
3885
+ const key = declKey(decl);
3886
+ const previous = decls.get(key);
3887
+ if (previous && previous.valueId !== decl.valueId) ambiguousKeys.add(key);
3888
+ decls.set(key, decl);
3889
+ if (decl.prop.startsWith("--")) writes.set(decl.prop, decl.valueId);
3890
+ }
3891
+ return {
3892
+ className: cls,
3893
+ decls,
3894
+ writes,
3895
+ order: cache.hasExactOrder(utility) ? cache.getOrder(cls) : null,
3896
+ important: isImportant(utility),
3897
+ partial: cache.isPartial(bare),
3898
+ ambiguousKeys
3899
+ };
3900
+ });
3901
+ const group = collectFacts(facts);
3902
+ for (let i = 0; i < facts.length; i++) for (let j = i + 1; j < facts.length; j++) {
3903
+ const a = facts[i];
3904
+ const b = facts[j];
3905
+ if (a.className === b.className) continue;
3906
+ if (shouldSkipPair(a.className, b.className)) continue;
3907
+ if (isAllowed(a.className, b.className, allowClasses, allowPairs)) continue;
3908
+ const verdict = decidePair(a, b, group);
3909
+ if (verdict.conflicts.length > 0) {
3910
+ const properties = formatProperties(verdict.conflicts);
3911
+ context.report(verdict.orderKnown ? {
3912
+ node: loc.node,
3913
+ messageId: "conflict",
3914
+ data: {
3915
+ winner: verdict.winner.className,
3916
+ loser: verdict.loser.className,
3917
+ properties
3918
+ }
3919
+ } : {
3920
+ node: loc.node,
3921
+ messageId: "conflictUnordered",
3922
+ data: {
3923
+ classA: a.className,
3924
+ classB: b.className,
3925
+ properties
3926
+ }
3927
+ });
3928
+ continue;
3929
+ }
3930
+ if (!reportRedundant) continue;
3931
+ const dead = redundantSide(verdict);
3932
+ if (dead) context.report({
3933
+ node: loc.node,
3934
+ messageId: "redundant",
3935
+ data: {
3936
+ loser: dead.loser.className,
3937
+ winner: dead.winner.className,
3938
+ properties: formatProperties(verdict.duplicates)
3939
+ }
3940
+ });
3941
+ }
3942
+ }
3943
+ }
3944
+ }
3945
+ return createExtractorVisitors(context, check);
3946
+ }
3947
+ });
3948
+ //#endregion
3047
3949
  //#region src/design-system/canonicalize-service.ts
3048
3950
  /**
3049
3951
  * Persistent canonicalize service backed by `DesignSystemWorker`.
@@ -3060,24 +3962,196 @@ var DesignSystemWorker = class {
3060
3962
  * after the first few files any given class has been seen, and every
3061
3963
  * subsequent lookup is O(1).
3062
3964
  */
3063
- const canonWorker = new DesignSystemWorker({
3064
- workerScript: makeWorkerScript(`(ds, request) => {
3965
+ const WORKER_SCRIPT = makeWorkerScript(`(ds, request) => {
3065
3966
  const { classes, rem } = request;
3066
3967
  const options = rem ? { rem } : undefined;
3968
+ const declsOf = (cls) => {
3969
+ let out;
3970
+ try { out = ds.candidatesToCss([cls]); } catch (e) { return null; }
3971
+ if (!out || !out[0]) return null;
3972
+ const css = out[0];
3973
+ const open = css.indexOf('{');
3974
+ const close = css.lastIndexOf('}');
3975
+ if (open < 0 || close < 0) return null;
3976
+ return css.slice(open + 1, close).replace(/\\s+/g, ' ').trim();
3977
+ };
3067
3978
  return classes.map((cls) => {
3068
3979
  const r = ds.canonicalizeCandidates([cls], options);
3069
- return r[0] ?? cls;
3980
+ const canonical = r[0] ?? cls;
3981
+ if (canonical === cls) return { canonical: cls, safe: true };
3982
+ const a = declsOf(cls);
3983
+ const b = declsOf(canonical);
3984
+ return { canonical, safe: a !== null && b !== null && a === b };
3070
3985
  });
3071
- }`),
3986
+ }`);
3987
+ const canonWorker = new DesignSystemWorker({
3988
+ workerScript: WORKER_SCRIPT,
3072
3989
  serviceName: "canonicalize"
3073
3990
  });
3074
3991
  /**
3075
3992
  * Process-wide cache of canonicalized classes.
3076
3993
  * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
3077
- * DSs) and different rem settings. Value: canonicalized class string.
3994
+ * DSs) and different rem settings. Value: the canonical form + its #78 `safe`
3995
+ * flag.
3078
3996
  */
3079
3997
  const canonCache = /* @__PURE__ */ new Map();
3080
3998
  /**
3999
+ * ## Disk persistence (per design system + rem)
4000
+ *
4001
+ * Each `oxlint` invocation is a fresh process, so without persistence every
4002
+ * unique dynamic class (`p-[2px]`, `bg-(--c)`, …) pays a synchronous worker
4003
+ * round-trip again on every run — on arbitrary-value-heavy codebases this
4004
+ * dominates the whole lint (seconds per run, issue: enforce-canonical perf).
4005
+ *
4006
+ * The canonical results are pure functions of the design system + rem + the
4007
+ * canonicalization logic, so we persist them next to the DS precompute
4008
+ * artifact, deriving the filename from `cacheArtifactPaths(cssPath).json`
4009
+ * (content-hash keyed) plus `CANON_LOGIC_HASH` (below). When the DS changes,
4010
+ * the artifact hash changes; when the canonicalization logic changes, the
4011
+ * logic hash changes — either way the canonical cache invalidates with it, so
4012
+ * no manual version bump is needed and stale values can never reach an autofix.
4013
+ *
4014
+ * We persist the full `CanonicalizeResult` (`canonical` + the #78 `safe`
4015
+ * flag), not just the string: `safe` gates whether `enforce-canonical`
4016
+ * actually applies the rewrite, so dropping it on restore would re-introduce
4017
+ * the unsafe-autofix bug #78 fixed.
4018
+ *
4019
+ * Best-effort everywhere: a missing/corrupt/unwritable cache file must never
4020
+ * break linting — it only costs worker round-trips.
4021
+ */
4022
+ const CANON_LOGIC_HASH = (0, node_crypto.createHash)("md5").update(WORKER_SCRIPT + roundRemValue.toString()).digest("hex").slice(0, 8);
4023
+ let tmpSeq = 0;
4024
+ const LOCK_STALE_MS = 1e4;
4025
+ /** One persistence state per `${cssPath}\0${rem}\0` cache prefix. */
4026
+ const persistStates = /* @__PURE__ */ new Map();
4027
+ function tryUnlink(path) {
4028
+ try {
4029
+ (0, node_fs.unlinkSync)(path);
4030
+ } catch {}
4031
+ }
4032
+ /**
4033
+ * Reclaim a stale lock via exclusive rename rather than unlink (mirrors
4034
+ * sync-loader.ts): two isolates that both judge the lock stale would otherwise
4035
+ * both unlink it, and the second could delete a FRESH lock a third isolate just
4036
+ * created. `renameSync` has a single winner; the loser gets ENOENT and moves on.
4037
+ */
4038
+ function reclaimStaleLock(lockPath) {
4039
+ let ageMs;
4040
+ try {
4041
+ ageMs = Date.now() - (0, node_fs.statSync)(lockPath).mtimeMs;
4042
+ } catch {
4043
+ return;
4044
+ }
4045
+ if (ageMs < LOCK_STALE_MS) return;
4046
+ const reclaimPath = `${lockPath}.reclaim.${process.pid}.${node_worker_threads.threadId}.${tmpSeq++}`;
4047
+ try {
4048
+ (0, node_fs.renameSync)(lockPath, reclaimPath);
4049
+ } catch {
4050
+ return;
4051
+ }
4052
+ tryUnlink(reclaimPath);
4053
+ }
4054
+ /**
4055
+ * Acquire the per-file flush lock by atomic exclusive create (`wx`). The lock
4056
+ * serializes the read-merge-write below so concurrent isolates don't clobber
4057
+ * each other's entries (last-writer-wins → the cache would otherwise only
4058
+ * converge over several runs). Distinguishes contention (another isolate is
4059
+ * mid-flush — skip and retry next threshold) from an unwritable dir (give up).
4060
+ */
4061
+ function acquireFlushLock(lockPath) {
4062
+ const tryCreate = () => {
4063
+ try {
4064
+ (0, node_fs.closeSync)((0, node_fs.openSync)(lockPath, "wx"));
4065
+ return "acquired";
4066
+ } catch (e) {
4067
+ return e.code === "EEXIST" ? "contended" : "unavailable";
4068
+ }
4069
+ };
4070
+ const first = tryCreate();
4071
+ if (first !== "contended") return first;
4072
+ reclaimStaleLock(lockPath);
4073
+ return tryCreate();
4074
+ }
4075
+ /** Exported for tests: the exact on-disk cache path for a (cssPath, rem). */
4076
+ function persistFileFor(cssPath, rem) {
4077
+ try {
4078
+ const { json } = cacheArtifactPaths(cssPath);
4079
+ const remKey = rem === void 0 ? "default" : String(rem);
4080
+ return json.replace(/\.json$/, `.canon-${CANON_LOGIC_HASH}-${remKey}.json`);
4081
+ } catch {
4082
+ return null;
4083
+ }
4084
+ }
4085
+ /** Load the persisted map (if any) into `canonCache`, and set up flushing. */
4086
+ function ensurePersistLoaded(cssPath, rem, cachePrefix) {
4087
+ if (persistStates.has(cachePrefix)) return;
4088
+ const file = persistFileFor(cssPath, rem);
4089
+ if (file === null) {
4090
+ persistStates.set(cachePrefix, {
4091
+ file: "",
4092
+ dirty: -1
4093
+ });
4094
+ return;
4095
+ }
4096
+ const state = {
4097
+ file,
4098
+ dirty: 0
4099
+ };
4100
+ persistStates.set(cachePrefix, state);
4101
+ try {
4102
+ const data = JSON.parse((0, node_fs.readFileSync)(file, "utf-8"));
4103
+ if (typeof data === "object" && data !== null) {
4104
+ for (const [cls, entry] of Object.entries(data)) if (Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "boolean") canonCache.set(cachePrefix + cls, {
4105
+ canonical: entry[0],
4106
+ safe: entry[1]
4107
+ });
4108
+ }
4109
+ } catch {}
4110
+ }
4111
+ /**
4112
+ * Persist this prefix's entries under a per-file lock, merging with whatever is
4113
+ * already on disk first. oxlint worker threads are separate JS isolates, each
4114
+ * with its own in-memory `canonCache`, so the file is their shared channel: a
4115
+ * bare overwrite would clobber the entries other isolates persisted
4116
+ * (last-writer-wins), leaving the cache to converge only over several runs.
4117
+ * Read-merge-write under the lock makes it converge in one.
4118
+ */
4119
+ function flushPersist(cachePrefix, state) {
4120
+ if (state.dirty <= 0) return;
4121
+ const lockPath = `${state.file}.lock`;
4122
+ const lock = acquireFlushLock(lockPath);
4123
+ if (lock === "contended") return;
4124
+ if (lock === "unavailable") {
4125
+ state.dirty = -1;
4126
+ return;
4127
+ }
4128
+ try {
4129
+ const merged = Object.create(null);
4130
+ try {
4131
+ const existing = JSON.parse((0, node_fs.readFileSync)(state.file, "utf-8"));
4132
+ if (typeof existing === "object" && existing !== null) {
4133
+ for (const [cls, entry] of Object.entries(existing)) if (Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "boolean") {
4134
+ merged[cls] = [entry[0], entry[1]];
4135
+ const key = cachePrefix + cls;
4136
+ if (!canonCache.has(key)) canonCache.set(key, {
4137
+ canonical: entry[0],
4138
+ safe: entry[1]
4139
+ });
4140
+ }
4141
+ }
4142
+ } catch {}
4143
+ for (const [key, value] of canonCache) if (key.startsWith(cachePrefix)) merged[key.slice(cachePrefix.length)] = [value.canonical, value.safe];
4144
+ const tmp = `${state.file}.${process.pid}.${node_worker_threads.threadId}.${tmpSeq++}.tmp`;
4145
+ (0, node_fs.writeFileSync)(tmp, JSON.stringify(merged));
4146
+ (0, node_fs.renameSync)(tmp, state.file);
4147
+ state.dirty = 0;
4148
+ } catch {
4149
+ state.dirty = -1;
4150
+ } finally {
4151
+ tryUnlink(lockPath);
4152
+ }
4153
+ }
4154
+ /**
3081
4155
  * Canonicalize classes via the worker thread.
3082
4156
  *
3083
4157
  * Throws `SortServiceError` on any worker failure (init timeout, request
@@ -3093,6 +4167,7 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
3093
4167
  const missingIdx = [];
3094
4168
  const missing = [];
3095
4169
  const cachePrefix = `${cssPath}\0${rem ?? ""}\0`;
4170
+ ensurePersistLoaded(cssPath, rem, cachePrefix);
3096
4171
  for (let i = 0; i < classes.length; i++) {
3097
4172
  const key = cachePrefix + classes[i];
3098
4173
  const hit = canonCache.get(key);
@@ -3113,10 +4188,22 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
3113
4188
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
3114
4189
  for (let j = 0; j < missing.length; j++) {
3115
4190
  const cls = missing[j];
3116
- const value = roundRemValue(freshByClass.get(cls) ?? cls);
4191
+ const raw = freshByClass.get(cls) ?? {
4192
+ canonical: cls,
4193
+ safe: true
4194
+ };
4195
+ const value = {
4196
+ canonical: roundRemValue(raw.canonical),
4197
+ safe: raw.safe
4198
+ };
3117
4199
  canonCache.set(cachePrefix + cls, value);
3118
4200
  out[missingIdx[j]] = value;
3119
4201
  }
4202
+ const state = persistStates.get(cachePrefix);
4203
+ if (state && state.dirty >= 0) {
4204
+ state.dirty += uniqueMissing.length;
4205
+ flushPersist(cachePrefix, state);
4206
+ }
3120
4207
  return out;
3121
4208
  }
3122
4209
  //#endregion
@@ -3181,7 +4268,10 @@ const enforceCanonical = defineRule({
3181
4268
  const rem = getRem();
3182
4269
  const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
3183
4270
  if (!dynamic) return;
3184
- for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
4271
+ for (let k = 0; k < arbitrary.length; k++) {
4272
+ const { canonical, safe } = dynamic[k];
4273
+ canonicals[arbitraryIdx[k]] = safe ? preserveImportantPosition(arbitrary[k], canonical) : arbitrary[k];
4274
+ }
3185
4275
  }
3186
4276
  reportClassReplacements(context, loc, split, classes, classes.flatMap((cls, i) => canonicals[i] === cls ? [] : [{
3187
4277
  cls,
@@ -4215,11 +5305,27 @@ const noContradictingVariants = defineRule({
4215
5305
  meta: {
4216
5306
  type: "suggestion",
4217
5307
  docs: { description: "Disallow variant-prefixed classes that are redundant because the base class already applies unconditionally" },
4218
- schema: [],
5308
+ schema: [{
5309
+ type: "object",
5310
+ properties: { entryPoint: { type: "string" } },
5311
+ additionalProperties: false
5312
+ }],
5313
+ defaultOptions: [{}],
4219
5314
  messages: { redundantVariant: "\"{{variantClass}}\" is redundant because \"{{baseClass}}\" already applies unconditionally." }
4220
5315
  },
4221
5316
  createOnce(context) {
5317
+ const getDS = createLazyLoader(context);
5318
+ function variantFactsLookup() {
5319
+ try {
5320
+ const ds = getDS();
5321
+ return (variant) => ds.cache.getVariantFacts(variant);
5322
+ } catch (err) {
5323
+ if (!isFatalError(err)) throw err;
5324
+ return () => void 0;
5325
+ }
5326
+ }
4222
5327
  function check(locations) {
5328
+ const factsFor = variantFactsLookup();
4223
5329
  for (const loc of locations) {
4224
5330
  const classes = splitClasses(loc.value);
4225
5331
  const baseUtilities = /* @__PURE__ */ new Set();
@@ -4227,7 +5333,7 @@ const noContradictingVariants = defineRule({
4227
5333
  for (const cls of classes) {
4228
5334
  const variants = extractVariants(cls);
4229
5335
  if (variants.length === 0) continue;
4230
- if (variants.some(changesTarget)) continue;
5336
+ if (variants.some((v) => changesTarget(v, factsFor(v)))) continue;
4231
5337
  const utility = extractUtility(cls);
4232
5338
  if (baseUtilities.has(utility)) context.report({
4233
5339
  node: loc.node,
@@ -4384,11 +5490,12 @@ const consistentVariantOrder = defineRule({
4384
5490
  }
4385
5491
  return {
4386
5492
  priorityOf,
4387
- prefix
5493
+ prefix,
5494
+ factsFor: dsCache ? (variant) => dsCache.getVariantFacts(variant) : () => void 0
4388
5495
  };
4389
5496
  }
4390
5497
  function reorderClass(cls) {
4391
- const { priorityOf, prefix } = resolveForFile();
5498
+ const { priorityOf, prefix, factsFor } = resolveForFile();
4392
5499
  let pfx = "";
4393
5500
  let body = cls;
4394
5501
  if (prefix && cls.startsWith(prefix + ":")) {
@@ -4399,7 +5506,7 @@ const consistentVariantOrder = defineRule({
4399
5506
  if (variants.length < 2) return null;
4400
5507
  const pseudo = [];
4401
5508
  const rest = [];
4402
- for (const v of variants) if (isPseudoElementVariant(v)) pseudo.push(v);
5509
+ for (const v of variants) if (isPseudoElementVariant(v, factsFor(v))) pseudo.push(v);
4403
5510
  else rest.push(v);
4404
5511
  const reorderedRest = [];
4405
5512
  let segment = [];
@@ -4409,7 +5516,7 @@ const consistentVariantOrder = defineRule({
4409
5516
  reorderedRest.push(...segment);
4410
5517
  segment = [];
4411
5518
  };
4412
- for (const v of rest) if (isSelectorBarrier(v)) {
5519
+ for (const v of rest) if (isSelectorBarrier(v, factsFor(v))) {
4413
5520
  flushSegment();
4414
5521
  reorderedRest.push(v);
4415
5522
  } else segment.push(v);
@@ -4675,6 +5782,9 @@ const plugin = definePlugin({
4675
5782
  if (!match) return [];
4676
5783
  const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
4677
5784
  if (!cache.isValid(candidate)) return [];
5785
+ const target = `--${match.varName}`;
5786
+ const baseCandidate = `${match.prefix}-${match.varName}`;
5787
+ if (!cache.getCssDeclarations(baseCandidate).some((decl) => [...decl.readsVars, ...decl.readsFallbackVars].some((read) => cache.themeVarResolvesTo(read, target))) && cache.definesVar(target)) return [];
4678
5788
  const namedEquivalent = cache.getNamedEquivalent(bareUtility);
4679
5789
  if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
4680
5790
  return [{