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