oxlint-tailwindcss 0.8.0 → 1.0.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
@@ -2,7 +2,7 @@ import { createRequire } from "node:module";
2
2
  import { definePlugin, defineRule } from "@oxlint/plugins";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { createHash } from "node:crypto";
5
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
5
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join, relative, resolve } from "node:path";
7
7
  import { tmpdir } from "node:os";
8
8
  import { Worker } from "node:worker_threads";
@@ -44,8 +44,7 @@ const DEFAULT_EXTRACTOR_CONFIG = {
44
44
  /^styles?$/
45
45
  ]
46
46
  };
47
- let _cachedConfig = null;
48
- let _settingsResolved = false;
47
+ const configCache = /* @__PURE__ */ new WeakMap();
49
48
  function mergeUnique(defaults, extras, exclusions) {
50
49
  let base = defaults;
51
50
  if (exclusions && exclusions.length > 0) {
@@ -58,34 +57,39 @@ function mergeUnique(defaults, extras, exclusions) {
58
57
  return [...set];
59
58
  }
60
59
  /**
61
- * Returns the extractor config, merging defaults with user settings from
62
- * `settings.tailwindcss`. Caches after the first successful settings read.
63
- * Falls back to DEFAULT_EXTRACTOR_CONFIG if settings are unavailable.
60
+ * Returns the extractor config for this rule context, merging defaults with
61
+ * user settings from `settings.tailwindcss`. The result is cached per
62
+ * context (WeakMap-keyed) so settings are read once per rule lifetime.
63
+ *
64
+ * In `createOnce` the settings getter throws — we fall back to the defaults
65
+ * without caching so the next visitor call (where settings ARE available)
66
+ * still resolves the user's overrides.
64
67
  */
65
68
  function getExtractorConfig(context) {
66
- if (_settingsResolved) return _cachedConfig;
69
+ const cached = configCache.get(context);
70
+ if (cached) return cached;
67
71
  let tw;
68
72
  try {
69
73
  const raw = context.settings?.tailwindcss;
70
74
  if (raw && typeof raw === "object") tw = raw;
71
- _settingsResolved = true;
72
75
  } catch {
73
76
  return DEFAULT_EXTRACTOR_CONFIG;
74
77
  }
75
78
  if (!tw) {
76
- _cachedConfig = DEFAULT_EXTRACTOR_CONFIG;
77
- return _cachedConfig;
79
+ configCache.set(context, DEFAULT_EXTRACTOR_CONFIG);
80
+ return DEFAULT_EXTRACTOR_CONFIG;
78
81
  }
79
82
  const exclude = tw.exclude;
80
83
  const excludedPatternSources = new Set(exclude?.variablePatterns ?? []);
81
84
  const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
82
- _cachedConfig = {
85
+ const resolved = {
83
86
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
84
87
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
85
88
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
86
89
  variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
87
90
  };
88
- return _cachedConfig;
91
+ configCache.set(context, resolved);
92
+ return resolved;
89
93
  }
90
94
  /**
91
95
  * Creates the 4 standard AST visitor callbacks that all rules use.
@@ -138,7 +142,7 @@ function extractFromCallExpression(node, config = DEFAULT_EXTRACTOR_CONFIG) {
138
142
  if (calleeName === "tv") return extractFromTvCall(node);
139
143
  if (calleeName === "classed") return extractFromClassedCall(node);
140
144
  const results = [];
141
- for (const arg of node.arguments) results.push(...extractFromExpression(arg));
145
+ for (const arg of node.arguments) extractFromExpression(arg, results);
142
146
  return results;
143
147
  }
144
148
  /**
@@ -156,7 +160,7 @@ function extractFromTaggedTemplate(node, config = DEFAULT_EXTRACTOR_CONFIG) {
156
160
  */
157
161
  function extractObjectValues(node) {
158
162
  const results = [];
159
- for (const prop of node.properties) if (prop.type === "Property") results.push(...extractFromExpression(prop.value));
163
+ for (const prop of node.properties) if (prop.type === "Property") extractFromExpression(prop.value, results);
160
164
  return results;
161
165
  }
162
166
  /**
@@ -183,7 +187,7 @@ function extractFromClassedCall(node) {
183
187
  }
184
188
  skippedFirst = true;
185
189
  if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
186
- else results.push(...extractFromExpression(arg));
190
+ else extractFromExpression(arg, results);
187
191
  }
188
192
  return results;
189
193
  }
@@ -194,7 +198,7 @@ function extractFromClassedCall(node) {
194
198
  function extractFromCvaCall(node) {
195
199
  const results = [];
196
200
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
197
- else results.push(...extractFromExpression(arg));
201
+ else extractFromExpression(arg, results);
198
202
  return results;
199
203
  }
200
204
  /**
@@ -209,10 +213,10 @@ function extractFromCvaConfig(node) {
209
213
  const name = getPropertyName(prop.key);
210
214
  if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
211
215
  if (category.type !== "Property" || category.value.type !== "ObjectExpression") continue;
212
- for (const variant of category.value.properties) if (variant.type === "Property") results.push(...extractFromExpression(variant.value));
216
+ for (const variant of category.value.properties) if (variant.type === "Property") extractFromExpression(variant.value, results);
213
217
  }
214
218
  else if (name === "compoundVariants" && prop.value.type === "ArrayExpression") results.push(...extractClassFromCompoundEntries(prop.value));
215
- else if (name === "defaultVariants") {} else results.push(...extractFromExpression(prop.value));
219
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
216
220
  }
217
221
  return results;
218
222
  }
@@ -223,7 +227,7 @@ function extractFromCvaConfig(node) {
223
227
  function extractFromTvCall(node) {
224
228
  const results = [];
225
229
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromTvConfig(arg));
226
- else results.push(...extractFromExpression(arg));
230
+ else extractFromExpression(arg, results);
227
231
  return results;
228
232
  }
229
233
  /**
@@ -236,20 +240,20 @@ function extractFromTvConfig(node) {
236
240
  for (const prop of node.properties) {
237
241
  if (prop.type !== "Property") continue;
238
242
  const name = getPropertyName(prop.key);
239
- if (name === "base") results.push(...extractFromExpression(prop.value));
243
+ if (name === "base") extractFromExpression(prop.value, results);
240
244
  else if (name === "slots" && prop.value.type === "ObjectExpression") {
241
- for (const slot of prop.value.properties) if (slot.type === "Property") results.push(...extractFromExpression(slot.value));
245
+ for (const slot of prop.value.properties) if (slot.type === "Property") extractFromExpression(slot.value, results);
242
246
  } else if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
243
247
  if (category.type !== "Property" || category.value.type !== "ObjectExpression") continue;
244
248
  for (const variant of category.value.properties) {
245
249
  if (variant.type !== "Property") continue;
246
250
  if (variant.value.type === "ObjectExpression") {
247
- for (const slotProp of variant.value.properties) if (slotProp.type === "Property") results.push(...extractFromExpression(slotProp.value));
248
- } else results.push(...extractFromExpression(variant.value));
251
+ for (const slotProp of variant.value.properties) if (slotProp.type === "Property") extractFromExpression(slotProp.value, results);
252
+ } else extractFromExpression(variant.value, results);
249
253
  }
250
254
  }
251
255
  else if ((name === "compoundVariants" || name === "compoundSlots") && prop.value.type === "ArrayExpression") results.push(...extractClassFromCompoundEntries(prop.value));
252
- else if (name === "defaultVariants") {} else results.push(...extractFromExpression(prop.value));
256
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
253
257
  }
254
258
  return results;
255
259
  }
@@ -264,7 +268,7 @@ function extractClassFromCompoundEntries(node) {
264
268
  for (const prop of element.properties) {
265
269
  if (prop.type !== "Property") continue;
266
270
  const name = getPropertyName(prop.key);
267
- if (name === "class" || name === "className") results.push(...extractFromExpression(prop.value));
271
+ if (name === "class" || name === "className") extractFromExpression(prop.value, results);
268
272
  }
269
273
  }
270
274
  return results;
@@ -286,34 +290,51 @@ function extractFromVariableDeclarator(node, config = DEFAULT_EXTRACTOR_CONFIG)
286
290
  if (!node.init) return [];
287
291
  return extractFromExpression(node.init);
288
292
  }
289
- function extractFromExpression(node) {
290
- if (node.type === "Literal" && typeof node.value === "string") return [{
291
- value: node.value,
292
- node,
293
- range: [node.range[0] + 1, node.range[1] - 1]
294
- }];
295
- if (node.type === "TemplateLiteral") return extractFromTemplateLiteral(node);
296
- if (node.type === "ConditionalExpression") return [...extractFromExpression(node.consequent), ...extractFromExpression(node.alternate)];
297
- if (node.type === "LogicalExpression") return extractFromExpression(node.right);
293
+ /**
294
+ * Walk an expression and append every class-bearing location to `out`.
295
+ *
296
+ * Internal helpers pass their accumulator down to avoid the
297
+ * `extractFromExpression(x, results)` pattern, which allocates an
298
+ * intermediate array per recursive call. Public callers may omit `out` to
299
+ * receive a fresh array.
300
+ */
301
+ function extractFromExpression(node, out = []) {
302
+ if (node.type === "Literal" && typeof node.value === "string") {
303
+ out.push({
304
+ value: node.value,
305
+ node,
306
+ range: [node.range[0] + 1, node.range[1] - 1]
307
+ });
308
+ return out;
309
+ }
310
+ if (node.type === "TemplateLiteral") return appendFromTemplateLiteral(node, out);
311
+ if (node.type === "ConditionalExpression") {
312
+ extractFromExpression(node.consequent, out);
313
+ extractFromExpression(node.alternate, out);
314
+ return out;
315
+ }
316
+ if (node.type === "LogicalExpression") return extractFromExpression(node.right, out);
317
+ if (node.type === "ArrayExpression") {
318
+ for (const element of node.elements) if (element && element.type !== "SpreadElement") extractFromExpression(element, out);
319
+ return out;
320
+ }
298
321
  if (node.type === "ObjectExpression") {
299
- const results = [];
300
- for (const prop of node.properties) if (prop.type === "Property" && prop.key.type === "Literal" && typeof prop.key.value === "string") results.push({
322
+ for (const prop of node.properties) if (prop.type === "Property" && prop.key.type === "Literal" && typeof prop.key.value === "string") out.push({
301
323
  value: prop.key.value,
302
324
  node: prop.key,
303
325
  range: [prop.key.range[0] + 1, prop.key.range[1] - 1]
304
326
  });
305
- return results;
327
+ return out;
306
328
  }
307
- return [];
329
+ return out;
308
330
  }
309
- function extractFromTemplateLiteral(node) {
310
- const results = [];
331
+ function appendFromTemplateLiteral(node, out) {
311
332
  for (let i = 0; i < node.quasis.length; i++) {
312
333
  const quasi = node.quasis[i];
313
334
  const value = quasi.value.raw;
314
335
  if (value.trim().length > 0) {
315
336
  const start = quasi.range[0] + 1;
316
- results.push({
337
+ out.push({
317
338
  value,
318
339
  node: quasi,
319
340
  range: [start, start + value.length],
@@ -322,7 +343,10 @@ function extractFromTemplateLiteral(node) {
322
343
  });
323
344
  }
324
345
  }
325
- return results;
346
+ return out;
347
+ }
348
+ function extractFromTemplateLiteral(node) {
349
+ return appendFromTemplateLiteral(node, []);
326
350
  }
327
351
  function getCalleeName(node) {
328
352
  if (node.type === "Identifier") return node.name;
@@ -536,21 +560,6 @@ function findBestSuggestion(input, candidates, maxDistance = 3) {
536
560
  return best;
537
561
  }
538
562
  //#endregion
539
- //#region src/utils/floating-point.ts
540
- /**
541
- * Rounds rem/em/px values in class strings to avoid
542
- * JavaScript floating point issues.
543
- *
544
- * Example: "text-lg/[2.4000000000000004rem]" -> "text-lg/[2.4rem]"
545
- *
546
- * Regression test for: better-tailwindcss#320
547
- */
548
- function roundRemValue(className) {
549
- return className.replace(/\[(-?\d+\.\d{7,})(rem|em|px|%)\]/g, (_, num, unit) => {
550
- return `[${Number.parseFloat(Number.parseFloat(num).toFixed(6))}${unit}]`;
551
- });
552
- }
553
- //#endregion
554
563
  //#region src/utils/class-parser.ts
555
564
  /**
556
565
  * Extracts variants from a class string, respecting bracket depth.
@@ -657,23 +666,53 @@ function getArbitraryValue(cls) {
657
666
  }
658
667
  return null;
659
668
  }
660
- //#endregion
661
- //#region src/design-system/cache.ts
662
- /** Strip `!` modifier from start or end: `!flex` → `flex`, `flex!` → `flex` */
663
- function stripImportant$1(cls) {
664
- if (cls.startsWith("!")) return {
665
- bare: cls.slice(1),
666
- important: true
669
+ /**
670
+ * Strip the `!` important modifier from a utility's bare form (no variant
671
+ * prefix). Returns the bare string and the original position. Operate on
672
+ * the utility part — call `splitUtilityAndVariant` first if you have the
673
+ * full class. `parseClass` does both in one pass; use that when you need
674
+ * the full ParsedClass shape.
675
+ */
676
+ function splitImportant(utility) {
677
+ if (utility.startsWith("!")) return {
678
+ bare: utility.slice(1),
679
+ position: "prefix"
667
680
  };
668
- if (cls.endsWith("!")) return {
669
- bare: cls.slice(0, -1),
670
- important: true
681
+ if (utility.endsWith("!")) return {
682
+ bare: utility.slice(0, -1),
683
+ position: "suffix"
671
684
  };
672
685
  return {
673
- bare: cls,
674
- important: false
686
+ bare: utility,
687
+ position: null
675
688
  };
676
689
  }
690
+ /**
691
+ * Reattach `!` at the position recorded by `splitImportant`.
692
+ * The inverse of `splitImportant`: `reattachImportant(splitImportant(x).bare, splitImportant(x).position) === x`.
693
+ */
694
+ function reattachImportant(bare, position) {
695
+ if (position === "prefix") return `!${bare}`;
696
+ if (position === "suffix") return `${bare}!`;
697
+ return bare;
698
+ }
699
+ //#endregion
700
+ //#region src/utils/floating-point.ts
701
+ /**
702
+ * Rounds rem/em/px values in class strings to avoid
703
+ * JavaScript floating point issues.
704
+ *
705
+ * Example: "text-lg/[2.4000000000000004rem]" -> "text-lg/[2.4rem]"
706
+ *
707
+ * Regression test for: better-tailwindcss#320
708
+ */
709
+ function roundRemValue(className) {
710
+ return className.replace(/\[(-?\d+\.\d{7,})(rem|em|px|%)\]/g, (_, num, unit) => {
711
+ return `[${Number.parseFloat(Number.parseFloat(num).toFixed(6))}${unit}]`;
712
+ });
713
+ }
714
+ //#endregion
715
+ //#region src/design-system/cache.ts
677
716
  var DesignSystemCache = class DesignSystemCache {
678
717
  canonicalMap = /* @__PURE__ */ new Map();
679
718
  validitySet = /* @__PURE__ */ new Set();
@@ -714,12 +753,12 @@ var DesignSystemCache = class DesignSystemCache {
714
753
  const canonicalUtility = this.canonicalMap.get(utility);
715
754
  if (canonicalUtility !== void 0) return className.slice(0, className.length - utility.length) + canonicalUtility;
716
755
  }
717
- const { bare, important } = stripImportant$1(utility);
718
- if (important) {
756
+ const { bare, position } = splitImportant(utility);
757
+ if (position) {
719
758
  const canonicalBare = this.canonicalMap.get(bare);
720
759
  if (canonicalBare !== void 0) {
721
760
  const variantPrefix = className.slice(0, className.length - utility.length);
722
- return utility.startsWith("!") ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
761
+ return position === "prefix" ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
723
762
  }
724
763
  }
725
764
  return className;
@@ -749,6 +788,20 @@ var DesignSystemCache = class DesignSystemCache {
749
788
  if (variant.startsWith("aria-")) return (this.variantOrderMap.get("inert") ?? 48) + 2;
750
789
  return 0;
751
790
  }
791
+ _prefixOrderMap = null;
792
+ buildPrefixOrderMap() {
793
+ const index = /* @__PURE__ */ new Map();
794
+ for (const [cls, order] of this.orderMap) {
795
+ if (order === null) continue;
796
+ for (let i = cls.indexOf("-"); i >= 0; i = cls.indexOf("-", i + 1)) {
797
+ const p = cls.slice(0, i);
798
+ if (!index.has(p)) index.set(p, order);
799
+ const pd = p + "-";
800
+ if (!index.has(pd)) index.set(pd, order);
801
+ }
802
+ }
803
+ return index;
804
+ }
752
805
  /** Find the order of the first class matching a prefix (e.g. "max-w-" → order of "max-w-0") */
753
806
  findOrderByPrefix(prefix) {
754
807
  const withoutDash = prefix.endsWith("-") ? prefix.slice(0, -1) : null;
@@ -756,7 +809,8 @@ var DesignSystemCache = class DesignSystemCache {
756
809
  const order = this.orderMap.get(withoutDash);
757
810
  if (order != null) return order;
758
811
  }
759
- for (const [cls, order] of this.orderMap) if (cls.startsWith(prefix) && order != null) return order;
812
+ if (!this._prefixOrderMap) this._prefixOrderMap = this.buildPrefixOrderMap();
813
+ return this._prefixOrderMap.get(prefix);
760
814
  }
761
815
  getKnownPrefixes() {
762
816
  if (!this._knownPrefixes) {
@@ -772,7 +826,7 @@ var DesignSystemCache = class DesignSystemCache {
772
826
  if (this.validitySet.has(className)) return true;
773
827
  const utility = extractUtility(className);
774
828
  if (utility !== className && this.validitySet.has(utility)) return true;
775
- const { bare } = stripImportant$1(utility);
829
+ const { bare } = splitImportant(utility);
776
830
  if (bare !== utility && this.validitySet.has(bare)) return true;
777
831
  const slashIdx = bare.lastIndexOf("/");
778
832
  if (slashIdx > 0) {
@@ -796,8 +850,8 @@ var DesignSystemCache = class DesignSystemCache {
796
850
  const hasVariant = utility !== className;
797
851
  let baseOrder = this.orderMap.get(utility) ?? void 0;
798
852
  if (baseOrder === void 0) {
799
- const { bare, important } = stripImportant$1(utility);
800
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
853
+ const { bare, position } = splitImportant(utility);
854
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
801
855
  }
802
856
  if (baseOrder === void 0) {
803
857
  const slashIdx = utility.lastIndexOf("/");
@@ -805,13 +859,13 @@ var DesignSystemCache = class DesignSystemCache {
805
859
  const base = utility.slice(0, slashIdx);
806
860
  baseOrder = this.orderMap.get(base) ?? void 0;
807
861
  if (baseOrder === void 0) {
808
- const { bare, important } = stripImportant$1(base);
809
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
862
+ const { bare, position } = splitImportant(base);
863
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
810
864
  }
811
865
  }
812
866
  }
813
867
  if (baseOrder === void 0) {
814
- const stripped = stripImportant$1(utility).bare;
868
+ const stripped = splitImportant(utility).bare;
815
869
  const bracketIdx = stripped.indexOf("[");
816
870
  if (bracketIdx > 0) {
817
871
  const prefix = stripped.slice(0, bracketIdx);
@@ -819,7 +873,7 @@ var DesignSystemCache = class DesignSystemCache {
819
873
  }
820
874
  }
821
875
  if (baseOrder === void 0) {
822
- const stripped = stripImportant$1(utility).bare;
876
+ const stripped = splitImportant(utility).bare;
823
877
  const parenIdx = stripped.indexOf("(");
824
878
  if (parenIdx > 0) {
825
879
  const prefix = stripped.slice(0, parenIdx);
@@ -827,7 +881,7 @@ var DesignSystemCache = class DesignSystemCache {
827
881
  }
828
882
  }
829
883
  if (baseOrder === void 0) {
830
- const stripped = stripImportant$1(utility).bare;
884
+ const stripped = splitImportant(utility).bare;
831
885
  const numericMatch = /^(.+)-(\d+\.?\d*)$/.exec(stripped);
832
886
  if (numericMatch && this.getKnownPrefixes().has(numericMatch[1])) baseOrder = this.findOrderByPrefix(numericMatch[1] + "-");
833
887
  }
@@ -846,8 +900,8 @@ var DesignSystemCache = class DesignSystemCache {
846
900
  getCssProperties(className) {
847
901
  const result = this.cssPropsMap.get(className);
848
902
  if (result) return result;
849
- const { bare, important } = stripImportant$1(className);
850
- if (important) return this.cssPropsMap.get(bare) ?? [];
903
+ const { bare, position } = splitImportant(className);
904
+ if (position) return this.cssPropsMap.get(bare) ?? [];
851
905
  return [];
852
906
  }
853
907
  getVariantPriority(variant) {
@@ -859,12 +913,139 @@ var DesignSystemCache = class DesignSystemCache {
859
913
  getNamedEquivalent(className) {
860
914
  const result = this.arbitraryEquivMap.get(className);
861
915
  if (result) return result;
862
- const { bare, important } = stripImportant$1(className);
863
- if (important) return this.arbitraryEquivMap.get(bare) ?? null;
916
+ const { bare, position } = splitImportant(className);
917
+ if (position) return this.arbitraryEquivMap.get(bare) ?? null;
864
918
  return null;
865
919
  }
866
920
  };
867
921
  //#endregion
922
+ //#region src/utils/fatal.ts
923
+ /**
924
+ * Fatal error types and reporter for the deterministic v1 design.
925
+ *
926
+ * The plugin used to silently skip when the design system could not be
927
+ * loaded or the worker thread misbehaved. v1 fails loud: every DS-dependent
928
+ * rule catches these errors and surfaces them as a single fatal lint
929
+ * diagnostic so the user sees exactly what to fix.
930
+ */
931
+ /**
932
+ * The single `messageId` every DS-dependent rule uses to surface a fatal
933
+ * design-system load failure. Exported as a constant so the rule's
934
+ * `meta.messages` and `context.report()` calls in `reportFatalDsError`
935
+ * cannot drift apart silently.
936
+ */
937
+ const DS_UNAVAILABLE_MESSAGE_ID = "designSystemUnavailable";
938
+ /** Pre-shaped entry for `meta.messages`. Spread it: `messages: { ..., ...DS_UNAVAILABLE_MESSAGE }`. */
939
+ const DS_UNAVAILABLE_MESSAGE = { [DS_UNAVAILABLE_MESSAGE_ID]: "{{message}}" };
940
+ var OxlintTailwindError = class extends Error {
941
+ /** A short, actionable hint shown alongside the error message. */
942
+ hint;
943
+ constructor(message, hint, options) {
944
+ super(message, options);
945
+ this.name = this.constructor.name;
946
+ this.hint = hint;
947
+ }
948
+ };
949
+ /** No `settings.tailwindcss.entryPoint` was provided and a DS-dependent rule needs one. */
950
+ var MissingEntryPointError = class extends OxlintTailwindError {};
951
+ /** `settings.tailwindcss.entryPoint` is an array of strings — removed in v1. */
952
+ var DeprecatedEntryPointShapeError = class extends OxlintTailwindError {};
953
+ /** `__unstable__loadDesignSystem` failed (bad CSS path, malformed CSS, install issue). */
954
+ var DesignSystemLoadError = class extends OxlintTailwindError {};
955
+ /** The sort or canonicalize worker thread failed to initialize or timed out. */
956
+ var SortServiceError = class extends OxlintTailwindError {};
957
+ /** Type-guard: did this error originate from the plugin's fail-loud infrastructure? */
958
+ function isFatalError(err) {
959
+ return err instanceof OxlintTailwindError;
960
+ }
961
+ /**
962
+ * Format a fatal error into the diagnostic message a rule should report.
963
+ *
964
+ * Pulls in the optional `hint` (a one-line "here's how to fix it" follow-up)
965
+ * so the message is self-contained even when the user is reading it in an
966
+ * editor without the docs site open.
967
+ */
968
+ function formatFatalError(err) {
969
+ return err.hint ? `${err.message}\n\nHint: ${err.hint}` : err.message;
970
+ }
971
+ /**
972
+ * Helper for DS-dependent rules to convert a caught fatal error into a
973
+ * single diagnostic. Returns `true` if the error was reported (and the
974
+ * visitor should bail out), `false` otherwise — the rule layer rethrows
975
+ * non-fatal errors to surface real bugs.
976
+ */
977
+ function reportFatalDsError(context, err, node) {
978
+ if (!isFatalError(err)) return false;
979
+ context.report({
980
+ node,
981
+ messageId: DS_UNAVAILABLE_MESSAGE_ID,
982
+ data: { message: formatFatalError(err) }
983
+ });
984
+ return true;
985
+ }
986
+ /**
987
+ * Call `getDS()` and route fatal errors through `reportFatalDsError`.
988
+ *
989
+ * Returns the load result on success, or `null` after a fatal error has been
990
+ * reported (rules should `if (!ds) return` and exit the visitor). Non-fatal
991
+ * errors are re-thrown so genuine bugs aren't hidden.
992
+ */
993
+ function safeGetDS(getDS, context, node) {
994
+ try {
995
+ return getDS();
996
+ } catch (err) {
997
+ if (reportFatalDsError(context, err, node)) return null;
998
+ throw err;
999
+ }
1000
+ }
1001
+ //#endregion
1002
+ //#region src/design-system/tailwind-node.ts
1003
+ /**
1004
+ * Single source of truth for the resolved `@tailwindcss/node` entry path
1005
+ * and its installed version. Three call sites (sync-loader, sort-service,
1006
+ * canonicalize-service) used to each call `require.resolve` independently
1007
+ * — this module resolves once at load and exposes the results.
1008
+ *
1009
+ * The version is read from `dist/../package.json` (the published layout)
1010
+ * with a walk-up fallback for unconventional installs.
1011
+ */
1012
+ function resolveTailwindNodePath() {
1013
+ try {
1014
+ return __require.resolve("@tailwindcss/node");
1015
+ } catch {
1016
+ return null;
1017
+ }
1018
+ }
1019
+ function readVersionFromEntry(entryPath) {
1020
+ let dir = dirname(entryPath);
1021
+ for (let i = 0; i < 5; i++) {
1022
+ const pkgJson = join(dir, "package.json");
1023
+ if (existsSync(pkgJson)) try {
1024
+ const pkg = JSON.parse(readFileSync(pkgJson, "utf-8"));
1025
+ if (pkg.name === "@tailwindcss/node" && pkg.version) return pkg.version;
1026
+ } catch {}
1027
+ const parent = dirname(dir);
1028
+ if (parent === dir) break;
1029
+ dir = parent;
1030
+ }
1031
+ return "unknown";
1032
+ }
1033
+ const entryPath = resolveTailwindNodePath();
1034
+ /**
1035
+ * Absolute path to `@tailwindcss/node`'s main entry, or `null` if not
1036
+ * installed. Workers receive this path via workerData; the parent does
1037
+ * the resolution because module resolution from a child process's `eval`
1038
+ * context (with cwd inside a tmp dir or under pnpm strict workspaces) can
1039
+ * fail to find the bare specifier.
1040
+ */
1041
+ const TAILWIND_NODE_PATH = entryPath;
1042
+ /**
1043
+ * Installed `@tailwindcss/node` version, or `'unknown'`. Used as part of
1044
+ * the disk-cache key in sync-loader so cached precompute output is
1045
+ * invalidated when the consumer upgrades.
1046
+ */
1047
+ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPath) : "unknown";
1048
+ //#endregion
868
1049
  //#region src/design-system/sync-loader.ts
869
1050
  /**
870
1051
  * Synchronous design system loader using execFileSync.
@@ -1255,35 +1436,7 @@ const CACHE_DIR = join(tmpdir(), "oxlint-tailwindcss");
1255
1436
  function computeCacheKey(scriptContent, tailwindVersion) {
1256
1437
  return `${createHash("md5").update(scriptContent).digest("hex").slice(0, 8)}:${tailwindVersion}`;
1257
1438
  }
1258
- function readTailwindVersion() {
1259
- try {
1260
- let dir = dirname(__require.resolve("@tailwindcss/node"));
1261
- while (true) {
1262
- const candidate = join(dir, "package.json");
1263
- if (existsSync(candidate)) {
1264
- const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
1265
- if (pkg.name === "@tailwindcss/node" && pkg.version) return pkg.version;
1266
- }
1267
- const parent = dirname(dir);
1268
- if (parent === dir) break;
1269
- dir = parent;
1270
- }
1271
- } catch {}
1272
- return "unknown";
1273
- }
1274
- const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, readTailwindVersion());
1275
- /**
1276
- * Two-level disk cache for monorepo deduplication:
1277
- *
1278
- * Level 1 — mtime index (.idx): maps path+mtime → content hash (fast-path, avoids reading CSS)
1279
- * Level 2 — content cache (.json): maps content hash → precomputed data (shared across packages)
1280
- *
1281
- * In monorepos, multiple packages with identical CSS (e.g. `@import 'tailwindcss'`) at different
1282
- * paths share a single content cache entry, avoiding redundant child process spawns.
1283
- */
1284
- function getMtimeIndexPath(cssPath, mtime) {
1285
- return join(CACHE_DIR, `${createHash("md5").update(`${CACHE_KEY}:${cssPath}:${mtime}`).digest("hex")}.idx`);
1286
- }
1439
+ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1287
1440
  function computeContentHash(content) {
1288
1441
  return createHash("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1289
1442
  }
@@ -1291,42 +1444,51 @@ function getContentCachePath(contentHash) {
1291
1444
  return join(CACHE_DIR, `${contentHash}.json`);
1292
1445
  }
1293
1446
  function tryReadCache(cachePath) {
1447
+ const raw = tryReadRawCache(cachePath);
1448
+ if (raw === null) return null;
1449
+ try {
1450
+ return JSON.parse(raw);
1451
+ } catch {
1452
+ return null;
1453
+ }
1454
+ }
1455
+ function tryReadRawCache(cachePath) {
1294
1456
  try {
1295
- return JSON.parse(readFileSync(cachePath, "utf-8"));
1457
+ return readFileSync(cachePath, "utf-8");
1296
1458
  } catch {
1297
1459
  return null;
1298
1460
  }
1299
1461
  }
1300
- function writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, data) {
1462
+ function writeCacheFile(contentCachePath, data) {
1301
1463
  try {
1302
1464
  mkdirSync(CACHE_DIR, { recursive: true });
1303
1465
  writeFileSync(contentCachePath, data);
1304
- writeFileSync(mtimeIndexPath, contentHash);
1305
1466
  } catch {}
1306
1467
  }
1307
- function loadDesignSystemSync(cssPath, timeout) {
1308
- const resolvedPath = resolve(cssPath);
1468
+ const LOCK_POLL_MS = 50;
1469
+ const SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
1470
+ function syncSleep(ms) {
1471
+ Atomics.wait(SLEEP_BUFFER, 0, 0, ms);
1472
+ }
1473
+ /** Age of the lock file in ms, or Infinity if it has already vanished. */
1474
+ function lockAgeMs(lockPath) {
1309
1475
  try {
1310
- const mtime = statSync(resolvedPath).mtimeMs;
1311
- const mtimeIndexPath = getMtimeIndexPath(resolvedPath, mtime);
1312
- if (existsSync(mtimeIndexPath)) try {
1313
- const cached = tryReadCache(getContentCachePath(readFileSync(mtimeIndexPath, "utf-8").trim()));
1314
- if (cached) return cached;
1315
- } catch {}
1316
- const contentHash = computeContentHash(readFileSync(resolvedPath, "utf-8"));
1317
- const contentCachePath = getContentCachePath(contentHash);
1318
- const cached = tryReadCache(contentCachePath);
1319
- if (cached) {
1320
- try {
1321
- mkdirSync(CACHE_DIR, { recursive: true });
1322
- writeFileSync(mtimeIndexPath, contentHash);
1323
- } catch {}
1324
- return cached;
1325
- }
1326
- const tailwindNodePath = __require.resolve("@tailwindcss/node");
1327
- const stdout = execFileSync(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1476
+ return Date.now() - statSync(lockPath).mtimeMs;
1477
+ } catch {
1478
+ return Number.POSITIVE_INFINITY;
1479
+ }
1480
+ }
1481
+ function tryUnlink(path) {
1482
+ try {
1483
+ unlinkSync(path);
1484
+ } catch {}
1485
+ }
1486
+ /** Fork the precompute child once. Throws `DesignSystemLoadError` on failure. */
1487
+ function runPrecompute(resolvedPath, tailwindNodePath, timeout) {
1488
+ try {
1489
+ return execFileSync(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1328
1490
  encoding: "utf-8",
1329
- timeout: timeout ?? 3e4,
1491
+ timeout,
1330
1492
  maxBuffer: 50 * 1024 * 1024,
1331
1493
  env: {
1332
1494
  ...process.env,
@@ -1335,108 +1497,75 @@ function loadDesignSystemSync(cssPath, timeout) {
1335
1497
  },
1336
1498
  cwd: dirname(resolvedPath)
1337
1499
  });
1338
- writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, stdout);
1339
- return JSON.parse(stdout);
1340
- } catch (error) {
1341
- const msg = error instanceof Error ? error.message : String(error);
1342
- if (msg.includes("Cannot find module '@tailwindcss/node'")) console.error(`[oxlint-tailwindcss] Could not resolve '@tailwindcss/node' for "${resolvedPath}". If you are using pnpm with strict hoisting, add '@tailwindcss/node' as a direct devDependency, or upgrade oxlint-tailwindcss to >= 0.7.0 which resolves it from the plugin's own install location. DS-dependent rules will be skipped for this file.`);
1343
- else console.error(`[oxlint-tailwindcss] Failed to load design system from "${resolvedPath}":`, msg);
1344
- return null;
1500
+ } catch (cause) {
1501
+ const causeError = cause instanceof Error ? cause : void 0;
1502
+ throw new DesignSystemLoadError(`Failed to precompute design system from "${resolvedPath}": ${causeError?.message ?? String(cause)}`, "Check the CSS file for syntax errors. If this looks like a timeout, raise `settings.tailwindcss.timeout`.", { cause: causeError });
1345
1503
  }
1346
1504
  }
1347
- //#endregion
1348
- //#region src/design-system/auto-detect.ts
1349
- const IMPORT_RE = /@import\s+['"]([^'"]+)['"]/g;
1350
1505
  /**
1351
- * Resolves a CSS @import specifier to an absolute path.
1352
- * Handles relative paths and package imports (walks up to node_modules).
1506
+ * Return the raw precompute JSON for `contentHash`, forking at most one child
1507
+ * across all isolates competing for the same hash. Whoever wins the lock
1508
+ * computes and writes the cache; the rest wait for that file.
1353
1509
  */
1354
- function resolveImport(specifier, baseDir) {
1355
- if (specifier.startsWith(".")) return resolve(baseDir, specifier);
1356
- let dir = baseDir;
1357
- while (true) {
1358
- const candidate = join(dir, "node_modules", specifier);
1359
- if (existsSync(candidate)) return candidate;
1360
- const parent = dirname(dir);
1361
- if (parent === dir) break;
1362
- dir = parent;
1510
+ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath, timeout) {
1511
+ const lockPath = join(CACHE_DIR, `${contentHash}.lock`);
1512
+ const staleMs = timeout + 3e4;
1513
+ try {
1514
+ mkdirSync(CACHE_DIR, { recursive: true });
1515
+ } catch {
1516
+ return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1363
1517
  }
1364
- return null;
1365
- }
1366
- /**
1367
- * Checks if any @import in the CSS content points to a file containing a Tailwind signal.
1368
- * Only follows ONE level of imports — no recursion.
1369
- */
1370
- function hasTailwindSignalInImports(content, baseDir, signals) {
1371
- IMPORT_RE.lastIndex = 0;
1372
- let match;
1373
- while ((match = IMPORT_RE.exec(content)) !== null) {
1374
- const specifier = match[1];
1375
- if (specifier === "tailwindcss") continue;
1376
- const resolved = resolveImport(specifier, baseDir);
1377
- if (!resolved) continue;
1518
+ const start = Date.now();
1519
+ for (;;) {
1520
+ const raw = tryReadRawCache(cachePath);
1521
+ if (raw !== null) return raw;
1522
+ let lockFd;
1378
1523
  try {
1379
- const imported = readFileSync(resolved, "utf-8");
1380
- if (signals.some((signal) => imported.includes(signal))) return true;
1381
- } catch {
1382
- continue;
1524
+ lockFd = openSync(lockPath, "wx");
1525
+ } catch (cause) {
1526
+ if (cause.code === "EEXIST") {
1527
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1528
+ else syncSleep(LOCK_POLL_MS);
1529
+ continue;
1530
+ }
1531
+ return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1532
+ }
1533
+ try {
1534
+ const stdout = runPrecompute(resolvedPath, tailwindNodePath, timeout);
1535
+ writeCacheFile(cachePath, stdout);
1536
+ return stdout;
1537
+ } finally {
1538
+ closeSync(lockFd);
1539
+ tryUnlink(lockPath);
1383
1540
  }
1384
1541
  }
1385
- return false;
1386
1542
  }
1387
- const CANDIDATE_DIRS = [
1388
- "src",
1389
- ".",
1390
- "app",
1391
- "styles",
1392
- "style",
1393
- "css",
1394
- "assets",
1395
- "assets/css",
1396
- "resources/css"
1397
- ];
1398
- const CANDIDATE_NAMES = [
1399
- "app",
1400
- "globals",
1401
- "global",
1402
- "style",
1403
- "styles",
1404
- "index",
1405
- "main",
1406
- "tailwind",
1407
- "tailwindcss"
1408
- ];
1409
- const CANDIDATE_PATHS = CANDIDATE_DIRS.flatMap((dir) => CANDIDATE_NAMES.map((name) => dir === "." ? `${name}.css` : `${dir}/${name}.css`));
1410
- const TAILWIND_SIGNALS = [
1411
- "@import \"tailwindcss\"",
1412
- "@import 'tailwindcss'",
1413
- "@tailwind base",
1414
- "@import tailwindcss"
1415
- ];
1416
1543
  /**
1417
- * Searches for the Tailwind CSS entry point by walking UP from the file
1418
- * being linted. Monorepo-aware: stops at package.json boundaries.
1544
+ * Synchronously load and precompute the design system for a CSS file.
1545
+ *
1546
+ * Throws `DesignSystemLoadError` on any failure (missing file, child
1547
+ * process error, missing `@tailwindcss/node`, etc.). Callers catch via
1548
+ * `reportFatalDsError` to surface a single Program-level diagnostic.
1419
1549
  */
1420
- function autoDetectEntryPoint(filePath) {
1421
- let currentDir = filePath ? dirname(resolve(filePath)) : process.cwd();
1422
- for (let depth = 0; depth < 20; depth++) {
1423
- for (const candidate of CANDIDATE_PATHS) {
1424
- const fullPath = join(currentDir, candidate);
1425
- if (!existsSync(fullPath)) continue;
1426
- try {
1427
- const content = readFileSync(fullPath, "utf-8");
1428
- if (TAILWIND_SIGNALS.some((signal) => content.includes(signal))) return fullPath;
1429
- if (hasTailwindSignalInImports(content, dirname(fullPath), TAILWIND_SIGNALS)) return fullPath;
1430
- } catch {
1431
- continue;
1432
- }
1433
- }
1434
- if (existsSync(join(currentDir, "package.json"))) break;
1435
- const parentDir = dirname(currentDir);
1436
- if (parentDir === currentDir) break;
1437
- currentDir = parentDir;
1550
+ function loadDesignSystemSync(cssPath, timeout) {
1551
+ const resolvedPath = resolve(cssPath);
1552
+ let content;
1553
+ try {
1554
+ content = readFileSync(resolvedPath, "utf-8");
1555
+ } catch (cause) {
1556
+ throw new DesignSystemLoadError(`Could not read CSS entry point: ${resolvedPath}`, "Verify the path resolves from the oxlint working directory and the file is readable.", { cause: cause instanceof Error ? cause : void 0 });
1557
+ }
1558
+ const contentHash = computeContentHash(content);
1559
+ const contentCachePath = getContentCachePath(contentHash);
1560
+ const cached = tryReadCache(contentCachePath);
1561
+ if (cached) return cached;
1562
+ if (TAILWIND_NODE_PATH === null) throw new DesignSystemLoadError(`Could not resolve '@tailwindcss/node' while loading "${resolvedPath}".`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
1563
+ const stdout = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1564
+ try {
1565
+ return JSON.parse(stdout);
1566
+ } catch (cause) {
1567
+ throw new DesignSystemLoadError(`Precompute output for "${resolvedPath}" was not valid JSON.`, "This is likely a bug in oxlint-tailwindcss. Please open an issue with the CSS that triggered it.", { cause: cause instanceof Error ? cause : void 0 });
1438
1568
  }
1439
- return null;
1440
1569
  }
1441
1570
  //#endregion
1442
1571
  //#region src/design-system/debug.ts
@@ -1467,48 +1596,143 @@ function debugLog(message) {
1467
1596
  if (_enabled || process.env.DEBUG === "oxlint-tailwindcss") console.error(`${PREFIX} ${message}`);
1468
1597
  }
1469
1598
  //#endregion
1599
+ //#region src/utils/context.ts
1600
+ /**
1601
+ * Safely read `context.options[0]`. Returns `undefined` if the getter throws
1602
+ * (oxlint < 1.31.0) or if options aren't populated yet.
1603
+ */
1604
+ function safeOptions(context) {
1605
+ try {
1606
+ return context.options?.[0] ?? void 0;
1607
+ } catch {
1608
+ return;
1609
+ }
1610
+ }
1611
+ /**
1612
+ * Safely read `context.settings`. Same try/catch pattern as `safeOptions`
1613
+ * for the createOnce-throws case.
1614
+ */
1615
+ function safeSettings(context) {
1616
+ try {
1617
+ return context.settings ?? void 0;
1618
+ } catch {
1619
+ return;
1620
+ }
1621
+ }
1622
+ /** Safely read `context.filename`. Same try/catch pattern. */
1623
+ function safeFilename(context) {
1624
+ try {
1625
+ return context.filename ?? void 0;
1626
+ } catch {
1627
+ return;
1628
+ }
1629
+ }
1630
+ /**
1631
+ * Lazily memoize a compiled options object across visitor calls.
1632
+ *
1633
+ * Every rule with options reinvents:
1634
+ *
1635
+ * let _x: CompiledOptions | null = null
1636
+ * function getX() {
1637
+ * if (_x === null) _x = compile(safeOptions<RawOptions>(context))
1638
+ * return _x
1639
+ * }
1640
+ *
1641
+ * This wraps the pattern: pass the context and a `compile` function (which
1642
+ * receives the raw options object — possibly undefined) and get a memoized
1643
+ * thunk back. Inside `createOnce`, options aren't available yet, so the first
1644
+ * visitor call triggers compilation; every subsequent call is O(1).
1645
+ */
1646
+ function createLazyOptions(context, compile) {
1647
+ let cached = null;
1648
+ return () => {
1649
+ if (cached) return cached.value;
1650
+ cached = { value: compile(safeOptions(context)) };
1651
+ return cached.value;
1652
+ };
1653
+ }
1654
+ //#endregion
1470
1655
  //#region src/design-system/loader.ts
1471
1656
  const dsCache = /* @__PURE__ */ new Map();
1472
- const autoDetectCache = /* @__PURE__ */ new Map();
1473
- let lastLoadedPath = null;
1657
+ function isEntryPointMapping(v) {
1658
+ if (typeof v !== "object" || v === null) return false;
1659
+ const m = v;
1660
+ return (typeof m.files === "string" || Array.isArray(m.files) && m.files.every((s) => typeof s === "string")) && typeof m.use === "string";
1661
+ }
1474
1662
  /**
1475
- * Extracts `entryPoint` from `context.settings.tailwindcss`.
1476
- * Supports both `string` and `string[]` (for monorepos).
1663
+ * Read `settings.tailwindcss.entryPoint` and normalize it to the v1 shape.
1664
+ *
1665
+ * Throws `DeprecatedEntryPointShapeError` if the legacy `string[]` shape is
1666
+ * still in use (removed in v1; the user must migrate to `{ files, use }[]`).
1477
1667
  */
1478
1668
  function entryPointFromSettings(settings) {
1479
1669
  const tw = settings?.tailwindcss;
1480
- if (tw && typeof tw === "object" && "entryPoint" in tw) {
1481
- const ep = tw.entryPoint;
1482
- if (typeof ep === "string") return ep;
1483
- if (Array.isArray(ep) && ep.length > 0 && ep.every((e) => typeof e === "string")) return ep;
1670
+ if (!tw || typeof tw !== "object" || !("entryPoint" in tw)) return void 0;
1671
+ const ep = tw.entryPoint;
1672
+ if (typeof ep === "string") return ep;
1673
+ if (Array.isArray(ep)) {
1674
+ if (ep.length === 0) return void 0;
1675
+ if (ep.every((e) => typeof e === "string")) throw new DeprecatedEntryPointShapeError("`settings.tailwindcss.entryPoint: string[]` was removed in v1.0.0.", "Convert each entry into an object with explicit globs:\n entryPoint: [\n { files: \"packages/app/**\", use: \"packages/app/src/styles.css\" },\n ...\n ]\nSee https://oxlint-tailwindcss.pages.dev/migration/v0-to-v1");
1676
+ if (ep.every(isEntryPointMapping)) return ep;
1677
+ throw new MissingEntryPointError("`settings.tailwindcss.entryPoint` must be either a string or an array of `{ files, use }` objects.", "Each item needs `files` (glob or array of globs) and `use` (path to a CSS file).");
1484
1678
  }
1485
1679
  }
1486
1680
  /**
1487
- * Given an array of entry points and a file path, pick the one that shares
1488
- * the longest common directory prefix with the file. Falls back to first entry.
1681
+ * Compile a minimal glob pattern to a regular expression.
1682
+ *
1683
+ * Supported syntax: `**` (any depth), `*` (any chars except `/`), `?` (one
1684
+ * char except `/`), plus literal segments. Anchored on both ends.
1685
+ *
1686
+ * Memoized across calls because `resolveByGlobMapping` runs per lint visit;
1687
+ * recompiling the same pattern per AST node would be wasted work.
1489
1688
  */
1490
- function resolveClosestEntryPoint(entryPoints, filePath) {
1491
- if (entryPoints.length === 1 || !filePath) return entryPoints[0];
1492
- const fileDir = dirname(resolve(filePath));
1493
- let best = entryPoints[0];
1494
- let bestLen = 0;
1495
- for (const ep of entryPoints) {
1496
- const len = commonPrefixLength(fileDir, dirname(resolve(ep)));
1497
- if (len > bestLen) {
1498
- bestLen = len;
1499
- best = ep;
1500
- }
1501
- }
1502
- return best;
1503
- }
1504
- function commonPrefixLength(a, b) {
1505
- const len = Math.min(a.length, b.length);
1689
+ const globRegexCache = /* @__PURE__ */ new Map();
1690
+ function globToRegExp(glob) {
1691
+ const cached = globRegexCache.get(glob);
1692
+ if (cached) return cached;
1693
+ let re = "";
1506
1694
  let i = 0;
1507
- while (i < len && a[i] === b[i]) i++;
1508
- return i;
1695
+ while (i < glob.length) {
1696
+ const c = glob[i];
1697
+ if (c === "*" && glob[i + 1] === "*") {
1698
+ re += ".*";
1699
+ i += 2;
1700
+ if (glob[i] === "/") i++;
1701
+ } else if (c === "*") {
1702
+ re += "[^/]*";
1703
+ i++;
1704
+ } else if (c === "?") {
1705
+ re += "[^/]";
1706
+ i++;
1707
+ } else if ("+()|.\\$^{}[]".includes(c)) {
1708
+ re += "\\" + c;
1709
+ i++;
1710
+ } else {
1711
+ re += c;
1712
+ i++;
1713
+ }
1714
+ }
1715
+ const compiled = new RegExp("^" + re + "$");
1716
+ globRegexCache.set(glob, compiled);
1717
+ return compiled;
1718
+ }
1719
+ function matchesAnyGlob(filePath, globs) {
1720
+ return (typeof globs === "string" ? [globs] : globs).some((g) => globToRegExp(g).test(filePath));
1509
1721
  }
1510
1722
  /**
1511
- * Extracts `rootFontSize` from `context.settings.tailwindcss` (default: 16).
1723
+ * Resolve a file path to its entry-point CSS via a mapping array.
1724
+ * First-match-wins. Paths are matched relative to `baseDir` (typically the
1725
+ * process CWD where oxlint runs), with forward-slash normalization for
1726
+ * cross-platform consistency. Returns the absolute CSS path, or `null` if
1727
+ * no mapping matches.
1728
+ */
1729
+ function resolveByGlobMapping(mappings, filePath, baseDir) {
1730
+ const relPath = relative(baseDir, resolve(filePath)).split("\\").join("/");
1731
+ for (const m of mappings) if (matchesAnyGlob(relPath, m.files)) return resolve(baseDir, m.use);
1732
+ return null;
1733
+ }
1734
+ /**
1735
+ * Extract `rootFontSize` from `settings.tailwindcss` (default: 16).
1512
1736
  */
1513
1737
  function rootFontSizeFromSettings(settings) {
1514
1738
  const tw = settings?.tailwindcss;
@@ -1518,9 +1742,6 @@ function rootFontSizeFromSettings(settings) {
1518
1742
  }
1519
1743
  return 16;
1520
1744
  }
1521
- /**
1522
- * Extracts `timeout` from `context.settings.tailwindcss`.
1523
- */
1524
1745
  function timeoutFromSettings(settings) {
1525
1746
  const tw = settings?.tailwindcss;
1526
1747
  if (tw && typeof tw === "object" && "timeout" in tw) {
@@ -1529,183 +1750,157 @@ function timeoutFromSettings(settings) {
1529
1750
  }
1530
1751
  }
1531
1752
  /**
1532
- * Cached auto-detect: caches by directory since all files in the same directory
1533
- * resolve to the same entry point. Avoids repeated filesystem walks.
1534
- */
1535
- function cachedAutoDetect(filePath) {
1536
- if (!filePath) return autoDetectEntryPoint(filePath);
1537
- const dir = dirname(resolve(filePath));
1538
- const cached = autoDetectCache.get(dir);
1539
- if (cached !== void 0) return cached;
1540
- const result = autoDetectEntryPoint(filePath);
1541
- autoDetectCache.set(dir, result);
1542
- return result;
1543
- }
1544
- /**
1545
- * Pure resolution of which CSS entry point to use for a given context.
1546
- *
1547
- * Resolution order: rule option `entryPoint` > `settingsEntry` (string or
1548
- * closest-of-array) > `autoDetect(filePath)` > `lastPath` fallback.
1753
+ * Load the design system for a specific CSS entry point.
1549
1754
  *
1550
- * Returns `isExplicit: true` when the result came from a rule option or
1551
- * settings (not auto-detect / lastPath) — the caller uses this to decide
1552
- * whether to update the shared `lastLoadedPath` fallback. Auto-detect
1553
- * results never update the fallback (prevents cross-package contamination
1554
- * in monorepos).
1755
+ * Throws `DesignSystemLoadError` if the load fails for any reason. Callers
1756
+ * (rules via `createLazyLoader`) catch via `reportFatalDsError` and surface
1757
+ * the failure as a single Program-level diagnostic.
1555
1758
  *
1556
- * `autoDetect` is injected for testability; in production it's
1557
- * `cachedAutoDetect`. Pure: does not touch module state.
1759
+ * Cached per absolute entry-point path, keyed by mtime. In monorepos each
1760
+ * unique CSS gets its own cache entry.
1558
1761
  */
1559
- function resolveCssPath(args) {
1560
- const { entryPoint, settingsEntry, filePath, lastPath, autoDetect } = args;
1561
- const explicit = entryPoint ?? (Array.isArray(settingsEntry) ? resolveClosestEntryPoint(settingsEntry, filePath) : settingsEntry);
1562
- if (explicit) return {
1563
- path: explicit,
1564
- isExplicit: true
1565
- };
1566
- const detected = autoDetect(filePath);
1567
- if (detected) return {
1568
- path: detected,
1569
- isExplicit: false
1762
+ function getLoadedDesignSystem(cssPath, settings) {
1763
+ const resolvedPath = resolve(cssPath);
1764
+ let mtime;
1765
+ try {
1766
+ mtime = statSync(resolvedPath).mtimeMs;
1767
+ } catch (cause) {
1768
+ throw new DesignSystemLoadError(`Could not stat CSS entry point: ${resolvedPath}`, "Check that the file exists and is readable. The path is resolved relative to the oxlint working directory.", { cause: cause instanceof Error ? cause : void 0 });
1769
+ }
1770
+ const cached = dsCache.get(resolvedPath);
1771
+ if (cached && cached.mtime === mtime) return {
1772
+ cache: cached.cache,
1773
+ entryPoint: resolvedPath
1570
1774
  };
1775
+ const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1776
+ const cache = DesignSystemCache.fromPrecomputed(data);
1777
+ dsCache.set(resolvedPath, {
1778
+ cache,
1779
+ mtime
1780
+ });
1781
+ debugLog(`Loaded design system from "${resolvedPath}"`);
1571
1782
  return {
1572
- path: lastPath ?? null,
1573
- isExplicit: false
1783
+ cache,
1784
+ entryPoint: resolvedPath
1574
1785
  };
1575
1786
  }
1576
1787
  /**
1577
- * Returns the design system cache, loading synchronously on first call.
1578
- * Uses execFileSync internally to bridge the async Tailwind API.
1788
+ * Lazy DS loader for a rule. Resolves the correct design system for each
1789
+ * file being linted, using (in priority order):
1579
1790
  *
1580
- * Supports multiple design systems: each unique CSS entry point gets its own cache.
1581
- * In monorepos, files in different packages auto-detect to different entry points
1582
- * and each gets the correct DS.
1583
- *
1584
- * Resolution order: rule option `entryPoint` > `settings.tailwindcss.entryPoint` > auto-detect.
1585
- */
1586
- function getLoadedDesignSystem(entryPoint, settings, filePath) {
1587
- const { path: cssPath, isExplicit } = resolveCssPath({
1588
- entryPoint,
1589
- settingsEntry: entryPointFromSettings(settings),
1590
- filePath,
1591
- lastPath: lastLoadedPath,
1592
- autoDetect: cachedAutoDetect
1593
- });
1594
- if (!cssPath) return null;
1595
- const resolvedPath = resolve(cssPath);
1596
- try {
1597
- const mtime = statSync(resolvedPath).mtimeMs;
1598
- const cached = dsCache.get(resolvedPath);
1599
- if (cached && cached.mtime === mtime) {
1600
- if (isExplicit) lastLoadedPath = resolvedPath;
1601
- return {
1602
- cache: cached.cache,
1603
- entryPoint: resolvedPath
1604
- };
1605
- }
1606
- const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1607
- if (!data) return null;
1608
- const cache = DesignSystemCache.fromPrecomputed(data);
1609
- dsCache.set(resolvedPath, {
1610
- cache,
1611
- mtime
1612
- });
1613
- debugLog(`Loaded design system from "${resolvedPath}"`);
1614
- if (isExplicit) lastLoadedPath = resolvedPath;
1615
- return {
1616
- cache,
1617
- entryPoint: resolvedPath
1618
- };
1619
- } catch {
1620
- return null;
1621
- }
1622
- }
1623
- /**
1624
- * Creates a lazy DS loader that resolves the correct design system per file.
1791
+ * 1. Rule option `entryPoint` (a string path).
1792
+ * 2. `settings.tailwindcss.entryPoint` as a string.
1793
+ * 3. `settings.tailwindcss.entryPoint` as an `EntryPointMapping[]` —
1794
+ * first matching glob (relative to CWD) wins.
1625
1795
  *
1626
- * In `createOnce`, `context.settings` and `context.filename` throw. When visitors
1627
- * run, they become available. The loader re-resolves when the filename changes,
1628
- * supporting monorepos where different files need different design systems.
1796
+ * If none of those produce an entry point for the current file, throws
1797
+ * `MissingEntryPointError`. If the resolved CSS fails to load, throws
1798
+ * `DesignSystemLoadError`. Both extend `OxlintTailwindError` and are
1799
+ * meant to be caught by `reportFatalDsError` in the rule's `check()`.
1629
1800
  *
1630
- * When a fixed entryPoint is provided (rule option or settings), it's used for all
1631
- * files and cached after first resolution.
1801
+ * `context.settings` and `context.filename` are unavailable in `createOnce`,
1802
+ * so the actual work is deferred until the returned thunk is invoked from
1803
+ * inside a visitor.
1632
1804
  */
1633
1805
  function createLazyLoader(context) {
1634
- let lastFilePath;
1635
- let lastResult = null;
1636
- let fixedEntryResolved = false;
1637
- let fixedResult = null;
1638
1806
  let debugInitialized = false;
1807
+ let lastFilePath;
1808
+ let lastResult;
1639
1809
  return () => {
1640
- let entryPoint;
1641
- try {
1642
- entryPoint = (context.options?.[0])?.entryPoint;
1643
- } catch {}
1644
- let settings;
1645
- try {
1646
- settings = context.settings;
1647
- } catch {}
1648
- let filePath;
1649
- try {
1650
- filePath = context.filename;
1651
- } catch {}
1810
+ const filePath = safeFilename(context);
1811
+ if (filePath !== void 0 && filePath === lastFilePath && lastResult) return lastResult;
1812
+ const ruleOptionEntry = safeOptions(context)?.entryPoint;
1813
+ const settings = safeSettings(context);
1652
1814
  if (!debugInitialized && settings) {
1653
1815
  debugInitialized = true;
1654
1816
  setDebugEnabled(isDebugEnabled(settings));
1655
1817
  }
1656
- const settingsEntry = entryPointFromSettings(settings);
1657
- const fixedEntry = entryPoint ?? (typeof settingsEntry === "string" ? settingsEntry : void 0);
1658
- if (fixedEntry) {
1659
- if (fixedEntryResolved) return fixedResult;
1660
- fixedEntryResolved = true;
1661
- fixedResult = getLoadedDesignSystem(fixedEntry, settings, filePath);
1662
- if (fixedResult && filePath) debugLog(`${relative(process.cwd(), filePath)} → ${relative(process.cwd(), fixedResult.entryPoint)}`);
1663
- return fixedResult;
1664
- }
1665
- if (Array.isArray(settingsEntry)) {
1666
- const closest = resolveClosestEntryPoint(settingsEntry, filePath);
1667
- if (filePath && filePath === lastFilePath) return lastResult;
1668
- if (filePath) lastFilePath = filePath;
1669
- lastResult = getLoadedDesignSystem(closest, settings, filePath);
1670
- if (lastResult && filePath) debugLog(`${relative(process.cwd(), filePath)} → ${relative(process.cwd(), lastResult.entryPoint)}`);
1671
- return lastResult;
1672
- }
1673
- if (filePath && filePath === lastFilePath) return lastResult;
1674
- if (filePath) lastFilePath = filePath;
1675
- lastResult = getLoadedDesignSystem(void 0, settings, filePath);
1676
- if (lastResult && filePath) debugLog(`${relative(process.cwd(), filePath)} → ${relative(process.cwd(), lastResult.entryPoint)}`);
1818
+ const cssPath = resolveEntryPointForFile(ruleOptionEntry, entryPointFromSettings(settings), filePath);
1819
+ lastFilePath = filePath;
1820
+ lastResult = getLoadedDesignSystem(cssPath, settings);
1821
+ if (filePath) debugLog(`${relative(process.cwd(), filePath)} → ${relative(process.cwd(), lastResult.entryPoint)}`);
1677
1822
  return lastResult;
1678
1823
  };
1679
1824
  }
1680
- //#endregion
1681
- //#region src/types.ts
1682
1825
  /**
1683
- * Safely read context.options.
1826
+ * Pure resolution from (rule option, settings entry, file path) to a CSS
1827
+ * entry-point path. Exported for testability.
1684
1828
  *
1685
- * In oxlint, `context.options` is `null` inside `createOnce()` — options are
1686
- * only populated when visitors run. Call this lazily (inside `check()` or a
1687
- * visitor) to get the user's configured options.
1688
- *
1689
- * In oxlint <1.31.0 the getter may throw — the try/catch handles that.
1829
+ * Throws `MissingEntryPointError` if nothing resolves. The error message
1830
+ * names the file so the user knows which one tripped the configuration.
1690
1831
  */
1691
- function safeOptions(context) {
1692
- try {
1693
- return context.options?.[0] ?? void 0;
1694
- } catch {
1695
- return;
1832
+ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath) {
1833
+ if (ruleOptionEntry) return ruleOptionEntry;
1834
+ if (typeof settingsEntry === "string") return settingsEntry;
1835
+ if (Array.isArray(settingsEntry)) {
1836
+ if (!filePath) throw new MissingEntryPointError("`settings.tailwindcss.entryPoint` is a mapping array but no file path is available to match against.", "This usually means the rule ran outside the linter context. Open an issue if you see this in a real lint run.");
1837
+ const matched = resolveByGlobMapping(settingsEntry, filePath, process.cwd());
1838
+ if (matched) return matched;
1839
+ throw new MissingEntryPointError(`No \`entryPoint\` mapping matched \`${filePath}\`.`, "Add a mapping covering this file to `settings.tailwindcss.entryPoint`, or use a `\"**\"` fallback entry.");
1696
1840
  }
1841
+ throw new MissingEntryPointError(`\`settings.tailwindcss.entryPoint\` is required${filePath ? ` (linting \`${filePath}\`)` : ""}.`, "Set it to a string (single-project) or an array of `{ files, use }` mappings (monorepo).");
1697
1842
  }
1843
+ //#endregion
1844
+ //#region src/utils/report.ts
1698
1845
  /**
1699
- * Safely read context.settings.
1846
+ * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
1847
+ *
1848
+ * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
1849
+ * enforce-consistent-variable-syntax, enforce-consistent-important-position,
1850
+ * enforce-negative-arbitrary-values, no-deprecated-classes,
1851
+ * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
1852
+ * replacements via the same shape:
1700
1853
  *
1701
- * Like `safeOptions`, `context.settings` may not be accessible in `createOnce()`.
1702
- * The try/catch handles that gracefully.
1854
+ * 1. Collect `{ cls, replacement }` entries from a class string.
1855
+ * 2. Rebuild the full class string with replacements applied.
1856
+ * 3. Emit ONE diagnostic with the autofix attached.
1857
+ * 4. Emit one MORE diagnostic per remaining offender, each carrying
1858
+ * the same autofix as a `suggest`.
1859
+ *
1860
+ * oxlint's fixer is single-shot per AST node, so multiple offenders in the
1861
+ * same class string can only get one mechanical fix; the rest stay as
1862
+ * suggestions the IDE can offer interactively.
1703
1863
  */
1704
- function safeSettings(context) {
1705
- try {
1706
- return context.settings ?? void 0;
1707
- } catch {
1708
- return;
1864
+ /**
1865
+ * Emit autofix + suggestion diagnostics for a list of class replacements.
1866
+ *
1867
+ * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
1868
+ * across all diagnostics — the first one is the primary fix, the rest carry
1869
+ * the same fix as a suggestion (oxlint can only apply one autofix per node).
1870
+ */
1871
+ function reportClassReplacements(context, loc, split, classes, offending, options) {
1872
+ if (offending.length === 0) return;
1873
+ const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
1874
+ const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
1875
+ const replacementKey = options.replacementKey ?? "replacement";
1876
+ const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
1877
+ const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1878
+ const report = context.report;
1879
+ for (let i = 0; i < offending.length; i++) {
1880
+ const { cls, replacement } = offending[i];
1881
+ const primaryData = {
1882
+ className: cls,
1883
+ [replacementKey]: replacement
1884
+ };
1885
+ if (i === 0) report({
1886
+ node: loc.node,
1887
+ messageId: options.messageId,
1888
+ data: primaryData,
1889
+ fix: applyFix
1890
+ });
1891
+ else report({
1892
+ node: loc.node,
1893
+ messageId: options.messageId,
1894
+ data: primaryData,
1895
+ suggest: [{
1896
+ messageId: suggestMessageId,
1897
+ data: {
1898
+ className: cls,
1899
+ replacement
1900
+ },
1901
+ fix: applyFix
1902
+ }]
1903
+ });
1709
1904
  }
1710
1905
  }
1711
1906
  //#endregion
@@ -1738,71 +1933,30 @@ const noDeprecatedClasses = defineRule({
1738
1933
  additionalProperties: false
1739
1934
  }],
1740
1935
  hasSuggestions: true,
1936
+ defaultOptions: [{}],
1741
1937
  messages: {
1742
1938
  deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
1743
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
1939
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
1940
+ ...DS_UNAVAILABLE_MESSAGE
1744
1941
  }
1745
1942
  },
1746
1943
  createOnce(context) {
1747
1944
  const getDS = createLazyLoader(context);
1748
1945
  function check(locations) {
1749
- const dsResult = getDS();
1946
+ if (locations.length === 0) return;
1947
+ if (!safeGetDS(getDS, context, locations[0].node)) return;
1750
1948
  for (const loc of locations) {
1751
1949
  const split = splitClassesWithSeparators(loc.value);
1752
- const classes = split.classes;
1753
- const offending = [];
1754
- for (const cls of classes) {
1950
+ const offending = split.classes.flatMap((cls) => {
1755
1951
  const { utility, variant } = splitUtilityAndVariant(cls);
1756
- const hasImportantPrefix = utility.startsWith("!");
1757
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
1758
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
1952
+ const { bare: bareUtility, position } = splitImportant(utility);
1759
1953
  const replacement = DEPRECATED_MAP[bareUtility];
1760
- if (!replacement) continue;
1761
- if (dsResult) {
1762
- const canonical = dsResult.cache.canonicalize(bareUtility);
1763
- if (canonical !== bareUtility && canonical === replacement) {}
1764
- }
1765
- const fullReplacement = variant + (hasImportantPrefix ? "!" : "") + replacement + (hasImportantSuffix ? "!" : "");
1766
- offending.push({
1954
+ return replacement ? [{
1767
1955
  cls,
1768
- replacement: fullReplacement
1769
- });
1770
- }
1771
- if (offending.length === 0) continue;
1772
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
1773
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
1774
- for (let i = 0; i < offending.length; i++) {
1775
- const { cls, replacement } = offending[i];
1776
- if (i === 0) context.report({
1777
- node: loc.node,
1778
- messageId: "deprecated",
1779
- data: {
1780
- className: cls,
1781
- replacement
1782
- },
1783
- fix(fixer) {
1784
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1785
- }
1786
- });
1787
- else context.report({
1788
- node: loc.node,
1789
- messageId: "deprecated",
1790
- data: {
1791
- className: cls,
1792
- replacement
1793
- },
1794
- suggest: [{
1795
- messageId: "suggestReplace",
1796
- data: {
1797
- className: cls,
1798
- replacement
1799
- },
1800
- fix(fixer) {
1801
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1802
- }
1803
- }]
1804
- });
1805
- }
1956
+ replacement: variant + reattachImportant(replacement, position)
1957
+ }] : [];
1958
+ });
1959
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
1806
1960
  }
1807
1961
  }
1808
1962
  return createExtractorVisitors(context, check);
@@ -1837,37 +1991,27 @@ const noUnknownClasses = defineRule({
1837
1991
  messages: {
1838
1992
  unknown: "\"{{className}}\" is not a valid Tailwind class.",
1839
1993
  unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
1840
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
1994
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
1995
+ ...DS_UNAVAILABLE_MESSAGE
1841
1996
  }
1842
1997
  },
1843
1998
  createOnce(context) {
1844
1999
  const getDS = createLazyLoader(context);
1845
- let _allowlist = null;
1846
- let _ignorePrefixes = null;
1847
- function getLazyOptions() {
1848
- if (_allowlist === null) {
1849
- const opts = safeOptions(context);
1850
- _allowlist = new Set(opts?.allowlist ?? []);
1851
- _ignorePrefixes = opts?.ignorePrefixes ?? [];
1852
- }
1853
- return {
1854
- allowlist: _allowlist,
1855
- ignorePrefixes: _ignorePrefixes
1856
- };
1857
- }
2000
+ const getLazyOptions = createLazyOptions(context, (o) => ({
2001
+ allowlist: new Set(o?.allowlist ?? []),
2002
+ ignorePrefixes: o?.ignorePrefixes ?? []
2003
+ }));
1858
2004
  function shouldIgnore(className) {
1859
2005
  const { allowlist, ignorePrefixes } = getLazyOptions();
1860
2006
  if (allowlist.has(className)) return true;
1861
2007
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
1862
2008
  }
1863
2009
  function stripModifiers(className) {
1864
- let stripped = className;
1865
- if (stripped.startsWith("!")) stripped = stripped.slice(1);
1866
- if (stripped.endsWith("!")) stripped = stripped.slice(0, -1);
1867
- return stripped;
2010
+ return splitImportant(className).bare;
1868
2011
  }
1869
2012
  function check(locations) {
1870
- const ds = getDS();
2013
+ if (locations.length === 0) return;
2014
+ const ds = safeGetDS(getDS, context, locations[0].node);
1871
2015
  if (!ds) return;
1872
2016
  const { cache } = ds;
1873
2017
  for (const loc of locations) {
@@ -1911,29 +2055,73 @@ const noUnknownClasses = defineRule({
1911
2055
  }
1912
2056
  });
1913
2057
  //#endregion
1914
- //#region src/rules/no-conflicting-classes.ts
2058
+ //#region src/rules/no-conflicting-classes/spec.ts
1915
2059
  const COMPLEMENTARY_GROUPS = [
1916
- /^(from|via|to)-/,
1917
- /^(transition|duration|ease|delay)(?:-|$)/,
1918
- /^-?(translate|scale|rotate|skew)-/,
1919
- /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
1920
- /^prose(?:-|$)/
2060
+ {
2061
+ pattern: /^(from|via|to)-/,
2062
+ reason: "Gradient stops (`from-*`, `via-*`, `to-*`) share `--tw-gradient-stops`; different prefixes compose, same prefix conflicts."
2063
+ },
2064
+ {
2065
+ pattern: /^(transition|duration|ease|delay)(?:-|$)/,
2066
+ reason: "`transition-*` composes with `duration-*`, `ease-*`, `delay-*` — `transition-all` itself has no `--tw-*` vars so the heuristic misses it."
2067
+ },
2068
+ {
2069
+ pattern: /^-?(translate|scale|rotate|skew)-/,
2070
+ reason: "Transform axes (translate / scale / rotate / skew) compose into a single `transform`; the overlap is not captured in `cssProps`."
2071
+ },
2072
+ {
2073
+ pattern: /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
2074
+ reason: "Mask gradients: different families (e.g. `mask-linear-*` vs `mask-radial-*`) or roles (`from`/`via`/`to`/`at`) compose; same family+role conflicts."
2075
+ },
2076
+ {
2077
+ pattern: /^prose(?:-|$)/,
2078
+ reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
2079
+ }
1921
2080
  ];
1922
2081
  const COMPOSITION_PAIRS = [
1923
- [/^text-/, /^leading-/],
1924
- [/^text-/, /^tracking-/],
1925
- [/^border(?:-[0-9]|$)/, /^border-(?:solid|dashed|dotted|double|hidden|none)$/],
1926
- [/^divide-/, /^border(?:-[trblxyse])?-/],
1927
- [/^prose(?:-|$)/, /^max-w-/],
1928
- [/^animate-in$/, /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/],
1929
- [/^animate-out$/, /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/],
1930
- [/^mask-(?:add|subtract|intersect|exclude)$/, /^-?mask-(?:linear|radial|conic|[trblxy])-/]
2082
+ {
2083
+ a: /^text-/,
2084
+ b: /^leading-/,
2085
+ reason: "`text-*` sets line-height via its size token; `leading-*` overrides it."
2086
+ },
2087
+ {
2088
+ a: /^text-/,
2089
+ b: /^tracking-/,
2090
+ reason: "`text-*` may set letter-spacing via its size token; `tracking-*` overrides it."
2091
+ },
2092
+ {
2093
+ a: /^border(?:-[0-9]|$)/,
2094
+ b: /^border-(?:solid|dashed|dotted|double|hidden|none)$/,
2095
+ reason: "`border-*` (width) composes with `border-{solid,dashed,…}` (style)."
2096
+ },
2097
+ {
2098
+ a: /^divide-/,
2099
+ b: /^border(?:-[trblxyse])?-/,
2100
+ reason: "`divide-*` styles direct children; `border-*` styles the element itself."
2101
+ },
2102
+ {
2103
+ a: /^prose(?:-|$)/,
2104
+ b: /^max-w-/,
2105
+ reason: "`prose` sets a default max-width; `max-w-*` overrides it."
2106
+ },
2107
+ {
2108
+ a: /^animate-in$/,
2109
+ b: /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/,
2110
+ reason: "`animate-in` initializes all `--tw-enter-*` vars; `*-in` modifiers each override one. (`tailwindcss-animate` / `tw-animate-css`.)"
2111
+ },
2112
+ {
2113
+ a: /^animate-out$/,
2114
+ b: /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/,
2115
+ reason: "`animate-out` initializes all `--tw-exit-*` vars; `*-out` modifiers each override one."
2116
+ },
2117
+ {
2118
+ a: /^mask-(?:add|subtract|intersect|exclude)$/,
2119
+ b: /^-?mask-(?:linear|radial|conic|[trblxy])-/,
2120
+ reason: "`mask-{add,subtract,intersect,exclude}` are mask-composite modes that compose with mask-gradient utilities."
2121
+ }
1931
2122
  ];
1932
- function stripImportant(utility) {
1933
- if (utility.startsWith("!")) return utility.slice(1);
1934
- if (utility.endsWith("!")) return utility.slice(0, -1);
1935
- return utility;
1936
- }
2123
+ //#endregion
2124
+ //#region src/rules/no-conflicting-classes.ts
1937
2125
  /**
1938
2126
  * Two utilities compose via CSS custom properties if both define their own
1939
2127
  * --tw-* properties that don't overlap — they each contribute to a shared
@@ -1966,18 +2154,21 @@ function isNarrowingOverride(propsEarlier, propsLater) {
1966
2154
  function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
1967
2155
  if (isCompositionViaCssVars(propsA, propsB)) return true;
1968
2156
  if (isNarrowingOverride(propsA, propsB)) return true;
1969
- const ua = stripImportant(extractUtility(a));
1970
- const ub = stripImportant(extractUtility(b));
1971
- const groups = rules.complementaryGroups ?? COMPLEMENTARY_GROUPS;
1972
- for (const re of groups) {
2157
+ const ua = splitImportant(extractUtility(a)).bare;
2158
+ const ub = splitImportant(extractUtility(b)).bare;
2159
+ const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
2160
+ for (const { pattern: re } of groups) {
1973
2161
  const ma = ua.match(re);
1974
2162
  const mb = ub.match(re);
1975
2163
  if (!ma || !mb) continue;
1976
2164
  if (ma[1] === void 0) return true;
1977
2165
  if (ma[1] !== mb[1]) return true;
1978
2166
  }
1979
- const pairs = rules.compositionPairs ?? COMPOSITION_PAIRS;
1980
- for (const [reA, reB] of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
2167
+ const pairs = rules.compositionPairs !== void 0 ? rules.compositionPairs.map(([a, b]) => ({
2168
+ a,
2169
+ b
2170
+ })) : COMPOSITION_PAIRS;
2171
+ for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
1981
2172
  return false;
1982
2173
  }
1983
2174
  const noConflictingClasses = defineRule({
@@ -1989,12 +2180,17 @@ const noConflictingClasses = defineRule({
1989
2180
  properties: { entryPoint: { type: "string" } },
1990
2181
  additionalProperties: false
1991
2182
  }],
1992
- messages: { conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later)." }
2183
+ defaultOptions: [{}],
2184
+ messages: {
2185
+ conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2186
+ ...DS_UNAVAILABLE_MESSAGE
2187
+ }
1993
2188
  },
1994
2189
  createOnce(context) {
1995
2190
  const getDS = createLazyLoader(context);
1996
2191
  function check(locations) {
1997
- const ds = getDS();
2192
+ if (locations.length === 0) return;
2193
+ const ds = safeGetDS(getDS, context, locations[0].node);
1998
2194
  if (!ds) return;
1999
2195
  const { cache } = ds;
2000
2196
  for (const loc of locations) {
@@ -2011,7 +2207,7 @@ const noConflictingClasses = defineRule({
2011
2207
  if (variantClasses.length < 2) continue;
2012
2208
  const propsMap = /* @__PURE__ */ new Map();
2013
2209
  for (const cls of variantClasses) {
2014
- const props = cache.getCssProperties(stripImportant(extractUtility(cls)));
2210
+ const props = cache.getCssProperties(splitImportant(extractUtility(cls)).bare);
2015
2211
  propsMap.set(cls, props);
2016
2212
  }
2017
2213
  for (let i = 0; i < variantClasses.length; i++) {
@@ -2044,42 +2240,168 @@ const noConflictingClasses = defineRule({
2044
2240
  }
2045
2241
  });
2046
2242
  //#endregion
2047
- //#region src/design-system/canonicalize-service.ts
2243
+ //#region src/design-system/ds-worker.ts
2048
2244
  /**
2049
- * Persistent canonicalize service using worker_threads + SharedArrayBuffer.
2245
+ * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
2050
2246
  *
2051
- * Calls `ds.canonicalizeCandidates([cls], { rem })` dynamically via a worker
2052
- * thread. Same pattern as sort-service.ts — loads the DS once, then accepts
2053
- * requests synchronously via Atomics.wait().
2247
+ * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
2248
+ * (~500 LOC) — both spawned a worker that loaded the design system, then served
2249
+ * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
2250
+ * real difference was the body of the request loop: `getClassOrder` vs
2251
+ * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
2252
+ * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
2253
+ * service shrinks to ~40 LOC of singleton + public signature.
2054
2254
  *
2055
- * This enables canonicalization of arbitrary user classes (e.g. `p-[2px]` → `p-0.5`)
2056
- * which can't be precomputed because the input space is infinite.
2057
- *
2058
- * ## Per-class cache (process-wide)
2255
+ * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
2256
+ * of the process (per cssPath) so subsequent calls don't pay another
2257
+ * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
2258
+ * single `designSystemUnavailable` diagnostic.
2259
+ */
2260
+ const BUFFER_SIZE = 4 * 1024 * 1024;
2261
+ const HEADER_INTS = 4;
2262
+ const DATA_OFFSET = 20;
2263
+ const INIT_TIMEOUT = 6e4;
2264
+ const REQUEST_TIMEOUT = 3e4;
2265
+ var DesignSystemWorker = class {
2266
+ opts;
2267
+ ready = null;
2268
+ lastError = null;
2269
+ constructor(opts) {
2270
+ this.opts = opts;
2271
+ }
2272
+ /**
2273
+ * Ensure the worker is running and pointed at `cssPath`. Returns the
2274
+ * ready state. Throws `SortServiceError` on any failure (init timeout,
2275
+ * spawn error, DS-load error). Sticky: subsequent calls for the same
2276
+ * cssPath rethrow without retrying.
2277
+ */
2278
+ ensure(cssPath) {
2279
+ if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2280
+ if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2281
+ if (this.ready) this.cleanup();
2282
+ this.lastError = null;
2283
+ if (TAILWIND_NODE_PATH === null) {
2284
+ this.lastError = new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
2285
+ throw this.lastError;
2286
+ }
2287
+ const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2288
+ const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2289
+ const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2290
+ const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2291
+ let worker;
2292
+ try {
2293
+ worker = new Worker(this.opts.workerScript, {
2294
+ eval: true,
2295
+ workerData: {
2296
+ sharedBuffer,
2297
+ cssPath,
2298
+ tailwindNodePath: TAILWIND_NODE_PATH
2299
+ }
2300
+ });
2301
+ } catch (cause) {
2302
+ this.lastError = new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 });
2303
+ throw this.lastError;
2304
+ }
2305
+ worker.unref();
2306
+ worker.on("error", (err) => {
2307
+ 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 });
2308
+ });
2309
+ if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2310
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow, or verify the CSS imports resolve.");
2311
+ this.terminateWorker(worker);
2312
+ throw this.lastError;
2313
+ }
2314
+ if (controlArray[2] === -1) {
2315
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid.");
2316
+ this.terminateWorker(worker);
2317
+ throw this.lastError;
2318
+ }
2319
+ this.ready = {
2320
+ worker,
2321
+ controlArray,
2322
+ lengthView,
2323
+ dataArea,
2324
+ cssPath
2325
+ };
2326
+ return this.ready;
2327
+ }
2328
+ /**
2329
+ * Send a request to the worker and synchronously wait for the response.
2330
+ * Throws `SortServiceError` on any failure.
2331
+ */
2332
+ callSync(cssPath, req) {
2333
+ const state = this.ensure(cssPath);
2334
+ const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
2335
+ if (requestBytes.length > BUFFER_SIZE - DATA_OFFSET) throw new SortServiceError(`${this.opts.serviceName} request payload is too large (${requestBytes.length} > ${BUFFER_SIZE - DATA_OFFSET} bytes).`, "This is unexpected with typical class lists; please open an issue.");
2336
+ state.dataArea.set(requestBytes, 0);
2337
+ state.lengthView.setUint32(0, requestBytes.length);
2338
+ Atomics.store(state.controlArray, 0, 1);
2339
+ Atomics.notify(state.controlArray, 0);
2340
+ if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2341
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow.");
2342
+ this.cleanup();
2343
+ throw this.lastError;
2344
+ }
2345
+ const responseLen = state.lengthView.getUint32(0);
2346
+ const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
2347
+ Atomics.store(state.controlArray, 1, 0);
2348
+ let parsed;
2349
+ try {
2350
+ parsed = JSON.parse(responseStr);
2351
+ } catch (cause) {
2352
+ this.lastError = 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 });
2353
+ this.cleanup();
2354
+ throw this.lastError;
2355
+ }
2356
+ if (parsed === null) {
2357
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker returned null — request body was rejected.`, "This is a bug; please open an issue with the input that triggered it.");
2358
+ this.cleanup();
2359
+ throw this.lastError;
2360
+ }
2361
+ return parsed;
2362
+ }
2363
+ reset() {
2364
+ this.cleanup();
2365
+ this.lastError = null;
2366
+ }
2367
+ cleanup() {
2368
+ if (this.ready) {
2369
+ this.terminateWorker(this.ready.worker);
2370
+ this.ready = null;
2371
+ }
2372
+ }
2373
+ terminateWorker(worker) {
2374
+ try {
2375
+ worker.terminate();
2376
+ } catch {}
2377
+ }
2378
+ };
2379
+ //#endregion
2380
+ //#region src/design-system/canonicalize-service.ts
2381
+ /**
2382
+ * Persistent canonicalize service backed by `DesignSystemWorker`.
2059
2383
  *
2060
- * Results are cached by `cssPath\0rem\0class`. The worker is invoked only for
2061
- * cache misses. In practice the cache converges quickly — after the first few
2062
- * files any given class has been seen, and every subsequent lookup is O(1).
2384
+ * Calls `ds.canonicalizeCandidates([cls], { rem })` one class at a time
2385
+ * (the design system deduplicates its input, so batching changes the
2386
+ * result shape — see sync-loader.ts). The shared protocol lives in
2387
+ * `./ds-worker.ts`.
2063
2388
  *
2064
- * ## Per-class worker calls
2389
+ * ## Per-class cache (process-wide)
2065
2390
  *
2066
- * `ds.canonicalizeCandidates` deduplicates its input (see sync-loader.ts note),
2067
- * so the worker MUST call it one class at a time to preserve input order/length.
2068
- * The cache amortizes the per-call overhead.
2391
+ * Results are cached by `${cssPath}\0${rem}\0${class}`. The worker is
2392
+ * invoked only for cache misses. In practice the cache converges quickly —
2393
+ * after the first few files any given class has been seen, and every
2394
+ * subsequent lookup is O(1).
2069
2395
  */
2070
- const BUFFER_SIZE$1 = 4 * 1024 * 1024;
2071
- const HEADER_INTS$1 = 4;
2072
- const DATA_OFFSET$1 = HEADER_INTS$1 * 4 + 4;
2073
- const INIT_TIMEOUT$1 = 3e4;
2074
- const REQUEST_TIMEOUT$1 = 1e4;
2075
- const WORKER_SCRIPT$1 = `
2396
+ const canonWorker = new DesignSystemWorker({
2397
+ workerScript: `
2076
2398
  const { workerData } = require('worker_threads');
2077
2399
 
2078
2400
  async function main() {
2079
2401
  const { sharedBuffer, cssPath } = workerData;
2080
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS$1});
2081
- const lengthView = new DataView(sharedBuffer, ${HEADER_INTS$1 * 4}, 4);
2082
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET$1});
2402
+ const control = new Int32Array(sharedBuffer, 0, 4);
2403
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2404
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2083
2405
 
2084
2406
  let ds;
2085
2407
  try {
@@ -2094,14 +2416,11 @@ async function main() {
2094
2416
  return;
2095
2417
  }
2096
2418
 
2097
- // Signal ready
2098
2419
  Atomics.store(control, 2, 1);
2099
2420
  Atomics.notify(control, 2);
2100
2421
 
2101
- // Request loop
2102
2422
  while (true) {
2103
2423
  Atomics.wait(control, 0, 0);
2104
-
2105
2424
  const len = lengthView.getUint32(0);
2106
2425
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2107
2426
  Atomics.store(control, 0, 0);
@@ -2123,117 +2442,32 @@ async function main() {
2123
2442
 
2124
2443
  dataArea.set(response, 0);
2125
2444
  lengthView.setUint32(0, response.length);
2126
-
2127
2445
  Atomics.store(control, 1, 1);
2128
2446
  Atomics.notify(control, 1);
2129
2447
  }
2130
2448
  }
2131
2449
  main();
2132
- `;
2133
- let worker$1 = null;
2134
- let controlArray$1 = null;
2135
- let lengthView$1 = null;
2136
- let dataArea$1 = null;
2137
- let initialized$1 = false;
2138
- let available$1 = true;
2139
- let currentCssPath$1 = null;
2140
- const canonCache = /* @__PURE__ */ new Map();
2141
- function ensureService$1(cssPath) {
2142
- if (initialized$1 && currentCssPath$1 === cssPath) return available$1;
2143
- if (initialized$1) {
2144
- cleanup$1();
2145
- initialized$1 = false;
2146
- available$1 = true;
2147
- controlArray$1 = null;
2148
- lengthView$1 = null;
2149
- dataArea$1 = null;
2150
- }
2151
- initialized$1 = true;
2152
- currentCssPath$1 = cssPath;
2153
- try {
2154
- const tailwindNodePath = __require.resolve("@tailwindcss/node");
2155
- const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE$1);
2156
- controlArray$1 = new Int32Array(sharedBuffer, 0, HEADER_INTS$1);
2157
- lengthView$1 = new DataView(sharedBuffer, HEADER_INTS$1 * 4, 4);
2158
- dataArea$1 = new Uint8Array(sharedBuffer, DATA_OFFSET$1);
2159
- worker$1 = new Worker(WORKER_SCRIPT$1, {
2160
- eval: true,
2161
- workerData: {
2162
- sharedBuffer,
2163
- cssPath,
2164
- tailwindNodePath
2165
- }
2166
- });
2167
- worker$1.unref();
2168
- worker$1.on("error", () => {
2169
- available$1 = false;
2170
- worker$1 = null;
2171
- });
2172
- worker$1.on("exit", () => {
2173
- worker$1 = null;
2174
- });
2175
- if (Atomics.wait(controlArray$1, 2, 0, INIT_TIMEOUT$1) === "timed-out" || controlArray$1[2] === -1) {
2176
- available$1 = false;
2177
- cleanup$1();
2178
- return false;
2179
- }
2180
- return true;
2181
- } catch {
2182
- available$1 = false;
2183
- cleanup$1();
2184
- return false;
2185
- }
2186
- }
2187
- function cleanup$1() {
2188
- if (worker$1) {
2189
- try {
2190
- worker$1.terminate();
2191
- } catch {}
2192
- worker$1 = null;
2193
- }
2194
- }
2450
+ `,
2451
+ serviceName: "canonicalize"
2452
+ });
2195
2453
  /**
2196
- * Round-trip raw worker call for a batch of classes (no caching).
2197
- * Returns the canonicalized class array (same length/order as input),
2198
- * or null if the service is unavailable.
2454
+ * Process-wide cache of canonicalized classes.
2455
+ * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
2456
+ * DSs) and different rem settings. Value: canonicalized class string.
2199
2457
  */
2200
- function callWorker(classes, rem) {
2201
- if (!controlArray$1 || !dataArea$1 || !lengthView$1) return null;
2202
- try {
2203
- const request = Buffer.from(JSON.stringify({
2204
- classes,
2205
- rem
2206
- }), "utf-8");
2207
- if (request.length > BUFFER_SIZE$1 - DATA_OFFSET$1) return null;
2208
- dataArea$1.set(request, 0);
2209
- lengthView$1.setUint32(0, request.length);
2210
- Atomics.store(controlArray$1, 0, 1);
2211
- Atomics.notify(controlArray$1, 0);
2212
- if (Atomics.wait(controlArray$1, 1, 0, REQUEST_TIMEOUT$1) === "timed-out") {
2213
- available$1 = false;
2214
- cleanup$1();
2215
- return null;
2216
- }
2217
- const responseLen = lengthView$1.getUint32(0);
2218
- const responseStr = Buffer.from(dataArea$1.slice(0, responseLen)).toString("utf-8");
2219
- Atomics.store(controlArray$1, 1, 0);
2220
- return JSON.parse(responseStr);
2221
- } catch {
2222
- available$1 = false;
2223
- cleanup$1();
2224
- return null;
2225
- }
2226
- }
2458
+ const canonCache = /* @__PURE__ */ new Map();
2227
2459
  /**
2228
- * Canonicalize classes using the Tailwind CSS design system via worker thread.
2229
- * Returns the canonicalized class array (same length/order as input), or null
2230
- * if the service is unavailable.
2460
+ * Canonicalize classes via the worker thread.
2231
2461
  *
2232
- * Uses a process-wide per-class cache: the worker is invoked only for classes
2462
+ * Throws `SortServiceError` on any worker failure (init timeout, request
2463
+ * timeout, worker crash). Callers should wrap via `safeGetDS` so the
2464
+ * failure surfaces as a single `designSystemUnavailable` diagnostic.
2465
+ *
2466
+ * Returns an array the same length and order as `classes`. Uses a
2467
+ * process-wide per-class cache: the worker is invoked only for classes
2233
2468
  * not already seen with this (cssPath, rem) combination.
2234
2469
  */
2235
2470
  function canonicalizeClassesSync(cssPath, classes, rem) {
2236
- if (!ensureService$1(cssPath)) return null;
2237
2471
  const out = Array.from({ length: classes.length });
2238
2472
  const missingIdx = [];
2239
2473
  const missing = [];
@@ -2249,8 +2483,11 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2249
2483
  }
2250
2484
  if (missing.length === 0) return out;
2251
2485
  const uniqueMissing = [...new Set(missing)];
2252
- const fresh = callWorker(uniqueMissing, rem);
2253
- if (!fresh || fresh.length !== uniqueMissing.length) return null;
2486
+ const fresh = canonWorker.callSync(cssPath, {
2487
+ classes: uniqueMissing,
2488
+ rem
2489
+ });
2490
+ if (fresh.length !== uniqueMissing.length) throw new SortServiceError(`Canonicalize worker returned ${fresh.length} results for ${uniqueMissing.length} inputs.`, "This is a bug; please open an issue.");
2254
2491
  const freshByClass = /* @__PURE__ */ new Map();
2255
2492
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2256
2493
  for (let j = 0; j < missing.length; j++) {
@@ -2264,20 +2501,20 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2264
2501
  //#endregion
2265
2502
  //#region src/rules/enforce-canonical.ts
2266
2503
  /**
2267
- * Preserve the user's ! position after canonicalization.
2268
- * canonicalizeCandidates always normalizes ! to suffix, but
2269
- * enforce-consistent-important-position handles that separately.
2504
+ * Preserve the user's `!` position after canonicalization.
2505
+ *
2506
+ * `canonicalizeCandidates` normalizes `!` to suffix; this restores the
2507
+ * original prefix-or-suffix-or-none position so `enforce-consistent-important-position`
2508
+ * remains the single source of truth for ! placement policy.
2509
+ *
2510
+ * Bracket-aware via `splitUtilityAndVariant` — arbitrary variants like
2511
+ * `[&>svg]:!w-4` round-trip correctly.
2270
2512
  */
2271
2513
  function preserveImportantPosition(original, canonicalized) {
2272
- const origHasPrefix = original.startsWith("!") || /^[a-z0-9[\]*@-]*:!/.test(original);
2273
- const origHasSuffix = original.endsWith("!") && !origHasPrefix;
2274
- if (!origHasPrefix && !origHasSuffix) return canonicalized.replace(/!/g, "");
2275
- const bare = canonicalized.replace(/!/g, "");
2276
- if (origHasPrefix) {
2277
- const variantPrefix = bare.slice(0, bare.length - bare.replace(/^[a-z0-9[\]*@-]*:/g, "").length);
2278
- return variantPrefix + "!" + bare.slice(variantPrefix.length);
2279
- }
2280
- return bare + "!";
2514
+ const { position } = splitImportant(splitUtilityAndVariant(original).utility);
2515
+ const { utility, variant } = splitUtilityAndVariant(canonicalized);
2516
+ const bare = splitImportant(utility).bare;
2517
+ return variant + reattachImportant(bare, position);
2281
2518
  }
2282
2519
  const enforceCanonical = defineRule({
2283
2520
  meta: {
@@ -2290,9 +2527,11 @@ const enforceCanonical = defineRule({
2290
2527
  additionalProperties: false
2291
2528
  }],
2292
2529
  hasSuggestions: true,
2530
+ defaultOptions: [{}],
2293
2531
  messages: {
2294
2532
  nonCanonical: "\"{{className}}\" can be written as \"{{canonical}}\". Use the canonical form.",
2295
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2533
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2534
+ ...DS_UNAVAILABLE_MESSAGE
2296
2535
  }
2297
2536
  },
2298
2537
  createOnce(context) {
@@ -2303,7 +2542,8 @@ const enforceCanonical = defineRule({
2303
2542
  return _rem;
2304
2543
  }
2305
2544
  function check(locations) {
2306
- const ds = getDS();
2545
+ if (locations.length === 0) return;
2546
+ const ds = safeGetDS(getDS, context, locations[0].node);
2307
2547
  if (!ds) return;
2308
2548
  const { cache, entryPoint } = ds;
2309
2549
  for (const loc of locations) {
@@ -2317,51 +2557,18 @@ const enforceCanonical = defineRule({
2317
2557
  arbitrary.push(classes[i]);
2318
2558
  } else canonicals[i] = cache.canonicalize(classes[i]);
2319
2559
  if (arbitrary.length > 0) {
2320
- const dynamic = canonicalizeClassesSync(entryPoint, arbitrary, getRem());
2321
- if (dynamic) for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
2322
- else for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = cache.canonicalize(arbitrary[k]);
2323
- }
2324
- let firstNonCanonical = true;
2325
- for (let i = 0; i < classes.length; i++) {
2326
- const cls = classes[i];
2327
- const canonical = canonicals[i];
2328
- if (canonical === cls) continue;
2329
- if (firstNonCanonical) {
2330
- firstNonCanonical = false;
2331
- const fixedValue = rebuildClassString(split, canonicals);
2332
- context.report({
2333
- node: loc.node,
2334
- messageId: "nonCanonical",
2335
- data: {
2336
- className: cls,
2337
- canonical
2338
- },
2339
- fix(fixer) {
2340
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2341
- }
2342
- });
2343
- } else {
2344
- const fixedValue = rebuildClassString(split, canonicals);
2345
- context.report({
2346
- node: loc.node,
2347
- messageId: "nonCanonical",
2348
- data: {
2349
- className: cls,
2350
- canonical
2351
- },
2352
- suggest: [{
2353
- messageId: "suggestReplace",
2354
- data: {
2355
- className: cls,
2356
- replacement: canonical
2357
- },
2358
- fix(fixer) {
2359
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2360
- }
2361
- }]
2362
- });
2363
- }
2560
+ const rem = getRem();
2561
+ const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
2562
+ if (!dynamic) return;
2563
+ for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
2364
2564
  }
2565
+ reportClassReplacements(context, loc, split, classes, classes.flatMap((cls, i) => canonicals[i] === cls ? [] : [{
2566
+ cls,
2567
+ replacement: canonicals[i]
2568
+ }]), {
2569
+ messageId: "nonCanonical",
2570
+ replacementKey: "canonical"
2571
+ });
2365
2572
  }
2366
2573
  }
2367
2574
  return createExtractorVisitors(context, check);
@@ -2370,31 +2577,21 @@ const enforceCanonical = defineRule({
2370
2577
  //#endregion
2371
2578
  //#region src/design-system/sort-service.ts
2372
2579
  /**
2373
- * Persistent sort service using worker_threads + SharedArrayBuffer.
2580
+ * Persistent sort service backed by `DesignSystemWorker`.
2374
2581
  *
2375
- * The problem: `ds.getClassOrder()` is the only way to get the exact official
2376
- * Tailwind CSS sort order (matching oxfmt/prettier-plugin-tailwindcss), but the
2377
- * design system is async to load and the oxlint plugin API is sync.
2378
- *
2379
- * The solution: spawn a Worker thread that loads the DS once, then accepts sort
2380
- * requests via SharedArrayBuffer + Atomics. The parent uses `Atomics.wait()`
2381
- * (with timeout) for synchronous blocking without risk of infinite hangs.
2382
- *
2383
- * Falls back gracefully if the worker fails to initialize within the timeout.
2582
+ * Calls `ds.getClassOrder(classes)` and returns the class names in the
2583
+ * Tailwind-canonical order. The shared protocol (SharedArrayBuffer,
2584
+ * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2384
2585
  */
2385
- const BUFFER_SIZE = 4 * 1024 * 1024;
2386
- const HEADER_INTS = 4;
2387
- const DATA_OFFSET = HEADER_INTS * 4 + 4;
2388
- const INIT_TIMEOUT = 3e4;
2389
- const REQUEST_TIMEOUT = 1e4;
2390
- const WORKER_SCRIPT = `
2586
+ const sortWorker = new DesignSystemWorker({
2587
+ workerScript: `
2391
2588
  const { workerData } = require('worker_threads');
2392
2589
 
2393
2590
  async function main() {
2394
2591
  const { sharedBuffer, cssPath } = workerData;
2395
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2396
- const lengthView = new DataView(sharedBuffer, ${HEADER_INTS * 4}, 4);
2397
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2592
+ const control = new Int32Array(sharedBuffer, 0, 4);
2593
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2594
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2398
2595
 
2399
2596
  let ds;
2400
2597
  try {
@@ -2409,17 +2606,14 @@ async function main() {
2409
2606
  return;
2410
2607
  }
2411
2608
 
2412
- // Signal ready
2413
2609
  Atomics.store(control, 2, 1);
2414
2610
  Atomics.notify(control, 2);
2415
2611
 
2416
- // Request loop
2417
2612
  while (true) {
2418
- Atomics.wait(control, 0, 0); // wait for requestSignal !== 0
2419
-
2613
+ Atomics.wait(control, 0, 0);
2420
2614
  const len = lengthView.getUint32(0);
2421
2615
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2422
- Atomics.store(control, 0, 0); // consume request
2616
+ Atomics.store(control, 0, 0);
2423
2617
 
2424
2618
  let response;
2425
2619
  try {
@@ -2440,102 +2634,24 @@ async function main() {
2440
2634
 
2441
2635
  dataArea.set(response, 0);
2442
2636
  lengthView.setUint32(0, response.length);
2443
-
2444
- Atomics.store(control, 1, 1); // signal response
2637
+ Atomics.store(control, 1, 1);
2445
2638
  Atomics.notify(control, 1);
2446
2639
  }
2447
2640
  }
2448
2641
  main();
2449
- `;
2450
- let worker = null;
2451
- let controlArray = null;
2452
- let lengthView = null;
2453
- let dataArea = null;
2454
- let initialized = false;
2455
- let available = true;
2456
- let currentCssPath = null;
2457
- function ensureService(cssPath) {
2458
- if (initialized && currentCssPath === cssPath) return available;
2459
- if (initialized) {
2460
- cleanup();
2461
- initialized = false;
2462
- available = true;
2463
- controlArray = null;
2464
- lengthView = null;
2465
- dataArea = null;
2466
- }
2467
- initialized = true;
2468
- currentCssPath = cssPath;
2469
- try {
2470
- const tailwindNodePath = __require.resolve("@tailwindcss/node");
2471
- const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2472
- controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2473
- lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2474
- dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2475
- worker = new Worker(WORKER_SCRIPT, {
2476
- eval: true,
2477
- workerData: {
2478
- sharedBuffer,
2479
- cssPath,
2480
- tailwindNodePath
2481
- }
2482
- });
2483
- worker.unref();
2484
- worker.on("error", () => {
2485
- available = false;
2486
- worker = null;
2487
- });
2488
- worker.on("exit", () => {
2489
- worker = null;
2490
- });
2491
- if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out" || controlArray[2] === -1) {
2492
- available = false;
2493
- cleanup();
2494
- return false;
2495
- }
2496
- return true;
2497
- } catch {
2498
- available = false;
2499
- cleanup();
2500
- return false;
2501
- }
2502
- }
2503
- function cleanup() {
2504
- if (worker) {
2505
- try {
2506
- worker.terminate();
2507
- } catch {}
2508
- worker = null;
2509
- }
2510
- }
2642
+ `,
2643
+ serviceName: "sort"
2644
+ });
2511
2645
  /**
2512
- * Sort classes using the official Tailwind CSS sort order via worker thread.
2513
- * Returns the sorted class array, or null if the service is unavailable.
2646
+ * Sort classes via worker thread using the official Tailwind class order.
2647
+ *
2648
+ * Throws `SortServiceError` on any failure (worker init timeout, request
2649
+ * timeout, worker crash, payload too large). Callers should wrap via
2650
+ * `safeGetDS` so the failure surfaces as a single `designSystemUnavailable`
2651
+ * diagnostic instead of crashing the lint.
2514
2652
  */
2515
2653
  function sortClassesSync(cssPath, classes) {
2516
- if (!ensureService(cssPath)) return null;
2517
- if (!controlArray || !dataArea || !lengthView) return null;
2518
- try {
2519
- const request = Buffer.from(JSON.stringify(classes), "utf-8");
2520
- if (request.length > BUFFER_SIZE - DATA_OFFSET) return null;
2521
- dataArea.set(request, 0);
2522
- lengthView.setUint32(0, request.length);
2523
- Atomics.store(controlArray, 0, 1);
2524
- Atomics.notify(controlArray, 0);
2525
- if (Atomics.wait(controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2526
- available = false;
2527
- cleanup();
2528
- return null;
2529
- }
2530
- const responseLen = lengthView.getUint32(0);
2531
- const responseStr = Buffer.from(dataArea.slice(0, responseLen)).toString("utf-8");
2532
- Atomics.store(controlArray, 1, 0);
2533
- return JSON.parse(responseStr);
2534
- } catch {
2535
- available = false;
2536
- cleanup();
2537
- return null;
2538
- }
2654
+ return sortWorker.callSync(cssPath, classes);
2539
2655
  }
2540
2656
  //#endregion
2541
2657
  //#region src/rules/enforce-sort-order.ts
@@ -2555,31 +2671,23 @@ const enforceSortOrder = defineRule({
2555
2671
  },
2556
2672
  additionalProperties: false
2557
2673
  }],
2558
- messages: { unsorted: "Tailwind classes are not in the recommended order." }
2674
+ defaultOptions: [{ mode: "default" }],
2675
+ messages: {
2676
+ unsorted: "Tailwind classes are not in the recommended order.",
2677
+ ...DS_UNAVAILABLE_MESSAGE
2678
+ }
2559
2679
  },
2560
2680
  createOnce(context) {
2561
2681
  const getDS = createLazyLoader(context);
2562
- let _mode = null;
2563
- function getMode() {
2564
- if (_mode === null) _mode = safeOptions(context)?.mode ?? "default";
2565
- return _mode;
2566
- }
2682
+ const getMode = createLazyOptions(context, (o) => o?.mode ?? "default");
2567
2683
  function check(locations) {
2568
- const ds = getDS();
2684
+ if (locations.length === 0) return;
2685
+ const ds = safeGetDS(getDS, context, locations[0].node);
2569
2686
  if (!ds) return;
2570
2687
  const { cache, entryPoint } = ds;
2571
2688
  const mode = getMode();
2572
2689
  function sortDefault(classes) {
2573
- const dynamic = sortClassesSync(entryPoint, classes);
2574
- if (dynamic) return dynamic;
2575
- return [...cache.getClassOrder(classes)].sort((a, b) => {
2576
- if (a[1] === null && b[1] === null) return 0;
2577
- if (a[1] === null) return -1;
2578
- if (b[1] === null) return 1;
2579
- if (a[1] < b[1]) return -1;
2580
- if (a[1] > b[1]) return 1;
2581
- return 0;
2582
- }).map(([name]) => name);
2690
+ return sortClassesSync(entryPoint, classes);
2583
2691
  }
2584
2692
  function sortStrict(classes) {
2585
2693
  const groups = /* @__PURE__ */ new Map();
@@ -2623,7 +2731,8 @@ const enforceSortOrder = defineRule({
2623
2731
  const split = splitClassesWithSeparators(loc.value);
2624
2732
  const classes = split.classes;
2625
2733
  if (classes.length < 2) continue;
2626
- const sortedNames = mode === "strict" ? sortStrict(classes) : sortDefault(classes);
2734
+ const sortedNames = mode === "strict" ? sortStrict(classes) : safeGetDS(() => sortDefault(classes), context, loc.node);
2735
+ if (!sortedNames) return;
2627
2736
  if (classes.every((name, i) => name === sortedNames[i])) continue;
2628
2737
  context.report({
2629
2738
  node: loc.node,
@@ -2721,8 +2830,7 @@ const enforceShorthand = defineRule({
2721
2830
  const classSet = new Set(classes);
2722
2831
  const values = /* @__PURE__ */ new Set();
2723
2832
  for (const cls of classes) {
2724
- const bare = cls.startsWith("!") ? cls.slice(1) : cls.endsWith("!") ? cls.slice(0, -1) : cls;
2725
- const match = VALUE_RE.exec(bare);
2833
+ const match = VALUE_RE.exec(splitImportant(cls).bare);
2726
2834
  if (match) values.add(match[1]);
2727
2835
  }
2728
2836
  for (const value of values) {
@@ -2756,180 +2864,234 @@ const enforceShorthand = defineRule({
2756
2864
  }
2757
2865
  });
2758
2866
  //#endregion
2867
+ //#region src/utils/allowlist.ts
2868
+ /**
2869
+ * Shared regex-allowlist helpers used by rules that accept an `allowlist`
2870
+ * option of regex source strings (currently enforce-logical / enforce-physical).
2871
+ *
2872
+ * Invalid regex sources are skipped rather than thrown so a typo in one
2873
+ * pattern doesn't blow up the entire lint run.
2874
+ */
2875
+ function compileRegexList(patterns) {
2876
+ if (!patterns || patterns.length === 0) return [];
2877
+ const compiled = [];
2878
+ for (const p of patterns) try {
2879
+ compiled.push(new RegExp(p));
2880
+ } catch {}
2881
+ return compiled;
2882
+ }
2883
+ function matchesAny(value, list) {
2884
+ return list.some((re) => re.test(value));
2885
+ }
2886
+ //#endregion
2759
2887
  //#region src/rules/enforce-logical.ts
2760
- const PHYSICAL_TO_LOGICAL = {
2761
- ml: "ms",
2762
- mr: "me",
2763
- pl: "ps",
2764
- pr: "pe",
2765
- left: "start",
2766
- right: "end",
2767
- "border-l": "border-s",
2768
- "border-r": "border-e",
2769
- "rounded-l": "rounded-s",
2770
- "rounded-r": "rounded-e",
2771
- "rounded-tl": "rounded-ss",
2772
- "rounded-tr": "rounded-se",
2773
- "rounded-bl": "rounded-es",
2774
- "rounded-br": "rounded-ee",
2775
- "scroll-ml": "scroll-ms",
2776
- "scroll-mr": "scroll-me",
2777
- "scroll-pl": "scroll-ps",
2778
- "scroll-pr": "scroll-pe"
2888
+ const LOGICAL_PHYSICAL_SCHEMA = {
2889
+ type: "object",
2890
+ properties: {
2891
+ allowlist: {
2892
+ type: "array",
2893
+ items: { type: "string" }
2894
+ },
2895
+ direction: {
2896
+ type: "string",
2897
+ enum: [
2898
+ "inline",
2899
+ "block",
2900
+ "both"
2901
+ ]
2902
+ }
2903
+ },
2904
+ additionalProperties: false
2779
2905
  };
2906
+ const PHYSICAL_TO_LOGICAL_MAPPINGS = [
2907
+ {
2908
+ from: "ml",
2909
+ to: "ms",
2910
+ axis: "inline"
2911
+ },
2912
+ {
2913
+ from: "mr",
2914
+ to: "me",
2915
+ axis: "inline"
2916
+ },
2917
+ {
2918
+ from: "pl",
2919
+ to: "ps",
2920
+ axis: "inline"
2921
+ },
2922
+ {
2923
+ from: "pr",
2924
+ to: "pe",
2925
+ axis: "inline"
2926
+ },
2927
+ {
2928
+ from: "left",
2929
+ to: "start",
2930
+ axis: "inline"
2931
+ },
2932
+ {
2933
+ from: "right",
2934
+ to: "end",
2935
+ axis: "inline"
2936
+ },
2937
+ {
2938
+ from: "border-l",
2939
+ to: "border-s",
2940
+ axis: "inline"
2941
+ },
2942
+ {
2943
+ from: "border-r",
2944
+ to: "border-e",
2945
+ axis: "inline"
2946
+ },
2947
+ {
2948
+ from: "rounded-l",
2949
+ to: "rounded-s",
2950
+ axis: "inline"
2951
+ },
2952
+ {
2953
+ from: "rounded-r",
2954
+ to: "rounded-e",
2955
+ axis: "inline"
2956
+ },
2957
+ {
2958
+ from: "rounded-tl",
2959
+ to: "rounded-ss",
2960
+ axis: "inline"
2961
+ },
2962
+ {
2963
+ from: "rounded-tr",
2964
+ to: "rounded-se",
2965
+ axis: "inline"
2966
+ },
2967
+ {
2968
+ from: "rounded-bl",
2969
+ to: "rounded-es",
2970
+ axis: "inline"
2971
+ },
2972
+ {
2973
+ from: "rounded-br",
2974
+ to: "rounded-ee",
2975
+ axis: "inline"
2976
+ },
2977
+ {
2978
+ from: "scroll-ml",
2979
+ to: "scroll-ms",
2980
+ axis: "inline"
2981
+ },
2982
+ {
2983
+ from: "scroll-mr",
2984
+ to: "scroll-me",
2985
+ axis: "inline"
2986
+ },
2987
+ {
2988
+ from: "scroll-pl",
2989
+ to: "scroll-ps",
2990
+ axis: "inline"
2991
+ },
2992
+ {
2993
+ from: "scroll-pr",
2994
+ to: "scroll-pe",
2995
+ axis: "inline"
2996
+ }
2997
+ ];
2998
+ /** Invert a directional table. enforce-physical consumes this. */
2999
+ function invertAxisMappings(mappings) {
3000
+ return mappings.map((m) => ({
3001
+ from: m.to,
3002
+ to: m.from,
3003
+ axis: m.axis
3004
+ }));
3005
+ }
3006
+ Object.fromEntries(PHYSICAL_TO_LOGICAL_MAPPINGS.map((m) => [m.from, m.to]));
3007
+ /**
3008
+ * Build the `check` callback for a directional-rewrite rule. Both
3009
+ * enforce-logical and enforce-physical instantiate this with their own
3010
+ * mapping table and messageId; the rule's `createOnce` wires it through
3011
+ * `createExtractorVisitors`.
3012
+ *
3013
+ * Owns: option compilation (allowlist + direction), per-class conversion
3014
+ * (linear scan of the mapping table respecting `!`-prefix/suffix), and
3015
+ * the `reportClassReplacements` dispatch.
3016
+ */
3017
+ function createDirectionalMapper(context, opts) {
3018
+ const getState = createLazyOptions(context, (o) => ({
3019
+ allowlist: compileRegexList(o?.allowlist),
3020
+ direction: o?.direction ?? "both"
3021
+ }));
3022
+ function convertClass(cls) {
3023
+ const { allowlist, direction } = getState();
3024
+ if (matchesAny(cls, allowlist)) return null;
3025
+ const { utility, variant } = splitUtilityAndVariant(cls);
3026
+ const { bare: bareUtility, position } = splitImportant(utility);
3027
+ for (const { from, to, axis } of opts.mappings) {
3028
+ if (direction !== "both" && direction !== axis) continue;
3029
+ if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
3030
+ }
3031
+ return null;
3032
+ }
3033
+ function check(locations) {
3034
+ for (const loc of locations) {
3035
+ const split = splitClassesWithSeparators(loc.value);
3036
+ const offending = split.classes.flatMap((cls) => {
3037
+ const converted = convertClass(cls);
3038
+ return converted ? [{
3039
+ cls,
3040
+ replacement: converted
3041
+ }] : [];
3042
+ });
3043
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: opts.messageId });
3044
+ }
3045
+ }
3046
+ return { check };
3047
+ }
2780
3048
  const enforceLogical = defineRule({
2781
3049
  meta: {
2782
3050
  type: "suggestion",
2783
3051
  docs: { description: "Enforce logical (RTL-friendly) Tailwind CSS properties instead of physical ones" },
2784
3052
  fixable: "code",
2785
- schema: [],
3053
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
2786
3054
  hasSuggestions: true,
3055
+ defaultOptions: [{
3056
+ allowlist: [],
3057
+ direction: "both"
3058
+ }],
2787
3059
  messages: {
2788
3060
  useLogical: "\"{{className}}\" uses a physical property. Use \"{{replacement}}\" for LTR/RTL support.",
2789
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2790
- }
2791
- },
2792
- createOnce(context) {
2793
- function convertClass(cls) {
2794
- const { utility, variant } = splitUtilityAndVariant(cls);
2795
- const hasImportantPrefix = utility.startsWith("!");
2796
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
2797
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
2798
- for (const [physical, logical] of Object.entries(PHYSICAL_TO_LOGICAL)) if (bareUtility === physical || bareUtility.startsWith(`${physical}-`)) {
2799
- const suffix = bareUtility.slice(physical.length);
2800
- return `${variant}${hasImportantPrefix ? "!" : ""}${logical}${suffix}${hasImportantSuffix ? "!" : ""}`;
2801
- }
2802
- return null;
2803
- }
2804
- function check(locations) {
2805
- for (const loc of locations) {
2806
- const split = splitClassesWithSeparators(loc.value);
2807
- const classes = split.classes;
2808
- const offending = [];
2809
- for (const cls of classes) {
2810
- const converted = convertClass(cls);
2811
- if (converted) offending.push({
2812
- cls,
2813
- replacement: converted
2814
- });
2815
- }
2816
- if (offending.length === 0) continue;
2817
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2818
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
2819
- for (let i = 0; i < offending.length; i++) {
2820
- const { cls, replacement } = offending[i];
2821
- if (i === 0) context.report({
2822
- node: loc.node,
2823
- messageId: "useLogical",
2824
- data: {
2825
- className: cls,
2826
- replacement
2827
- },
2828
- fix(fixer) {
2829
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2830
- }
2831
- });
2832
- else context.report({
2833
- node: loc.node,
2834
- messageId: "useLogical",
2835
- data: {
2836
- className: cls,
2837
- replacement
2838
- },
2839
- suggest: [{
2840
- messageId: "suggestReplace",
2841
- data: {
2842
- className: cls,
2843
- replacement
2844
- },
2845
- fix(fixer) {
2846
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2847
- }
2848
- }]
2849
- });
2850
- }
2851
- }
3061
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2852
3062
  }
3063
+ },
3064
+ createOnce(context) {
3065
+ const { check } = createDirectionalMapper(context, {
3066
+ mappings: PHYSICAL_TO_LOGICAL_MAPPINGS,
3067
+ messageId: "useLogical"
3068
+ });
2853
3069
  return createExtractorVisitors(context, check);
2854
3070
  }
2855
3071
  });
2856
3072
  //#endregion
2857
3073
  //#region src/rules/enforce-physical.ts
2858
- const LOGICAL_TO_PHYSICAL = {};
2859
- for (const [physical, logical] of Object.entries(PHYSICAL_TO_LOGICAL)) LOGICAL_TO_PHYSICAL[logical] = physical;
2860
3074
  const enforcePhysical = defineRule({
2861
3075
  meta: {
2862
3076
  type: "suggestion",
2863
3077
  docs: { description: "Enforce physical Tailwind CSS properties instead of logical ones for consistency in LTR-only projects" },
2864
3078
  fixable: "code",
2865
- schema: [],
3079
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
2866
3080
  hasSuggestions: true,
3081
+ defaultOptions: [{
3082
+ allowlist: [],
3083
+ direction: "both"
3084
+ }],
2867
3085
  messages: {
2868
3086
  usePhysical: "\"{{className}}\" uses a logical property. Use \"{{replacement}}\" for consistency.",
2869
3087
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2870
3088
  }
2871
3089
  },
2872
3090
  createOnce(context) {
2873
- function convertClass(cls) {
2874
- const { utility, variant } = splitUtilityAndVariant(cls);
2875
- const hasImportantPrefix = utility.startsWith("!");
2876
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
2877
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
2878
- for (const [logical, physical] of Object.entries(LOGICAL_TO_PHYSICAL)) if (bareUtility === logical || bareUtility.startsWith(`${logical}-`)) {
2879
- const suffix = bareUtility.slice(logical.length);
2880
- return `${variant}${hasImportantPrefix ? "!" : ""}${physical}${suffix}${hasImportantSuffix ? "!" : ""}`;
2881
- }
2882
- return null;
2883
- }
2884
- function check(locations) {
2885
- for (const loc of locations) {
2886
- const split = splitClassesWithSeparators(loc.value);
2887
- const classes = split.classes;
2888
- const offending = [];
2889
- for (const cls of classes) {
2890
- const converted = convertClass(cls);
2891
- if (converted) offending.push({
2892
- cls,
2893
- replacement: converted
2894
- });
2895
- }
2896
- if (offending.length === 0) continue;
2897
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2898
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
2899
- for (let i = 0; i < offending.length; i++) {
2900
- const { cls, replacement } = offending[i];
2901
- if (i === 0) context.report({
2902
- node: loc.node,
2903
- messageId: "usePhysical",
2904
- data: {
2905
- className: cls,
2906
- replacement
2907
- },
2908
- fix(fixer) {
2909
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2910
- }
2911
- });
2912
- else context.report({
2913
- node: loc.node,
2914
- messageId: "usePhysical",
2915
- data: {
2916
- className: cls,
2917
- replacement
2918
- },
2919
- suggest: [{
2920
- messageId: "suggestReplace",
2921
- data: {
2922
- className: cls,
2923
- replacement
2924
- },
2925
- fix(fixer) {
2926
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2927
- }
2928
- }]
2929
- });
2930
- }
2931
- }
2932
- }
3091
+ const { check } = createDirectionalMapper(context, {
3092
+ mappings: invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS),
3093
+ messageId: "usePhysical"
3094
+ });
2933
3095
  return createExtractorVisitors(context, check);
2934
3096
  }
2935
3097
  });
@@ -2949,11 +3111,7 @@ const maxClassCount = defineRule({
2949
3111
  messages: { tooMany: "Too many Tailwind classes ({{count}}). Maximum allowed is {{max}}. Consider extracting into a component or utility." }
2950
3112
  },
2951
3113
  createOnce(context) {
2952
- let _max = null;
2953
- function getMax() {
2954
- if (_max === null) _max = safeOptions(context)?.max ?? DEFAULT_MAX;
2955
- return _max;
2956
- }
3114
+ const getMax = createLazyOptions(context, (o) => o?.max ?? DEFAULT_MAX);
2957
3115
  function check(locations) {
2958
3116
  const max = getMax();
2959
3117
  for (const loc of locations) {
@@ -2999,26 +3157,23 @@ const noRestrictedClasses = defineRule({
2999
3157
  },
3000
3158
  additionalProperties: false
3001
3159
  }],
3160
+ defaultOptions: [{
3161
+ classes: [],
3162
+ patterns: []
3163
+ }],
3002
3164
  messages: {
3003
3165
  restricted: "\"{{className}}\" is restricted.",
3004
3166
  restrictedWithMessage: "\"{{className}}\" is restricted: {{message}}"
3005
3167
  }
3006
3168
  },
3007
3169
  createOnce(context) {
3008
- let _config = null;
3009
- function getConfig() {
3010
- if (_config === null) {
3011
- const options = safeOptions(context);
3012
- _config = {
3013
- restrictedClasses: new Set(options?.classes ?? []),
3014
- patterns: (options?.patterns ?? []).map((p) => ({
3015
- regex: new RegExp(p.pattern),
3016
- message: p.message
3017
- }))
3018
- };
3019
- }
3020
- return _config;
3021
- }
3170
+ const getConfig = createLazyOptions(context, (o) => ({
3171
+ restrictedClasses: new Set(o?.classes ?? []),
3172
+ patterns: (o?.patterns ?? []).map((p) => ({
3173
+ regex: new RegExp(p.pattern),
3174
+ message: p.message
3175
+ }))
3176
+ }));
3022
3177
  function check(locations) {
3023
3178
  const { restrictedClasses, patterns } = getConfig();
3024
3179
  if (restrictedClasses.size === 0 && patterns.length === 0) return;
@@ -3069,14 +3224,11 @@ const noArbitraryValue = defineRule({
3069
3224
  } },
3070
3225
  additionalProperties: false
3071
3226
  }],
3227
+ defaultOptions: [{ allow: [] }],
3072
3228
  messages: { noArbitrary: "\"{{className}}\" uses an arbitrary value. Use a design token or extend your theme instead." }
3073
3229
  },
3074
3230
  createOnce(context) {
3075
- let _allowPrefixes = null;
3076
- function getAllowPrefixes() {
3077
- if (_allowPrefixes === null) _allowPrefixes = safeOptions(context)?.allow ?? [];
3078
- return _allowPrefixes;
3079
- }
3231
+ const getAllowPrefixes = createLazyOptions(context, (o) => o?.allow ?? []);
3080
3232
  function isAllowed(utility) {
3081
3233
  return getAllowPrefixes().some((prefix) => utility.startsWith(prefix));
3082
3234
  }
@@ -3085,9 +3237,7 @@ const noArbitraryValue = defineRule({
3085
3237
  const classes = splitClasses(loc.value);
3086
3238
  for (const cls of classes) {
3087
3239
  if (!hasArbitraryValue(cls)) continue;
3088
- let utility = extractUtility(cls);
3089
- if (utility.startsWith("!")) utility = utility.slice(1);
3090
- else if (utility.endsWith("!")) utility = utility.slice(0, -1);
3240
+ const utility = splitImportant(extractUtility(cls)).bare;
3091
3241
  if (isAllowed(utility)) continue;
3092
3242
  context.report({
3093
3243
  node: loc.node,
@@ -3124,11 +3274,7 @@ const enforceConsistentImportantPosition = defineRule({
3124
3274
  }
3125
3275
  },
3126
3276
  createOnce(context) {
3127
- let _position = null;
3128
- function getPosition() {
3129
- if (_position === null) _position = safeOptions(context)?.position ?? "suffix";
3130
- return _position;
3131
- }
3277
+ const getPosition = createLazyOptions(context, (o) => o?.position ?? "suffix");
3132
3278
  function fixUtility(utility, variantPfx) {
3133
3279
  const position = getPosition();
3134
3280
  if (position === "prefix" && utility.endsWith("!") && !utility.startsWith("!")) return `${variantPfx}!${utility.slice(0, -1)}`;
@@ -3136,54 +3282,18 @@ const enforceConsistentImportantPosition = defineRule({
3136
3282
  return null;
3137
3283
  }
3138
3284
  function check(locations) {
3139
- const position = getPosition();
3285
+ const messageId = getPosition() === "prefix" ? "usePrefix" : "useSuffix";
3140
3286
  for (const loc of locations) {
3141
3287
  const split = splitClassesWithSeparators(loc.value);
3142
- const classes = split.classes;
3143
- const offending = [];
3144
- for (const cls of classes) {
3288
+ const offending = split.classes.flatMap((cls) => {
3145
3289
  const { utility, variant } = splitUtilityAndVariant(cls);
3146
3290
  const fixed = fixUtility(utility, variant);
3147
- if (fixed) offending.push({
3291
+ return fixed ? [{
3148
3292
  cls,
3149
3293
  replacement: fixed
3150
- });
3151
- }
3152
- if (offending.length === 0) continue;
3153
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3154
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3155
- for (let i = 0; i < offending.length; i++) {
3156
- const { cls, replacement } = offending[i];
3157
- if (i === 0) context.report({
3158
- node: loc.node,
3159
- messageId: position === "prefix" ? "usePrefix" : "useSuffix",
3160
- data: {
3161
- className: cls,
3162
- replacement
3163
- },
3164
- fix(fixer) {
3165
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3166
- }
3167
- });
3168
- else context.report({
3169
- node: loc.node,
3170
- messageId: position === "prefix" ? "usePrefix" : "useSuffix",
3171
- data: {
3172
- className: cls,
3173
- replacement
3174
- },
3175
- suggest: [{
3176
- messageId: "suggestReplace",
3177
- data: {
3178
- className: cls,
3179
- replacement
3180
- },
3181
- fix(fixer) {
3182
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3183
- }
3184
- }]
3185
- });
3186
- }
3294
+ }] : [];
3295
+ });
3296
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3187
3297
  }
3188
3298
  }
3189
3299
  return createExtractorVisitors(context, check);
@@ -3226,50 +3336,14 @@ const enforceNegativeArbitraryValues = defineRule({
3226
3336
  function check(locations) {
3227
3337
  for (const loc of locations) {
3228
3338
  const split = splitClassesWithSeparators(loc.value);
3229
- const classes = split.classes;
3230
- const offending = [];
3231
- for (const cls of classes) {
3339
+ const offending = split.classes.flatMap((cls) => {
3232
3340
  const fixed = fixClass(cls);
3233
- if (fixed) offending.push({
3341
+ return fixed ? [{
3234
3342
  cls,
3235
3343
  replacement: fixed
3236
- });
3237
- }
3238
- if (offending.length === 0) continue;
3239
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3240
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3241
- for (let i = 0; i < offending.length; i++) {
3242
- const { cls, replacement } = offending[i];
3243
- if (i === 0) context.report({
3244
- node: loc.node,
3245
- messageId: "moveNegative",
3246
- data: {
3247
- className: cls,
3248
- replacement
3249
- },
3250
- fix(fixer) {
3251
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3252
- }
3253
- });
3254
- else context.report({
3255
- node: loc.node,
3256
- messageId: "moveNegative",
3257
- data: {
3258
- className: cls,
3259
- replacement
3260
- },
3261
- suggest: [{
3262
- messageId: "suggestReplace",
3263
- data: {
3264
- className: cls,
3265
- replacement
3266
- },
3267
- fix(fixer) {
3268
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3269
- }
3270
- }]
3271
- });
3272
- }
3344
+ }] : [];
3345
+ });
3346
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "moveNegative" });
3273
3347
  }
3274
3348
  }
3275
3349
  return createExtractorVisitors(context, check);
@@ -3281,22 +3355,18 @@ const EXPLICIT_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\[var\((--[a-zA-Z0-9-
3281
3355
  const SHORTHAND_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\((--[a-zA-Z0-9-]+)\)$/;
3282
3356
  function convertClass(cls, syntax) {
3283
3357
  const { utility, variant } = splitUtilityAndVariant(cls);
3284
- const hasImportantPrefix = utility.startsWith("!");
3285
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
3286
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
3287
- const importantStart = hasImportantPrefix ? "!" : "";
3288
- const importantEnd = hasImportantSuffix ? "!" : "";
3358
+ const { bare: bareUtility, position } = splitImportant(utility);
3289
3359
  if (syntax === "shorthand") {
3290
3360
  const match = EXPLICIT_VAR_RE.exec(bareUtility);
3291
3361
  if (match) {
3292
3362
  const [, prefix, varName] = match;
3293
- return `${variant}${importantStart}${prefix}-(${varName})${importantEnd}`;
3363
+ return `${variant}${reattachImportant(`${prefix}-(${varName})`, position)}`;
3294
3364
  }
3295
3365
  } else {
3296
3366
  const match = SHORTHAND_VAR_RE.exec(bareUtility);
3297
3367
  if (match) {
3298
3368
  const [, prefix, varName] = match;
3299
- return `${variant}${importantStart}${prefix}-[var(${varName})]${importantEnd}`;
3369
+ return `${variant}${reattachImportant(`${prefix}-[var(${varName})]`, position)}`;
3300
3370
  }
3301
3371
  }
3302
3372
  return null;
@@ -3323,60 +3393,20 @@ const enforceConsistentVariableSyntax = defineRule({
3323
3393
  }
3324
3394
  },
3325
3395
  createOnce(context) {
3326
- let _syntax = null;
3327
- function getSyntax() {
3328
- if (_syntax === null) _syntax = safeOptions(context)?.syntax ?? "shorthand";
3329
- return _syntax;
3330
- }
3396
+ const getSyntax = createLazyOptions(context, (o) => o?.syntax ?? "shorthand");
3331
3397
  function check(locations) {
3332
3398
  const syntax = getSyntax();
3399
+ const messageId = syntax === "shorthand" ? "useShorthand" : "useExplicit";
3333
3400
  for (const loc of locations) {
3334
3401
  const split = splitClassesWithSeparators(loc.value);
3335
- const classes = split.classes;
3336
- const offending = [];
3337
- for (const cls of classes) {
3402
+ const offending = split.classes.flatMap((cls) => {
3338
3403
  const converted = convertClass(cls, syntax);
3339
- if (converted) offending.push({
3404
+ return converted ? [{
3340
3405
  cls,
3341
3406
  replacement: converted
3342
- });
3343
- }
3344
- if (offending.length === 0) continue;
3345
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3346
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3347
- const messageId = syntax === "shorthand" ? "useShorthand" : "useExplicit";
3348
- for (let i = 0; i < offending.length; i++) {
3349
- const { cls, replacement } = offending[i];
3350
- if (i === 0) context.report({
3351
- node: loc.node,
3352
- messageId,
3353
- data: {
3354
- className: cls,
3355
- replacement
3356
- },
3357
- fix(fixer) {
3358
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3359
- }
3360
- });
3361
- else context.report({
3362
- node: loc.node,
3363
- messageId,
3364
- data: {
3365
- className: cls,
3366
- replacement
3367
- },
3368
- suggest: [{
3369
- messageId: "suggestReplace",
3370
- data: {
3371
- className: cls,
3372
- replacement
3373
- },
3374
- fix(fixer) {
3375
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3376
- }
3377
- }]
3378
- });
3379
- }
3407
+ }] : [];
3408
+ });
3409
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3380
3410
  }
3381
3411
  }
3382
3412
  return createExtractorVisitors(context, check);
@@ -3422,9 +3452,7 @@ const KNOWN_PREFIXES = [
3422
3452
  * Used to group utilities by their property type.
3423
3453
  */
3424
3454
  function getUtilityPrefix(utility) {
3425
- let u = utility;
3426
- if (u.startsWith("!")) u = u.slice(1);
3427
- else if (u.endsWith("!")) u = u.slice(0, -1);
3455
+ let u = splitImportant(utility).bare;
3428
3456
  if (u.startsWith("-")) u = u.slice(1);
3429
3457
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3430
3458
  const dashIdx = u.indexOf("-");
@@ -3446,14 +3474,7 @@ const noDarkWithoutLight = defineRule({
3446
3474
  messages: { missingBase: "\"{{className}}\" uses the {{variant}} variant, but there is no base \"{{prefix}}-*\" class on this element." }
3447
3475
  },
3448
3476
  createOnce(context) {
3449
- let _watchedVariants = null;
3450
- function getWatchedVariants() {
3451
- if (_watchedVariants === null) {
3452
- const options = safeOptions(context);
3453
- _watchedVariants = new Set(options?.variants ?? DEFAULT_VARIANTS);
3454
- }
3455
- return _watchedVariants;
3456
- }
3477
+ const getWatchedVariants = createLazyOptions(context, (o) => new Set(o?.variants ?? DEFAULT_VARIANTS));
3457
3478
  function check(locations) {
3458
3479
  const watchedVariants = getWatchedVariants();
3459
3480
  for (const loc of locations) {
@@ -3549,17 +3570,11 @@ const noHardcodedColors = defineRule({
3549
3570
  },
3550
3571
  additionalProperties: false
3551
3572
  }],
3573
+ defaultOptions: [{ allow: [] }],
3552
3574
  messages: { noHardcoded: "\"{{className}}\" uses a hardcoded color value. Use a design token from your theme instead." }
3553
3575
  },
3554
3576
  createOnce(context) {
3555
- let _allowlist = null;
3556
- function getAllowlist() {
3557
- if (_allowlist === null) {
3558
- const options = safeOptions(context);
3559
- _allowlist = new Set(options?.allow ?? []);
3560
- }
3561
- return _allowlist;
3562
- }
3577
+ const getAllowlist = createLazyOptions(context, (o) => new Set(o?.allow ?? []));
3563
3578
  function check(locations) {
3564
3579
  const allowlist = getAllowlist();
3565
3580
  for (const loc of locations) {
@@ -3567,9 +3582,7 @@ const noHardcodedColors = defineRule({
3567
3582
  for (const cls of classes) {
3568
3583
  if (allowlist.has(cls)) continue;
3569
3584
  if (!hasArbitraryValue(cls)) continue;
3570
- let utility = extractUtility(cls);
3571
- if (utility.startsWith("!")) utility = utility.slice(1);
3572
- else if (utility.endsWith("!")) utility = utility.slice(0, -1);
3585
+ const utility = splitImportant(extractUtility(cls)).bare;
3573
3586
  if (!isColorUtility(utility)) continue;
3574
3587
  const value = getArbitraryValue(cls);
3575
3588
  if (!value) continue;
@@ -3740,6 +3753,7 @@ const consistentVariantOrder = defineRule({
3740
3753
  additionalProperties: false
3741
3754
  }],
3742
3755
  hasSuggestions: true,
3756
+ defaultOptions: [{}],
3743
3757
  messages: {
3744
3758
  wrongOrder: "\"{{className}}\" has variants in wrong order. Use \"{{replacement}}\" instead.",
3745
3759
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
@@ -3747,54 +3761,33 @@ const consistentVariantOrder = defineRule({
3747
3761
  },
3748
3762
  createOnce(context) {
3749
3763
  const getDS = createLazyLoader(context);
3750
- let _config = null;
3751
- function getConfig() {
3752
- if (_config === null) {
3753
- const options = safeOptions(context);
3754
- const dsCache = getDS()?.cache ?? null;
3755
- const priorityMap = /* @__PURE__ */ new Map();
3756
- if (options?.order) {
3757
- for (let i = 0; i < options.order.length; i++) priorityMap.set(options.order[i], i);
3758
- _config = {
3759
- priorityMap,
3760
- fallbackPriority: options.order.length,
3761
- dsCache
3762
- };
3763
- } else if (dsCache && dsCache.hasVariantOrder()) {
3764
- for (const variant of DEFAULT_VARIANT_ORDER) {
3765
- const p = dsCache.getVariantPriority(variant);
3766
- if (p !== null) priorityMap.set(variant, p);
3767
- }
3768
- _config = {
3769
- priorityMap,
3770
- fallbackPriority: Number.MAX_SAFE_INTEGER,
3771
- dsCache
3772
- };
3773
- } else {
3774
- for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) priorityMap.set(DEFAULT_VARIANT_ORDER[i], i);
3775
- _config = {
3776
- priorityMap,
3777
- fallbackPriority: DEFAULT_VARIANT_ORDER.length,
3778
- dsCache
3779
- };
3780
- }
3764
+ const getPriority = createLazyOptions(context, (o) => {
3765
+ let dsCache = null;
3766
+ try {
3767
+ dsCache = getDS().cache;
3768
+ } catch (err) {
3769
+ if (!isFatalError(err)) throw err;
3770
+ }
3771
+ if (o?.order) {
3772
+ const map = /* @__PURE__ */ new Map();
3773
+ for (let i = 0; i < o.order.length; i++) map.set(o.order[i], i);
3774
+ const fallback = o.order.length;
3775
+ return (v) => map.get(v) ?? fallback;
3781
3776
  }
3782
- return _config;
3783
- }
3784
- function getVariantPriority(variant) {
3785
- const { priorityMap, fallbackPriority, dsCache } = getConfig();
3786
- const priority = priorityMap.get(variant);
3787
- if (priority !== void 0) return priority;
3788
3777
  if (dsCache && dsCache.hasVariantOrder()) {
3789
- const dsPriority = dsCache.getVariantPriority(variant);
3790
- if (dsPriority !== null) return dsPriority;
3778
+ const ds = dsCache;
3779
+ return (v) => ds.getVariantPriority(v) ?? Number.MAX_SAFE_INTEGER;
3791
3780
  }
3792
- return fallbackPriority;
3793
- }
3781
+ const map = /* @__PURE__ */ new Map();
3782
+ for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3783
+ const fallback = DEFAULT_VARIANT_ORDER.length;
3784
+ return (v) => map.get(v) ?? fallback;
3785
+ });
3794
3786
  function reorderClass(cls) {
3795
3787
  const variants = extractVariants(cls);
3796
3788
  if (variants.length < 2) return null;
3797
- const sorted = [...variants].sort((a, b) => getVariantPriority(a) - getVariantPriority(b));
3789
+ const priorityOf = getPriority();
3790
+ const sorted = [...variants].sort((a, b) => priorityOf(a) - priorityOf(b));
3798
3791
  const nonPseudo = [];
3799
3792
  const pseudo = [];
3800
3793
  for (const v of sorted) if (PSEUDO_ELEMENTS.has(v)) pseudo.push(v);
@@ -3879,16 +3872,8 @@ const enforceConsistentLineWrapping = defineRule({
3879
3872
  }
3880
3873
  },
3881
3874
  createOnce(context) {
3882
- let _printWidth = null;
3883
- function getPrintWidth() {
3884
- if (_printWidth === null) _printWidth = safeOptions(context)?.printWidth ?? DEFAULT_PRINT_WIDTH;
3885
- return _printWidth;
3886
- }
3887
- let _classesPerLine = null;
3888
- function getClassesPerLine() {
3889
- if (_classesPerLine === null) _classesPerLine = safeOptions(context)?.classesPerLine ?? void 0;
3890
- return _classesPerLine;
3891
- }
3875
+ const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
3876
+ const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
3892
3877
  function check(locations) {
3893
3878
  const printWidth = getPrintWidth();
3894
3879
  const classesPerLine = getClassesPerLine();
@@ -3947,69 +3932,33 @@ const noUnnecessaryArbitraryValue = defineRule({
3947
3932
  additionalProperties: false
3948
3933
  }],
3949
3934
  hasSuggestions: true,
3935
+ defaultOptions: [{}],
3950
3936
  messages: {
3951
3937
  unnecessaryArbitrary: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named class instead.",
3952
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3938
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
3939
+ ...DS_UNAVAILABLE_MESSAGE
3953
3940
  }
3954
3941
  },
3955
3942
  createOnce(context) {
3956
3943
  const getDS = createLazyLoader(context);
3957
3944
  function check(locations) {
3958
- const ds = getDS();
3945
+ if (locations.length === 0) return;
3946
+ const ds = safeGetDS(getDS, context, locations[0].node);
3959
3947
  if (!ds) return;
3960
3948
  const { cache } = ds;
3961
3949
  for (const loc of locations) {
3962
3950
  const split = splitClassesWithSeparators(loc.value);
3963
- const classes = split.classes;
3964
- const offending = [];
3965
- for (const cls of classes) {
3966
- if (!hasArbitraryValue(cls)) continue;
3951
+ const offending = split.classes.flatMap((cls) => {
3952
+ if (!hasArbitraryValue(cls)) return [];
3967
3953
  const { utility, variant } = splitUtilityAndVariant(cls);
3968
- const hasImportantPrefix = utility.startsWith("!");
3969
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
3970
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
3954
+ const { bare: bareUtility, position } = splitImportant(utility);
3971
3955
  const named = cache.getNamedEquivalent(bareUtility);
3972
- if (!named) continue;
3973
- offending.push({
3956
+ return named ? [{
3974
3957
  cls,
3975
- replacement: variant + (hasImportantPrefix ? "!" : "") + named + (hasImportantSuffix ? "!" : "")
3976
- });
3977
- }
3978
- if (offending.length === 0) continue;
3979
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3980
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3981
- for (let i = 0; i < offending.length; i++) {
3982
- const { cls, replacement } = offending[i];
3983
- if (i === 0) context.report({
3984
- node: loc.node,
3985
- messageId: "unnecessaryArbitrary",
3986
- data: {
3987
- className: cls,
3988
- replacement
3989
- },
3990
- fix(fixer) {
3991
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3992
- }
3993
- });
3994
- else context.report({
3995
- node: loc.node,
3996
- messageId: "unnecessaryArbitrary",
3997
- data: {
3998
- className: cls,
3999
- replacement
4000
- },
4001
- suggest: [{
4002
- messageId: "suggestReplace",
4003
- data: {
4004
- className: cls,
4005
- replacement
4006
- },
4007
- fix(fixer) {
4008
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4009
- }
4010
- }]
4011
- });
4012
- }
3958
+ replacement: variant + reattachImportant(named, position)
3959
+ }] : [];
3960
+ });
3961
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "unnecessaryArbitrary" });
4013
3962
  }
4014
3963
  }
4015
3964
  return createExtractorVisitors(context, check);
@@ -4080,73 +4029,37 @@ const plugin = definePlugin({
4080
4029
  additionalProperties: false
4081
4030
  }],
4082
4031
  hasSuggestions: true,
4032
+ defaultOptions: [{}],
4083
4033
  messages: {
4084
4034
  preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
4085
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
4035
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
4036
+ ...DS_UNAVAILABLE_MESSAGE
4086
4037
  }
4087
4038
  },
4088
4039
  createOnce(context) {
4089
4040
  const getDS = createLazyLoader(context);
4090
4041
  function check(locations) {
4091
- const ds = getDS();
4042
+ if (locations.length === 0) return;
4043
+ const ds = safeGetDS(getDS, context, locations[0].node);
4092
4044
  if (!ds) return;
4093
4045
  const { cache } = ds;
4094
4046
  for (const loc of locations) {
4095
4047
  const split = splitClassesWithSeparators(loc.value);
4096
- const classes = split.classes;
4097
- const offending = [];
4098
- for (const cls of classes) {
4048
+ const offending = split.classes.flatMap((cls) => {
4099
4049
  const { utility, variant } = splitUtilityAndVariant(cls);
4100
- const hasImportantPrefix = utility.startsWith("!");
4101
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
4102
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
4050
+ const { bare: bareUtility, position } = splitImportant(utility);
4103
4051
  const match = detectRawVariable(bareUtility);
4104
- if (!match) continue;
4052
+ if (!match) return [];
4105
4053
  const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
4106
- if (!cache.isValid(candidate)) continue;
4054
+ if (!cache.isValid(candidate)) return [];
4107
4055
  const namedEquivalent = cache.getNamedEquivalent(bareUtility);
4108
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) continue;
4109
- const replacement = variant + (hasImportantPrefix ? "!" : "") + candidate + (hasImportantSuffix ? "!" : "");
4110
- offending.push({
4056
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
4057
+ return [{
4111
4058
  cls,
4112
- replacement
4113
- });
4114
- }
4115
- if (offending.length === 0) continue;
4116
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
4117
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
4118
- for (let i = 0; i < offending.length; i++) {
4119
- const { cls, replacement } = offending[i];
4120
- if (i === 0) context.report({
4121
- node: loc.node,
4122
- messageId: "preferNamed",
4123
- data: {
4124
- className: cls,
4125
- replacement
4126
- },
4127
- fix(fixer) {
4128
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4129
- }
4130
- });
4131
- else context.report({
4132
- node: loc.node,
4133
- messageId: "preferNamed",
4134
- data: {
4135
- className: cls,
4136
- replacement
4137
- },
4138
- suggest: [{
4139
- messageId: "suggestReplace",
4140
- data: {
4141
- className: cls,
4142
- replacement
4143
- },
4144
- fix(fixer) {
4145
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4146
- }
4147
- }]
4148
- });
4149
- }
4059
+ replacement: variant + reattachImportant(candidate, position)
4060
+ }];
4061
+ });
4062
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
4150
4063
  }
4151
4064
  }
4152
4065
  return createExtractorVisitors(context, check);