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