oxlint-tailwindcss 0.8.0 → 1.0.1

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
@@ -1,10 +1,9 @@
1
1
  let _oxlint_plugins = require("@oxlint/plugins");
2
- let node_child_process = require("node:child_process");
2
+ let node_worker_threads = require("node:worker_threads");
3
3
  let node_crypto = require("node:crypto");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  let node_os = require("node:os");
7
- let node_worker_threads = require("node:worker_threads");
8
7
  //#region src/utils/extractors.ts
9
8
  /**
10
9
  * Preserves leading/trailing spaces in fixed class strings for template literals.
@@ -40,8 +39,7 @@ const DEFAULT_EXTRACTOR_CONFIG = {
40
39
  /^styles?$/
41
40
  ]
42
41
  };
43
- let _cachedConfig = null;
44
- let _settingsResolved = false;
42
+ const configCache = /* @__PURE__ */ new WeakMap();
45
43
  function mergeUnique(defaults, extras, exclusions) {
46
44
  let base = defaults;
47
45
  if (exclusions && exclusions.length > 0) {
@@ -54,34 +52,39 @@ function mergeUnique(defaults, extras, exclusions) {
54
52
  return [...set];
55
53
  }
56
54
  /**
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.
55
+ * Returns the extractor config for this rule context, merging defaults with
56
+ * user settings from `settings.tailwindcss`. The result is cached per
57
+ * context (WeakMap-keyed) so settings are read once per rule lifetime.
58
+ *
59
+ * In `createOnce` the settings getter throws — we fall back to the defaults
60
+ * without caching so the next visitor call (where settings ARE available)
61
+ * still resolves the user's overrides.
60
62
  */
61
63
  function getExtractorConfig(context) {
62
- if (_settingsResolved) return _cachedConfig;
64
+ const cached = configCache.get(context);
65
+ if (cached) return cached;
63
66
  let tw;
64
67
  try {
65
68
  const raw = context.settings?.tailwindcss;
66
69
  if (raw && typeof raw === "object") tw = raw;
67
- _settingsResolved = true;
68
70
  } catch {
69
71
  return DEFAULT_EXTRACTOR_CONFIG;
70
72
  }
71
73
  if (!tw) {
72
- _cachedConfig = DEFAULT_EXTRACTOR_CONFIG;
73
- return _cachedConfig;
74
+ configCache.set(context, DEFAULT_EXTRACTOR_CONFIG);
75
+ return DEFAULT_EXTRACTOR_CONFIG;
74
76
  }
75
77
  const exclude = tw.exclude;
76
78
  const excludedPatternSources = new Set(exclude?.variablePatterns ?? []);
77
79
  const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
78
- _cachedConfig = {
80
+ const resolved = {
79
81
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
80
82
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
81
83
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
82
84
  variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
83
85
  };
84
- return _cachedConfig;
86
+ configCache.set(context, resolved);
87
+ return resolved;
85
88
  }
86
89
  /**
87
90
  * Creates the 4 standard AST visitor callbacks that all rules use.
@@ -134,7 +137,7 @@ function extractFromCallExpression(node, config = DEFAULT_EXTRACTOR_CONFIG) {
134
137
  if (calleeName === "tv") return extractFromTvCall(node);
135
138
  if (calleeName === "classed") return extractFromClassedCall(node);
136
139
  const results = [];
137
- for (const arg of node.arguments) results.push(...extractFromExpression(arg));
140
+ for (const arg of node.arguments) extractFromExpression(arg, results);
138
141
  return results;
139
142
  }
140
143
  /**
@@ -152,7 +155,7 @@ function extractFromTaggedTemplate(node, config = DEFAULT_EXTRACTOR_CONFIG) {
152
155
  */
153
156
  function extractObjectValues(node) {
154
157
  const results = [];
155
- for (const prop of node.properties) if (prop.type === "Property") results.push(...extractFromExpression(prop.value));
158
+ for (const prop of node.properties) if (prop.type === "Property") extractFromExpression(prop.value, results);
156
159
  return results;
157
160
  }
158
161
  /**
@@ -179,7 +182,7 @@ function extractFromClassedCall(node) {
179
182
  }
180
183
  skippedFirst = true;
181
184
  if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
182
- else results.push(...extractFromExpression(arg));
185
+ else extractFromExpression(arg, results);
183
186
  }
184
187
  return results;
185
188
  }
@@ -190,7 +193,7 @@ function extractFromClassedCall(node) {
190
193
  function extractFromCvaCall(node) {
191
194
  const results = [];
192
195
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
193
- else results.push(...extractFromExpression(arg));
196
+ else extractFromExpression(arg, results);
194
197
  return results;
195
198
  }
196
199
  /**
@@ -205,10 +208,10 @@ function extractFromCvaConfig(node) {
205
208
  const name = getPropertyName(prop.key);
206
209
  if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
207
210
  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));
211
+ for (const variant of category.value.properties) if (variant.type === "Property") extractFromExpression(variant.value, results);
209
212
  }
210
213
  else if (name === "compoundVariants" && prop.value.type === "ArrayExpression") results.push(...extractClassFromCompoundEntries(prop.value));
211
- else if (name === "defaultVariants") {} else results.push(...extractFromExpression(prop.value));
214
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
212
215
  }
213
216
  return results;
214
217
  }
@@ -219,7 +222,7 @@ function extractFromCvaConfig(node) {
219
222
  function extractFromTvCall(node) {
220
223
  const results = [];
221
224
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromTvConfig(arg));
222
- else results.push(...extractFromExpression(arg));
225
+ else extractFromExpression(arg, results);
223
226
  return results;
224
227
  }
225
228
  /**
@@ -232,20 +235,20 @@ function extractFromTvConfig(node) {
232
235
  for (const prop of node.properties) {
233
236
  if (prop.type !== "Property") continue;
234
237
  const name = getPropertyName(prop.key);
235
- if (name === "base") results.push(...extractFromExpression(prop.value));
238
+ if (name === "base") extractFromExpression(prop.value, results);
236
239
  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));
240
+ for (const slot of prop.value.properties) if (slot.type === "Property") extractFromExpression(slot.value, results);
238
241
  } else if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
239
242
  if (category.type !== "Property" || category.value.type !== "ObjectExpression") continue;
240
243
  for (const variant of category.value.properties) {
241
244
  if (variant.type !== "Property") continue;
242
245
  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));
246
+ for (const slotProp of variant.value.properties) if (slotProp.type === "Property") extractFromExpression(slotProp.value, results);
247
+ } else extractFromExpression(variant.value, results);
245
248
  }
246
249
  }
247
250
  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));
251
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
249
252
  }
250
253
  return results;
251
254
  }
@@ -260,7 +263,7 @@ function extractClassFromCompoundEntries(node) {
260
263
  for (const prop of element.properties) {
261
264
  if (prop.type !== "Property") continue;
262
265
  const name = getPropertyName(prop.key);
263
- if (name === "class" || name === "className") results.push(...extractFromExpression(prop.value));
266
+ if (name === "class" || name === "className") extractFromExpression(prop.value, results);
264
267
  }
265
268
  }
266
269
  return results;
@@ -282,34 +285,51 @@ function extractFromVariableDeclarator(node, config = DEFAULT_EXTRACTOR_CONFIG)
282
285
  if (!node.init) return [];
283
286
  return extractFromExpression(node.init);
284
287
  }
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);
288
+ /**
289
+ * Walk an expression and append every class-bearing location to `out`.
290
+ *
291
+ * Internal helpers pass their accumulator down to avoid the
292
+ * `extractFromExpression(x, results)` pattern, which allocates an
293
+ * intermediate array per recursive call. Public callers may omit `out` to
294
+ * receive a fresh array.
295
+ */
296
+ function extractFromExpression(node, out = []) {
297
+ if (node.type === "Literal" && typeof node.value === "string") {
298
+ out.push({
299
+ value: node.value,
300
+ node,
301
+ range: [node.range[0] + 1, node.range[1] - 1]
302
+ });
303
+ return out;
304
+ }
305
+ if (node.type === "TemplateLiteral") return appendFromTemplateLiteral(node, out);
306
+ if (node.type === "ConditionalExpression") {
307
+ extractFromExpression(node.consequent, out);
308
+ extractFromExpression(node.alternate, out);
309
+ return out;
310
+ }
311
+ if (node.type === "LogicalExpression") return extractFromExpression(node.right, out);
312
+ if (node.type === "ArrayExpression") {
313
+ for (const element of node.elements) if (element && element.type !== "SpreadElement") extractFromExpression(element, out);
314
+ return out;
315
+ }
294
316
  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({
317
+ for (const prop of node.properties) if (prop.type === "Property" && prop.key.type === "Literal" && typeof prop.key.value === "string") out.push({
297
318
  value: prop.key.value,
298
319
  node: prop.key,
299
320
  range: [prop.key.range[0] + 1, prop.key.range[1] - 1]
300
321
  });
301
- return results;
322
+ return out;
302
323
  }
303
- return [];
324
+ return out;
304
325
  }
305
- function extractFromTemplateLiteral(node) {
306
- const results = [];
326
+ function appendFromTemplateLiteral(node, out) {
307
327
  for (let i = 0; i < node.quasis.length; i++) {
308
328
  const quasi = node.quasis[i];
309
329
  const value = quasi.value.raw;
310
330
  if (value.trim().length > 0) {
311
331
  const start = quasi.range[0] + 1;
312
- results.push({
332
+ out.push({
313
333
  value,
314
334
  node: quasi,
315
335
  range: [start, start + value.length],
@@ -318,7 +338,10 @@ function extractFromTemplateLiteral(node) {
318
338
  });
319
339
  }
320
340
  }
321
- return results;
341
+ return out;
342
+ }
343
+ function extractFromTemplateLiteral(node) {
344
+ return appendFromTemplateLiteral(node, []);
322
345
  }
323
346
  function getCalleeName(node) {
324
347
  if (node.type === "Identifier") return node.name;
@@ -532,21 +555,6 @@ function findBestSuggestion(input, candidates, maxDistance = 3) {
532
555
  return best;
533
556
  }
534
557
  //#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
558
  //#region src/utils/class-parser.ts
551
559
  /**
552
560
  * Extracts variants from a class string, respecting bracket depth.
@@ -653,23 +661,53 @@ function getArbitraryValue(cls) {
653
661
  }
654
662
  return null;
655
663
  }
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
664
+ /**
665
+ * Strip the `!` important modifier from a utility's bare form (no variant
666
+ * prefix). Returns the bare string and the original position. Operate on
667
+ * the utility part — call `splitUtilityAndVariant` first if you have the
668
+ * full class. `parseClass` does both in one pass; use that when you need
669
+ * the full ParsedClass shape.
670
+ */
671
+ function splitImportant(utility) {
672
+ if (utility.startsWith("!")) return {
673
+ bare: utility.slice(1),
674
+ position: "prefix"
663
675
  };
664
- if (cls.endsWith("!")) return {
665
- bare: cls.slice(0, -1),
666
- important: true
676
+ if (utility.endsWith("!")) return {
677
+ bare: utility.slice(0, -1),
678
+ position: "suffix"
667
679
  };
668
680
  return {
669
- bare: cls,
670
- important: false
681
+ bare: utility,
682
+ position: null
671
683
  };
672
684
  }
685
+ /**
686
+ * Reattach `!` at the position recorded by `splitImportant`.
687
+ * The inverse of `splitImportant`: `reattachImportant(splitImportant(x).bare, splitImportant(x).position) === x`.
688
+ */
689
+ function reattachImportant(bare, position) {
690
+ if (position === "prefix") return `!${bare}`;
691
+ if (position === "suffix") return `${bare}!`;
692
+ return bare;
693
+ }
694
+ //#endregion
695
+ //#region src/utils/floating-point.ts
696
+ /**
697
+ * Rounds rem/em/px values in class strings to avoid
698
+ * JavaScript floating point issues.
699
+ *
700
+ * Example: "text-lg/[2.4000000000000004rem]" -> "text-lg/[2.4rem]"
701
+ *
702
+ * Regression test for: better-tailwindcss#320
703
+ */
704
+ function roundRemValue(className) {
705
+ return className.replace(/\[(-?\d+\.\d{7,})(rem|em|px|%)\]/g, (_, num, unit) => {
706
+ return `[${Number.parseFloat(Number.parseFloat(num).toFixed(6))}${unit}]`;
707
+ });
708
+ }
709
+ //#endregion
710
+ //#region src/design-system/cache.ts
673
711
  var DesignSystemCache = class DesignSystemCache {
674
712
  canonicalMap = /* @__PURE__ */ new Map();
675
713
  validitySet = /* @__PURE__ */ new Set();
@@ -710,12 +748,12 @@ var DesignSystemCache = class DesignSystemCache {
710
748
  const canonicalUtility = this.canonicalMap.get(utility);
711
749
  if (canonicalUtility !== void 0) return className.slice(0, className.length - utility.length) + canonicalUtility;
712
750
  }
713
- const { bare, important } = stripImportant$1(utility);
714
- if (important) {
751
+ const { bare, position } = splitImportant(utility);
752
+ if (position) {
715
753
  const canonicalBare = this.canonicalMap.get(bare);
716
754
  if (canonicalBare !== void 0) {
717
755
  const variantPrefix = className.slice(0, className.length - utility.length);
718
- return utility.startsWith("!") ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
756
+ return position === "prefix" ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
719
757
  }
720
758
  }
721
759
  return className;
@@ -745,6 +783,20 @@ var DesignSystemCache = class DesignSystemCache {
745
783
  if (variant.startsWith("aria-")) return (this.variantOrderMap.get("inert") ?? 48) + 2;
746
784
  return 0;
747
785
  }
786
+ _prefixOrderMap = null;
787
+ buildPrefixOrderMap() {
788
+ const index = /* @__PURE__ */ new Map();
789
+ for (const [cls, order] of this.orderMap) {
790
+ if (order === null) continue;
791
+ for (let i = cls.indexOf("-"); i >= 0; i = cls.indexOf("-", i + 1)) {
792
+ const p = cls.slice(0, i);
793
+ if (!index.has(p)) index.set(p, order);
794
+ const pd = p + "-";
795
+ if (!index.has(pd)) index.set(pd, order);
796
+ }
797
+ }
798
+ return index;
799
+ }
748
800
  /** Find the order of the first class matching a prefix (e.g. "max-w-" → order of "max-w-0") */
749
801
  findOrderByPrefix(prefix) {
750
802
  const withoutDash = prefix.endsWith("-") ? prefix.slice(0, -1) : null;
@@ -752,7 +804,8 @@ var DesignSystemCache = class DesignSystemCache {
752
804
  const order = this.orderMap.get(withoutDash);
753
805
  if (order != null) return order;
754
806
  }
755
- for (const [cls, order] of this.orderMap) if (cls.startsWith(prefix) && order != null) return order;
807
+ if (!this._prefixOrderMap) this._prefixOrderMap = this.buildPrefixOrderMap();
808
+ return this._prefixOrderMap.get(prefix);
756
809
  }
757
810
  getKnownPrefixes() {
758
811
  if (!this._knownPrefixes) {
@@ -768,7 +821,7 @@ var DesignSystemCache = class DesignSystemCache {
768
821
  if (this.validitySet.has(className)) return true;
769
822
  const utility = extractUtility(className);
770
823
  if (utility !== className && this.validitySet.has(utility)) return true;
771
- const { bare } = stripImportant$1(utility);
824
+ const { bare } = splitImportant(utility);
772
825
  if (bare !== utility && this.validitySet.has(bare)) return true;
773
826
  const slashIdx = bare.lastIndexOf("/");
774
827
  if (slashIdx > 0) {
@@ -792,8 +845,8 @@ var DesignSystemCache = class DesignSystemCache {
792
845
  const hasVariant = utility !== className;
793
846
  let baseOrder = this.orderMap.get(utility) ?? void 0;
794
847
  if (baseOrder === void 0) {
795
- const { bare, important } = stripImportant$1(utility);
796
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
848
+ const { bare, position } = splitImportant(utility);
849
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
797
850
  }
798
851
  if (baseOrder === void 0) {
799
852
  const slashIdx = utility.lastIndexOf("/");
@@ -801,13 +854,13 @@ var DesignSystemCache = class DesignSystemCache {
801
854
  const base = utility.slice(0, slashIdx);
802
855
  baseOrder = this.orderMap.get(base) ?? void 0;
803
856
  if (baseOrder === void 0) {
804
- const { bare, important } = stripImportant$1(base);
805
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
857
+ const { bare, position } = splitImportant(base);
858
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
806
859
  }
807
860
  }
808
861
  }
809
862
  if (baseOrder === void 0) {
810
- const stripped = stripImportant$1(utility).bare;
863
+ const stripped = splitImportant(utility).bare;
811
864
  const bracketIdx = stripped.indexOf("[");
812
865
  if (bracketIdx > 0) {
813
866
  const prefix = stripped.slice(0, bracketIdx);
@@ -815,7 +868,7 @@ var DesignSystemCache = class DesignSystemCache {
815
868
  }
816
869
  }
817
870
  if (baseOrder === void 0) {
818
- const stripped = stripImportant$1(utility).bare;
871
+ const stripped = splitImportant(utility).bare;
819
872
  const parenIdx = stripped.indexOf("(");
820
873
  if (parenIdx > 0) {
821
874
  const prefix = stripped.slice(0, parenIdx);
@@ -823,7 +876,7 @@ var DesignSystemCache = class DesignSystemCache {
823
876
  }
824
877
  }
825
878
  if (baseOrder === void 0) {
826
- const stripped = stripImportant$1(utility).bare;
879
+ const stripped = splitImportant(utility).bare;
827
880
  const numericMatch = /^(.+)-(\d+\.?\d*)$/.exec(stripped);
828
881
  if (numericMatch && this.getKnownPrefixes().has(numericMatch[1])) baseOrder = this.findOrderByPrefix(numericMatch[1] + "-");
829
882
  }
@@ -842,8 +895,8 @@ var DesignSystemCache = class DesignSystemCache {
842
895
  getCssProperties(className) {
843
896
  const result = this.cssPropsMap.get(className);
844
897
  if (result) return result;
845
- const { bare, important } = stripImportant$1(className);
846
- if (important) return this.cssPropsMap.get(bare) ?? [];
898
+ const { bare, position } = splitImportant(className);
899
+ if (position) return this.cssPropsMap.get(bare) ?? [];
847
900
  return [];
848
901
  }
849
902
  getVariantPriority(variant) {
@@ -855,29 +908,186 @@ var DesignSystemCache = class DesignSystemCache {
855
908
  getNamedEquivalent(className) {
856
909
  const result = this.arbitraryEquivMap.get(className);
857
910
  if (result) return result;
858
- const { bare, important } = stripImportant$1(className);
859
- if (important) return this.arbitraryEquivMap.get(bare) ?? null;
911
+ const { bare, position } = splitImportant(className);
912
+ if (position) return this.arbitraryEquivMap.get(bare) ?? null;
860
913
  return null;
861
914
  }
862
915
  };
863
916
  //#endregion
917
+ //#region src/utils/fatal.ts
918
+ /**
919
+ * Fatal error types and reporter for the deterministic v1 design.
920
+ *
921
+ * The plugin used to silently skip when the design system could not be
922
+ * loaded or the worker thread misbehaved. v1 fails loud: every DS-dependent
923
+ * rule catches these errors and surfaces them as a single fatal lint
924
+ * diagnostic so the user sees exactly what to fix.
925
+ */
926
+ /**
927
+ * The single `messageId` every DS-dependent rule uses to surface a fatal
928
+ * design-system load failure. Exported as a constant so the rule's
929
+ * `meta.messages` and `context.report()` calls in `reportFatalDsError`
930
+ * cannot drift apart silently.
931
+ */
932
+ const DS_UNAVAILABLE_MESSAGE_ID = "designSystemUnavailable";
933
+ /** Pre-shaped entry for `meta.messages`. Spread it: `messages: { ..., ...DS_UNAVAILABLE_MESSAGE }`. */
934
+ const DS_UNAVAILABLE_MESSAGE = { [DS_UNAVAILABLE_MESSAGE_ID]: "{{message}}" };
935
+ var OxlintTailwindError = class extends Error {
936
+ /** A short, actionable hint shown alongside the error message. */
937
+ hint;
938
+ constructor(message, hint, options) {
939
+ super(message, options);
940
+ this.name = this.constructor.name;
941
+ this.hint = hint;
942
+ }
943
+ };
944
+ /** No `settings.tailwindcss.entryPoint` was provided and a DS-dependent rule needs one. */
945
+ var MissingEntryPointError = class extends OxlintTailwindError {};
946
+ /** `settings.tailwindcss.entryPoint` is an array of strings — removed in v1. */
947
+ var DeprecatedEntryPointShapeError = class extends OxlintTailwindError {};
948
+ /** `__unstable__loadDesignSystem` failed (bad CSS path, malformed CSS, install issue). */
949
+ var DesignSystemLoadError = class extends OxlintTailwindError {};
950
+ /** The sort or canonicalize worker thread failed to initialize or timed out. */
951
+ var SortServiceError = class extends OxlintTailwindError {};
952
+ /** Type-guard: did this error originate from the plugin's fail-loud infrastructure? */
953
+ function isFatalError(err) {
954
+ return err instanceof OxlintTailwindError;
955
+ }
956
+ /**
957
+ * Format a fatal error into the diagnostic message a rule should report.
958
+ *
959
+ * Pulls in the optional `hint` (a one-line "here's how to fix it" follow-up)
960
+ * so the message is self-contained even when the user is reading it in an
961
+ * editor without the docs site open.
962
+ */
963
+ function formatFatalError(err) {
964
+ return err.hint ? `${err.message}\n\nHint: ${err.hint}` : err.message;
965
+ }
966
+ /**
967
+ * Helper for DS-dependent rules to convert a caught fatal error into a
968
+ * single diagnostic. Returns `true` if the error was reported (and the
969
+ * visitor should bail out), `false` otherwise — the rule layer rethrows
970
+ * non-fatal errors to surface real bugs.
971
+ */
972
+ function reportFatalDsError(context, err, node) {
973
+ if (!isFatalError(err)) return false;
974
+ context.report({
975
+ node,
976
+ messageId: DS_UNAVAILABLE_MESSAGE_ID,
977
+ data: { message: formatFatalError(err) }
978
+ });
979
+ return true;
980
+ }
981
+ /**
982
+ * Call `getDS()` and route fatal errors through `reportFatalDsError`.
983
+ *
984
+ * Returns the load result on success, or `null` after a fatal error has been
985
+ * reported (rules should `if (!ds) return` and exit the visitor). Non-fatal
986
+ * errors are re-thrown so genuine bugs aren't hidden.
987
+ */
988
+ function safeGetDS(getDS, context, node) {
989
+ try {
990
+ return getDS();
991
+ } catch (err) {
992
+ if (reportFatalDsError(context, err, node)) return null;
993
+ throw err;
994
+ }
995
+ }
996
+ //#endregion
997
+ //#region src/design-system/tailwind-node.ts
998
+ /**
999
+ * Single source of truth for the resolved `@tailwindcss/node` entry path
1000
+ * and its installed version. Three call sites (sync-loader, sort-service,
1001
+ * canonicalize-service) used to each call `require.resolve` independently
1002
+ * — this module resolves once at load and exposes the results.
1003
+ *
1004
+ * The version is read from `dist/../package.json` (the published layout)
1005
+ * with a walk-up fallback for unconventional installs.
1006
+ */
1007
+ function resolveTailwindNodePath() {
1008
+ try {
1009
+ return require.resolve("@tailwindcss/node");
1010
+ } catch {
1011
+ return null;
1012
+ }
1013
+ }
1014
+ function readVersionFromEntry(entryPath) {
1015
+ let dir = (0, node_path.dirname)(entryPath);
1016
+ for (let i = 0; i < 5; i++) {
1017
+ const pkgJson = (0, node_path.join)(dir, "package.json");
1018
+ if ((0, node_fs.existsSync)(pkgJson)) try {
1019
+ const pkg = JSON.parse((0, node_fs.readFileSync)(pkgJson, "utf-8"));
1020
+ if (pkg.name === "@tailwindcss/node" && pkg.version) return pkg.version;
1021
+ } catch {}
1022
+ const parent = (0, node_path.dirname)(dir);
1023
+ if (parent === dir) break;
1024
+ dir = parent;
1025
+ }
1026
+ return "unknown";
1027
+ }
1028
+ const entryPath = resolveTailwindNodePath();
1029
+ /**
1030
+ * Absolute path to `@tailwindcss/node`'s main entry, or `null` if not
1031
+ * installed. Workers receive this path via workerData; the parent does
1032
+ * the resolution because module resolution from a child process's `eval`
1033
+ * context (with cwd inside a tmp dir or under pnpm strict workspaces) can
1034
+ * fail to find the bare specifier.
1035
+ */
1036
+ const TAILWIND_NODE_PATH = entryPath;
1037
+ /**
1038
+ * Installed `@tailwindcss/node` version, or `'unknown'`. Used as part of
1039
+ * the disk-cache key in sync-loader so cached precompute output is
1040
+ * invalidated when the consumer upgrades.
1041
+ */
1042
+ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPath) : "unknown";
1043
+ //#endregion
864
1044
  //#region src/design-system/sync-loader.ts
865
1045
  /**
866
- * Synchronous design system loader using execFileSync.
1046
+ * Synchronous design system loader using a worker_thread.
867
1047
  *
868
1048
  * The problem: __unstable__loadDesignSystem is async, but oxlint's createOnce is sync.
869
- * The solution: spawn a child process that loads the design system, pre-computes all
870
- * data we need, and returns it as JSON via stdout. This runs ONCE at plugin init time.
1049
+ * The solution: run the design-system load + precompute in a worker_thread that writes
1050
+ * the result JSON straight to the disk cache and signals completion over a
1051
+ * SharedArrayBuffer, while the main thread blocks on `Atomics.wait`. This runs ONCE per
1052
+ * unique CSS entry point at plugin init time.
1053
+ *
1054
+ * Why a worker_thread and not a forked child process (the pre-1.1 design): `execFileSync`
1055
+ * does `fork()` of the oxlint host (Rust + embedded Node). Under Linux overcommit
1056
+ * accounting on memory-constrained CI runners, forking a large-RSS process is rejected
1057
+ * with `spawnSync … ENOMEM` even though the child immediately `exec`s (#24). A
1058
+ * worker_thread creates a thread in-process — no address-space duplication — so it is
1059
+ * immune. This mirrors what `sort-service.ts` / `canonicalize-service.ts` already do.
871
1060
  *
872
1061
  * For arbitrary values (bg-[#123]) that aren't in the class list, we use heuristics.
873
1062
  */
874
1063
  const PRECOMPUTE_SCRIPT = `
875
- // Resolve @tailwindcss/node via an absolute path passed in by the parent
876
- // process — bare-specifier lookup from this child's cwd fails under pnpm
877
- // strict workspaces (the module lives under node_modules/.pnpm/... which
878
- // is not on the resolution path from the consumer's project root).
879
- const { __unstable__loadDesignSystem } = require(process.env.TAILWIND_NODE_PATH);
880
- const { readFileSync } = require('fs');
1064
+ // Runs as a worker_thread (NOT a forked child process). Inputs arrive via
1065
+ // workerData; the result is written straight to the disk cache and completion
1066
+ // is signaled over the SharedArrayBuffer's control[2] (0=loading, 1=done,
1067
+ // -1=error), mirroring sort-service.ts / canonicalize-service.ts.
1068
+ const { workerData } = require('worker_threads');
1069
+ const { tailwindNodePath, cssPath: WD_CSS_PATH, cachePath: WD_CACHE_PATH, tmpPath: WD_TMP_PATH, sharedBuffer } = workerData;
1070
+ const control = new Int32Array(sharedBuffer, 0, 4);
1071
+ // On failure, write the error message into the data region so the main thread
1072
+ // can surface the real cause instead of a bare "undefined".
1073
+ const errLengthView = new DataView(sharedBuffer, 16, 4);
1074
+ const errDataArea = new Uint8Array(sharedBuffer, 20);
1075
+ function signalError(e) {
1076
+ try {
1077
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown precompute error'), 'utf-8');
1078
+ const n = Math.min(msg.length, errDataArea.length);
1079
+ errDataArea.set(msg.subarray(0, n), 0);
1080
+ errLengthView.setUint32(0, n);
1081
+ } catch {}
1082
+ Atomics.store(control, 2, -1);
1083
+ Atomics.notify(control, 2);
1084
+ }
1085
+ // Resolve @tailwindcss/node via an absolute path passed in by the parent —
1086
+ // bare-specifier lookup from the worker's cwd fails under pnpm strict
1087
+ // workspaces (the module lives under node_modules/.pnpm/... which is not on the
1088
+ // resolution path from the consumer's project root).
1089
+ const { __unstable__loadDesignSystem } = require(tailwindNodePath);
1090
+ const { readFileSync, writeFileSync, renameSync } = require('fs');
881
1091
  const { dirname, resolve } = require('path');
882
1092
 
883
1093
  function resolveImport(specifier, baseDir) {
@@ -954,7 +1164,7 @@ function extractComponentClasses(cssPath, baseDir) {
954
1164
  }
955
1165
 
956
1166
  async function main() {
957
- const cssPath = process.env.TAILWIND_CSS_PATH;
1167
+ const cssPath = WD_CSS_PATH;
958
1168
  const css = readFileSync(cssPath, 'utf-8');
959
1169
  const base = dirname(cssPath);
960
1170
  const ds = await __unstable__loadDesignSystem(css, { base });
@@ -1232,9 +1442,15 @@ async function main() {
1232
1442
  }
1233
1443
  }
1234
1444
 
1235
- process.stdout.write(JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents }));
1445
+ const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents });
1446
+ // Atomic write: write to a unique temp path then rename, so a peer isolate
1447
+ // busy-waiting on the cache file never observes a half-written JSON.
1448
+ writeFileSync(WD_TMP_PATH, json);
1449
+ renameSync(WD_TMP_PATH, WD_CACHE_PATH);
1236
1450
  }
1237
- main().catch(e => { process.stderr.write(e.message); process.exit(1); });
1451
+ main()
1452
+ .then(() => { Atomics.store(control, 2, 1); Atomics.notify(control, 2); })
1453
+ .catch((e) => signalError(e));
1238
1454
  `;
1239
1455
  const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), "oxlint-tailwindcss");
1240
1456
  /**
@@ -1251,35 +1467,7 @@ const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), "oxlint-tailwindcss
1251
1467
  function computeCacheKey(scriptContent, tailwindVersion) {
1252
1468
  return `${(0, node_crypto.createHash)("md5").update(scriptContent).digest("hex").slice(0, 8)}:${tailwindVersion}`;
1253
1469
  }
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
- }
1470
+ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1283
1471
  function computeContentHash(content) {
1284
1472
  return (0, node_crypto.createHash)("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1285
1473
  }
@@ -1287,152 +1475,178 @@ function getContentCachePath(contentHash) {
1287
1475
  return (0, node_path.join)(CACHE_DIR, `${contentHash}.json`);
1288
1476
  }
1289
1477
  function tryReadCache(cachePath) {
1478
+ const raw = tryReadRawCache(cachePath);
1479
+ if (raw === null) return null;
1290
1480
  try {
1291
- return JSON.parse((0, node_fs.readFileSync)(cachePath, "utf-8"));
1481
+ return JSON.parse(raw);
1292
1482
  } catch {
1293
1483
  return null;
1294
1484
  }
1295
1485
  }
1296
- function writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, data) {
1486
+ function tryReadRawCache(cachePath) {
1297
1487
  try {
1298
- (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1299
- (0, node_fs.writeFileSync)(contentCachePath, data);
1300
- (0, node_fs.writeFileSync)(mtimeIndexPath, contentHash);
1301
- } catch {}
1488
+ return (0, node_fs.readFileSync)(cachePath, "utf-8");
1489
+ } catch {
1490
+ return null;
1491
+ }
1302
1492
  }
1303
- function loadDesignSystemSync(cssPath, timeout) {
1304
- const resolvedPath = (0, node_path.resolve)(cssPath);
1493
+ const LOCK_POLL_MS = 50;
1494
+ const SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
1495
+ function syncSleep(ms) {
1496
+ Atomics.wait(SLEEP_BUFFER, 0, 0, ms);
1497
+ }
1498
+ /** Age of the lock file in ms, or Infinity if it has already vanished. */
1499
+ function lockAgeMs(lockPath) {
1305
1500
  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], {
1324
- encoding: "utf-8",
1325
- timeout: timeout ?? 3e4,
1326
- maxBuffer: 50 * 1024 * 1024,
1327
- env: {
1328
- ...process.env,
1329
- TAILWIND_CSS_PATH: resolvedPath,
1330
- TAILWIND_NODE_PATH: tailwindNodePath
1331
- },
1332
- cwd: (0, node_path.dirname)(resolvedPath)
1333
- });
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;
1501
+ return Date.now() - (0, node_fs.statSync)(lockPath).mtimeMs;
1502
+ } catch {
1503
+ return Number.POSITIVE_INFINITY;
1341
1504
  }
1342
1505
  }
1343
- //#endregion
1344
- //#region src/design-system/auto-detect.ts
1345
- const IMPORT_RE = /@import\s+['"]([^'"]+)['"]/g;
1506
+ function tryUnlink(path) {
1507
+ try {
1508
+ (0, node_fs.unlinkSync)(path);
1509
+ } catch {}
1510
+ }
1511
+ /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1512
+ const PRECOMPUTE_SIGNAL_INDEX = 2;
1513
+ const ERR_BUFFER_SIZE = 64 * 1024;
1514
+ let precomputeSeq = 0;
1346
1515
  /**
1347
- * Resolves a CSS @import specifier to an absolute path.
1348
- * Handles relative paths and package imports (walks up to node_modules).
1516
+ * Choose the diagnostic hint based on the underlying error code. ENOMEM/EAGAIN
1517
+ * is memory pressure, not a CSS or timeout problem — the legacy hint pointed
1518
+ * users at the wrong levers (issue #24 / birdman CI report). Exported for tests.
1349
1519
  */
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;
1359
- }
1360
- return null;
1520
+ function precomputeHint(cause) {
1521
+ const code = cause?.code;
1522
+ const message = cause instanceof Error ? cause.message : "";
1523
+ if (code === "ENOMEM" || code === "EAGAIN" || message.includes("ENOMEM")) return "The host ran out of memory spawning the precompute worker. This is rare now that precompute runs in a worker thread; if it persists, lower oxlint concurrency (e.g. `--threads`) or give the machine/CI runner more memory.";
1524
+ return "Check the CSS file (and its imports) for syntax errors. If this looks like a timeout, raise `settings.tailwindcss.timeout`.";
1525
+ }
1526
+ function precomputeLoadError(resolvedPath, cause) {
1527
+ const causeError = cause instanceof Error ? cause : void 0;
1528
+ return new DesignSystemLoadError(`Failed to precompute design system from "${resolvedPath}": ${causeError?.message ?? String(cause)}`, precomputeHint(cause), { cause: causeError });
1361
1529
  }
1362
1530
  /**
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.
1531
+ * Run the precompute in a worker_thread (not a forked child). The worker loads
1532
+ * the design system in-process, writes the JSON straight to `cachePath`, and
1533
+ * signals completion over a SharedArrayBuffer; the main thread blocks on
1534
+ * `Atomics.wait`. Because worker_threads don't fork the host's address space,
1535
+ * this avoids the `spawnSync … ENOMEM` the fork-based path hit on
1536
+ * memory-constrained CI runners (#24).
1537
+ *
1538
+ * Throws `DesignSystemLoadError` on spawn failure, worker error, or timeout.
1539
+ * The worker writes the result itself, so this returns nothing — callers read
1540
+ * it back from `cachePath`.
1365
1541
  */
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;
1374
- 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;
1542
+ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout) {
1543
+ const sharedBuffer = new SharedArrayBuffer(ERR_BUFFER_SIZE);
1544
+ const control = new Int32Array(sharedBuffer, 0, 4);
1545
+ const errLengthView = new DataView(sharedBuffer, 16, 4);
1546
+ const errDataArea = new Uint8Array(sharedBuffer, 20);
1547
+ const tmpPath = `${cachePath}.tmp.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
1548
+ let worker;
1549
+ try {
1550
+ worker = new node_worker_threads.Worker(PRECOMPUTE_SCRIPT, {
1551
+ eval: true,
1552
+ workerData: {
1553
+ sharedBuffer,
1554
+ cssPath: resolvedPath,
1555
+ cachePath,
1556
+ tmpPath,
1557
+ tailwindNodePath
1558
+ }
1559
+ });
1560
+ } catch (cause) {
1561
+ throw precomputeLoadError(resolvedPath, cause);
1562
+ }
1563
+ let workerError;
1564
+ worker.on("error", (err) => {
1565
+ workerError = err;
1566
+ });
1567
+ try {
1568
+ if (Atomics.wait(control, PRECOMPUTE_SIGNAL_INDEX, 0, timeout) === "timed-out") throw new DesignSystemLoadError(`Timed out precomputing design system from "${resolvedPath}" after ${timeout}ms.`, "Raise `settings.tailwindcss.timeout` if your machine or CI runner is slow, or verify the CSS imports resolve.");
1569
+ if (control[PRECOMPUTE_SIGNAL_INDEX] === -1) {
1570
+ const len = errLengthView.getUint32(0);
1571
+ throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : workerError);
1379
1572
  }
1573
+ } finally {
1574
+ tryUnlink(tmpPath);
1575
+ worker.terminate();
1380
1576
  }
1381
- return false;
1382
1577
  }
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
1578
  /**
1413
- * Searches for the Tailwind CSS entry point by walking UP from the file
1414
- * being linted. Monorepo-aware: stops at package.json boundaries.
1579
+ * Run the precompute worker, then read back the JSON it wrote to `cachePath`.
1580
+ * Used by both the lock-winner path and the uncoordinated degrade path.
1415
1581
  */
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 {
1582
+ function precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout) {
1583
+ runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout);
1584
+ const raw = tryReadRawCache(cachePath);
1585
+ if (raw === null) throw new DesignSystemLoadError(`Precompute worker finished but wrote no cache file for "${resolvedPath}".`, "This usually means the system temp directory is not writable; check its permissions.");
1586
+ return raw;
1587
+ }
1588
+ /**
1589
+ * Return the raw precompute JSON for `contentHash`, spawning at most one
1590
+ * precompute worker across all isolates competing for the same hash. Whoever
1591
+ * wins the lock computes and writes the cache; the rest wait for that file.
1592
+ */
1593
+ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath, timeout) {
1594
+ const lockPath = (0, node_path.join)(CACHE_DIR, `${contentHash}.lock`);
1595
+ const staleMs = timeout + 3e4;
1596
+ try {
1597
+ (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1598
+ } catch {
1599
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1600
+ }
1601
+ const start = Date.now();
1602
+ for (;;) {
1603
+ const raw = tryReadRawCache(cachePath);
1604
+ if (raw !== null) return raw;
1605
+ let lockFd;
1606
+ try {
1607
+ lockFd = (0, node_fs.openSync)(lockPath, "wx");
1608
+ } catch (cause) {
1609
+ if (cause.code === "EEXIST") {
1610
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1611
+ else syncSleep(LOCK_POLL_MS);
1427
1612
  continue;
1428
1613
  }
1614
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1615
+ }
1616
+ try {
1617
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1618
+ } finally {
1619
+ (0, node_fs.closeSync)(lockFd);
1620
+ tryUnlink(lockPath);
1429
1621
  }
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;
1434
1622
  }
1435
- return null;
1623
+ }
1624
+ /**
1625
+ * Synchronously load and precompute the design system for a CSS file.
1626
+ *
1627
+ * Throws `DesignSystemLoadError` on any failure (missing file, worker
1628
+ * error, missing `@tailwindcss/node`, etc.). Callers catch via
1629
+ * `reportFatalDsError` to surface a single Program-level diagnostic.
1630
+ */
1631
+ function loadDesignSystemSync(cssPath, timeout) {
1632
+ const resolvedPath = (0, node_path.resolve)(cssPath);
1633
+ let content;
1634
+ try {
1635
+ content = (0, node_fs.readFileSync)(resolvedPath, "utf-8");
1636
+ } catch (cause) {
1637
+ 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 });
1638
+ }
1639
+ const contentHash = computeContentHash(content);
1640
+ const contentCachePath = getContentCachePath(contentHash);
1641
+ const cached = tryReadCache(contentCachePath);
1642
+ if (cached) return cached;
1643
+ 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.");
1644
+ const raw = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1645
+ try {
1646
+ return JSON.parse(raw);
1647
+ } catch (cause) {
1648
+ 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 });
1649
+ }
1436
1650
  }
1437
1651
  //#endregion
1438
1652
  //#region src/design-system/debug.ts
@@ -1463,48 +1677,154 @@ function debugLog(message) {
1463
1677
  if (_enabled || process.env.DEBUG === "oxlint-tailwindcss") console.error(`${PREFIX} ${message}`);
1464
1678
  }
1465
1679
  //#endregion
1680
+ //#region src/utils/context.ts
1681
+ /**
1682
+ * Safely read `context.options[0]`. Returns `undefined` if the getter throws
1683
+ * (oxlint < 1.31.0) or if options aren't populated yet.
1684
+ */
1685
+ function safeOptions(context) {
1686
+ try {
1687
+ return context.options?.[0] ?? void 0;
1688
+ } catch {
1689
+ return;
1690
+ }
1691
+ }
1692
+ /**
1693
+ * Safely read `context.settings`. Same try/catch pattern as `safeOptions`
1694
+ * for the createOnce-throws case.
1695
+ */
1696
+ function safeSettings(context) {
1697
+ try {
1698
+ return context.settings ?? void 0;
1699
+ } catch {
1700
+ return;
1701
+ }
1702
+ }
1703
+ /** Safely read `context.filename`. Same try/catch pattern. */
1704
+ function safeFilename(context) {
1705
+ try {
1706
+ return context.filename ?? void 0;
1707
+ } catch {
1708
+ return;
1709
+ }
1710
+ }
1711
+ /**
1712
+ * Lazily memoize a compiled options object across visitor calls.
1713
+ *
1714
+ * Every rule with options reinvents:
1715
+ *
1716
+ * let _x: CompiledOptions | null = null
1717
+ * function getX() {
1718
+ * if (_x === null) _x = compile(safeOptions<RawOptions>(context))
1719
+ * return _x
1720
+ * }
1721
+ *
1722
+ * This wraps the pattern: pass the context and a `compile` function (which
1723
+ * receives the raw options object — possibly undefined) and get a memoized
1724
+ * thunk back. Inside `createOnce`, options aren't available yet, so the first
1725
+ * visitor call triggers compilation; every subsequent call is O(1).
1726
+ */
1727
+ function createLazyOptions(context, compile) {
1728
+ let cached = null;
1729
+ return () => {
1730
+ if (cached) return cached.value;
1731
+ cached = { value: compile(safeOptions(context)) };
1732
+ return cached.value;
1733
+ };
1734
+ }
1735
+ //#endregion
1466
1736
  //#region src/design-system/loader.ts
1467
1737
  const dsCache = /* @__PURE__ */ new Map();
1468
- const autoDetectCache = /* @__PURE__ */ new Map();
1469
- let lastLoadedPath = null;
1470
1738
  /**
1471
- * Extracts `entryPoint` from `context.settings.tailwindcss`.
1472
- * Supports both `string` and `string[]` (for monorepos).
1739
+ * Memoizes DS-load FAILURES per entry point, keyed by `(resolvedPath, mtime)`.
1740
+ *
1741
+ * Without this, a single environmental failure (e.g. `spawnSync … ENOMEM` on a
1742
+ * constrained CI runner) was re-attempted on every AST node × every rule ×
1743
+ * every file — the storm that turned one failure into ~18k re-spawns and 21k
1744
+ * per-class errors (issue #24 / birdman report). Caching the failure collapses
1745
+ * it to one attempt per entry point per process. Keyed by mtime so fixing the
1746
+ * CSS (mtime changes) invalidates the entry and a fresh load is attempted.
1747
+ */
1748
+ const dsFailureCache = /* @__PURE__ */ new Map();
1749
+ function isEntryPointMapping(v) {
1750
+ if (typeof v !== "object" || v === null) return false;
1751
+ const m = v;
1752
+ return (typeof m.files === "string" || Array.isArray(m.files) && m.files.every((s) => typeof s === "string")) && typeof m.use === "string";
1753
+ }
1754
+ /**
1755
+ * Read `settings.tailwindcss.entryPoint` and normalize it to the v1 shape.
1756
+ *
1757
+ * Throws `DeprecatedEntryPointShapeError` if the legacy `string[]` shape is
1758
+ * still in use (removed in v1; the user must migrate to `{ files, use }[]`).
1473
1759
  */
1474
1760
  function entryPointFromSettings(settings) {
1475
1761
  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;
1762
+ if (!tw || typeof tw !== "object" || !("entryPoint" in tw)) return void 0;
1763
+ const ep = tw.entryPoint;
1764
+ if (typeof ep === "string") return ep;
1765
+ if (Array.isArray(ep)) {
1766
+ if (ep.length === 0) return void 0;
1767
+ 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");
1768
+ if (ep.every(isEntryPointMapping)) return ep;
1769
+ 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
1770
  }
1481
1771
  }
1482
1772
  /**
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.
1773
+ * Compile a minimal glob pattern to a regular expression.
1774
+ *
1775
+ * Supported syntax: `**` (any depth), `*` (any chars except `/`), `?` (one
1776
+ * char except `/`), plus literal segments. Anchored on both ends.
1777
+ *
1778
+ * Memoized across calls because `resolveByGlobMapping` runs per lint visit;
1779
+ * recompiling the same pattern per AST node would be wasted work.
1485
1780
  */
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;
1781
+ const globRegexCache = /* @__PURE__ */ new Map();
1782
+ function globToRegExp(glob) {
1783
+ const cached = globRegexCache.get(glob);
1784
+ if (cached) return cached;
1785
+ let re = "";
1786
+ let i = 0;
1787
+ while (i < glob.length) {
1788
+ const c = glob[i];
1789
+ if (c === "*" && glob[i + 1] === "*") {
1790
+ re += ".*";
1791
+ i += 2;
1792
+ if (glob[i] === "/") i++;
1793
+ } else if (c === "*") {
1794
+ re += "[^/]*";
1795
+ i++;
1796
+ } else if (c === "?") {
1797
+ re += "[^/]";
1798
+ i++;
1799
+ } else if ("+()|.\\$^{}[]".includes(c)) {
1800
+ re += "\\" + c;
1801
+ i++;
1802
+ } else {
1803
+ re += c;
1804
+ i++;
1496
1805
  }
1497
1806
  }
1498
- return best;
1807
+ const compiled = new RegExp("^" + re + "$");
1808
+ globRegexCache.set(glob, compiled);
1809
+ return compiled;
1499
1810
  }
1500
- function commonPrefixLength(a, b) {
1501
- const len = Math.min(a.length, b.length);
1502
- let i = 0;
1503
- while (i < len && a[i] === b[i]) i++;
1504
- return i;
1811
+ function matchesAnyGlob(filePath, globs) {
1812
+ return (typeof globs === "string" ? [globs] : globs).some((g) => globToRegExp(g).test(filePath));
1813
+ }
1814
+ /**
1815
+ * Resolve a file path to its entry-point CSS via a mapping array.
1816
+ * First-match-wins. Paths are matched relative to `baseDir` (typically the
1817
+ * process CWD where oxlint runs), with forward-slash normalization for
1818
+ * cross-platform consistency. Returns the absolute CSS path, or `null` if
1819
+ * no mapping matches.
1820
+ */
1821
+ function resolveByGlobMapping(mappings, filePath, baseDir) {
1822
+ const relPath = (0, node_path.relative)(baseDir, (0, node_path.resolve)(filePath)).split("\\").join("/");
1823
+ for (const m of mappings) if (matchesAnyGlob(relPath, m.files)) return (0, node_path.resolve)(baseDir, m.use);
1824
+ return null;
1505
1825
  }
1506
1826
  /**
1507
- * Extracts `rootFontSize` from `context.settings.tailwindcss` (default: 16).
1827
+ * Extract `rootFontSize` from `settings.tailwindcss` (default: 16).
1508
1828
  */
1509
1829
  function rootFontSizeFromSettings(settings) {
1510
1830
  const tw = settings?.tailwindcss;
@@ -1514,9 +1834,6 @@ function rootFontSizeFromSettings(settings) {
1514
1834
  }
1515
1835
  return 16;
1516
1836
  }
1517
- /**
1518
- * Extracts `timeout` from `context.settings.tailwindcss`.
1519
- */
1520
1837
  function timeoutFromSettings(settings) {
1521
1838
  const tw = settings?.tailwindcss;
1522
1839
  if (tw && typeof tw === "object" && "timeout" in tw) {
@@ -1525,183 +1842,178 @@ function timeoutFromSettings(settings) {
1525
1842
  }
1526
1843
  }
1527
1844
  /**
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.
1845
+ * Load the design system for a specific CSS entry point.
1545
1846
  *
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).
1847
+ * Throws `DesignSystemLoadError` if the load fails for any reason. Callers
1848
+ * (rules via `createLazyLoader`) catch via `reportFatalDsError` and surface
1849
+ * the failure as a single Program-level diagnostic.
1551
1850
  *
1552
- * `autoDetect` is injected for testability; in production it's
1553
- * `cachedAutoDetect`. Pure: does not touch module state.
1851
+ * Cached per absolute entry-point path, keyed by mtime. In monorepos each
1852
+ * unique CSS gets its own cache entry.
1554
1853
  */
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
1854
+ function getLoadedDesignSystem(cssPath, settings) {
1855
+ const resolvedPath = (0, node_path.resolve)(cssPath);
1856
+ let mtime;
1857
+ try {
1858
+ mtime = (0, node_fs.statSync)(resolvedPath).mtimeMs;
1859
+ } catch (cause) {
1860
+ 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 });
1861
+ }
1862
+ const cached = dsCache.get(resolvedPath);
1863
+ if (cached && cached.mtime === mtime) return {
1864
+ cache: cached.cache,
1865
+ entryPoint: resolvedPath
1566
1866
  };
1867
+ const failed = dsFailureCache.get(resolvedPath);
1868
+ if (failed && failed.mtime === mtime) throw failed.error;
1869
+ let data;
1870
+ try {
1871
+ data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1872
+ } catch (err) {
1873
+ if (isFatalError(err)) dsFailureCache.set(resolvedPath, {
1874
+ error: err,
1875
+ mtime
1876
+ });
1877
+ throw err;
1878
+ }
1879
+ const cache = DesignSystemCache.fromPrecomputed(data);
1880
+ dsCache.set(resolvedPath, {
1881
+ cache,
1882
+ mtime
1883
+ });
1884
+ debugLog(`Loaded design system from "${resolvedPath}"`);
1567
1885
  return {
1568
- path: lastPath ?? null,
1569
- isExplicit: false
1886
+ cache,
1887
+ entryPoint: resolvedPath
1570
1888
  };
1571
1889
  }
1572
1890
  /**
1573
- * Returns the design system cache, loading synchronously on first call.
1574
- * Uses execFileSync internally to bridge the async Tailwind API.
1891
+ * Lazy DS loader for a rule. Resolves the correct design system for each
1892
+ * file being linted, using (in priority order):
1893
+ *
1894
+ * 1. Rule option `entryPoint` (a string path).
1895
+ * 2. `settings.tailwindcss.entryPoint` as a string.
1896
+ * 3. `settings.tailwindcss.entryPoint` as an `EntryPointMapping[]` —
1897
+ * first matching glob (relative to CWD) wins.
1575
1898
  *
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.
1899
+ * If none of those produce an entry point for the current file, throws
1900
+ * `MissingEntryPointError`. If the resolved CSS fails to load, throws
1901
+ * `DesignSystemLoadError`. Both extend `OxlintTailwindError` and are
1902
+ * meant to be caught by `reportFatalDsError` in the rule's `check()`.
1579
1903
  *
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.
1621
- *
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.
1625
- *
1626
- * When a fixed entryPoint is provided (rule option or settings), it's used for all
1627
- * files and cached after first resolution.
1904
+ * `context.settings` and `context.filename` are unavailable in `createOnce`,
1905
+ * so the actual work is deferred until the returned thunk is invoked from
1906
+ * inside a visitor.
1628
1907
  */
1629
1908
  function createLazyLoader(context) {
1630
- let lastFilePath;
1631
- let lastResult = null;
1632
- let fixedEntryResolved = false;
1633
- let fixedResult = null;
1634
1909
  let debugInitialized = false;
1910
+ let lastFilePath;
1911
+ let lastResult;
1912
+ let lastError;
1635
1913
  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 {}
1914
+ const filePath = safeFilename(context);
1915
+ if (filePath !== void 0 && filePath === lastFilePath) {
1916
+ if (lastError) throw lastError;
1917
+ if (lastResult) return lastResult;
1918
+ }
1919
+ const ruleOptionEntry = safeOptions(context)?.entryPoint;
1920
+ const settings = safeSettings(context);
1648
1921
  if (!debugInitialized && settings) {
1649
1922
  debugInitialized = true;
1650
1923
  setDebugEnabled(isDebugEnabled(settings));
1651
1924
  }
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;
1925
+ lastFilePath = filePath;
1926
+ lastResult = void 0;
1927
+ lastError = void 0;
1928
+ try {
1929
+ lastResult = getLoadedDesignSystem(resolveEntryPointForFile(ruleOptionEntry, entryPointFromSettings(settings), filePath), settings);
1930
+ } catch (err) {
1931
+ if (isFatalError(err) && err instanceof Error) lastError = err;
1932
+ throw err;
1668
1933
  }
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)}`);
1934
+ if (filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), lastResult.entryPoint)}`);
1673
1935
  return lastResult;
1674
1936
  };
1675
1937
  }
1676
- //#endregion
1677
- //#region src/types.ts
1678
1938
  /**
1679
- * Safely read context.options.
1680
- *
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.
1939
+ * Pure resolution from (rule option, settings entry, file path) to a CSS
1940
+ * entry-point path. Exported for testability.
1684
1941
  *
1685
- * In oxlint <1.31.0 the getter may throw — the try/catch handles that.
1942
+ * Throws `MissingEntryPointError` if nothing resolves. The error message
1943
+ * names the file so the user knows which one tripped the configuration.
1686
1944
  */
1687
- function safeOptions(context) {
1688
- try {
1689
- return context.options?.[0] ?? void 0;
1690
- } catch {
1691
- return;
1945
+ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath) {
1946
+ if (ruleOptionEntry) return ruleOptionEntry;
1947
+ if (typeof settingsEntry === "string") return settingsEntry;
1948
+ if (Array.isArray(settingsEntry)) {
1949
+ 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.");
1950
+ const matched = resolveByGlobMapping(settingsEntry, filePath, process.cwd());
1951
+ if (matched) return matched;
1952
+ throw new MissingEntryPointError(`No \`entryPoint\` mapping matched \`${filePath}\`.`, "Add a mapping covering this file to `settings.tailwindcss.entryPoint`, or use a `\"**\"` fallback entry.");
1692
1953
  }
1954
+ 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
1955
  }
1956
+ //#endregion
1957
+ //#region src/utils/report.ts
1694
1958
  /**
1695
- * Safely read context.settings.
1959
+ * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
1960
+ *
1961
+ * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
1962
+ * enforce-consistent-variable-syntax, enforce-consistent-important-position,
1963
+ * enforce-negative-arbitrary-values, no-deprecated-classes,
1964
+ * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
1965
+ * replacements via the same shape:
1966
+ *
1967
+ * 1. Collect `{ cls, replacement }` entries from a class string.
1968
+ * 2. Rebuild the full class string with replacements applied.
1969
+ * 3. Emit ONE diagnostic with the autofix attached.
1970
+ * 4. Emit one MORE diagnostic per remaining offender, each carrying
1971
+ * the same autofix as a `suggest`.
1696
1972
  *
1697
- * Like `safeOptions`, `context.settings` may not be accessible in `createOnce()`.
1698
- * The try/catch handles that gracefully.
1973
+ * oxlint's fixer is single-shot per AST node, so multiple offenders in the
1974
+ * same class string can only get one mechanical fix; the rest stay as
1975
+ * suggestions the IDE can offer interactively.
1699
1976
  */
1700
- function safeSettings(context) {
1701
- try {
1702
- return context.settings ?? void 0;
1703
- } catch {
1704
- return;
1977
+ /**
1978
+ * Emit autofix + suggestion diagnostics for a list of class replacements.
1979
+ *
1980
+ * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
1981
+ * across all diagnostics — the first one is the primary fix, the rest carry
1982
+ * the same fix as a suggestion (oxlint can only apply one autofix per node).
1983
+ */
1984
+ function reportClassReplacements(context, loc, split, classes, offending, options) {
1985
+ if (offending.length === 0) return;
1986
+ const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
1987
+ const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
1988
+ const replacementKey = options.replacementKey ?? "replacement";
1989
+ const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
1990
+ const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1991
+ const report = context.report;
1992
+ for (let i = 0; i < offending.length; i++) {
1993
+ const { cls, replacement } = offending[i];
1994
+ const primaryData = {
1995
+ className: cls,
1996
+ [replacementKey]: replacement
1997
+ };
1998
+ if (i === 0) report({
1999
+ node: loc.node,
2000
+ messageId: options.messageId,
2001
+ data: primaryData,
2002
+ fix: applyFix
2003
+ });
2004
+ else report({
2005
+ node: loc.node,
2006
+ messageId: options.messageId,
2007
+ data: primaryData,
2008
+ suggest: [{
2009
+ messageId: suggestMessageId,
2010
+ data: {
2011
+ className: cls,
2012
+ replacement
2013
+ },
2014
+ fix: applyFix
2015
+ }]
2016
+ });
1705
2017
  }
1706
2018
  }
1707
2019
  //#endregion
@@ -1734,71 +2046,30 @@ const noDeprecatedClasses = (0, _oxlint_plugins.defineRule)({
1734
2046
  additionalProperties: false
1735
2047
  }],
1736
2048
  hasSuggestions: true,
2049
+ defaultOptions: [{}],
1737
2050
  messages: {
1738
2051
  deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
1739
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2052
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2053
+ ...DS_UNAVAILABLE_MESSAGE
1740
2054
  }
1741
2055
  },
1742
2056
  createOnce(context) {
1743
2057
  const getDS = createLazyLoader(context);
1744
2058
  function check(locations) {
1745
- const dsResult = getDS();
2059
+ if (locations.length === 0) return;
2060
+ if (!safeGetDS(getDS, context, locations[0].node)) return;
1746
2061
  for (const loc of locations) {
1747
2062
  const split = splitClassesWithSeparators(loc.value);
1748
- const classes = split.classes;
1749
- const offending = [];
1750
- for (const cls of classes) {
2063
+ const offending = split.classes.flatMap((cls) => {
1751
2064
  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;
2065
+ const { bare: bareUtility, position } = splitImportant(utility);
1755
2066
  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({
2067
+ return replacement ? [{
1763
2068
  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
- }
2069
+ replacement: variant + reattachImportant(replacement, position)
2070
+ }] : [];
2071
+ });
2072
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
1802
2073
  }
1803
2074
  }
1804
2075
  return createExtractorVisitors(context, check);
@@ -1833,37 +2104,27 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
1833
2104
  messages: {
1834
2105
  unknown: "\"{{className}}\" is not a valid Tailwind class.",
1835
2106
  unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
1836
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2107
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2108
+ ...DS_UNAVAILABLE_MESSAGE
1837
2109
  }
1838
2110
  },
1839
2111
  createOnce(context) {
1840
2112
  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
- }
2113
+ const getLazyOptions = createLazyOptions(context, (o) => ({
2114
+ allowlist: new Set(o?.allowlist ?? []),
2115
+ ignorePrefixes: o?.ignorePrefixes ?? []
2116
+ }));
1854
2117
  function shouldIgnore(className) {
1855
2118
  const { allowlist, ignorePrefixes } = getLazyOptions();
1856
2119
  if (allowlist.has(className)) return true;
1857
2120
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
1858
2121
  }
1859
2122
  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;
2123
+ return splitImportant(className).bare;
1864
2124
  }
1865
2125
  function check(locations) {
1866
- const ds = getDS();
2126
+ if (locations.length === 0) return;
2127
+ const ds = safeGetDS(getDS, context, locations[0].node);
1867
2128
  if (!ds) return;
1868
2129
  const { cache } = ds;
1869
2130
  for (const loc of locations) {
@@ -1907,29 +2168,73 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
1907
2168
  }
1908
2169
  });
1909
2170
  //#endregion
1910
- //#region src/rules/no-conflicting-classes.ts
2171
+ //#region src/rules/no-conflicting-classes/spec.ts
1911
2172
  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(?:-|$)/
2173
+ {
2174
+ pattern: /^(from|via|to)-/,
2175
+ reason: "Gradient stops (`from-*`, `via-*`, `to-*`) share `--tw-gradient-stops`; different prefixes compose, same prefix conflicts."
2176
+ },
2177
+ {
2178
+ pattern: /^(transition|duration|ease|delay)(?:-|$)/,
2179
+ reason: "`transition-*` composes with `duration-*`, `ease-*`, `delay-*` — `transition-all` itself has no `--tw-*` vars so the heuristic misses it."
2180
+ },
2181
+ {
2182
+ pattern: /^-?(translate|scale|rotate|skew)-/,
2183
+ reason: "Transform axes (translate / scale / rotate / skew) compose into a single `transform`; the overlap is not captured in `cssProps`."
2184
+ },
2185
+ {
2186
+ pattern: /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
2187
+ reason: "Mask gradients: different families (e.g. `mask-linear-*` vs `mask-radial-*`) or roles (`from`/`via`/`to`/`at`) compose; same family+role conflicts."
2188
+ },
2189
+ {
2190
+ pattern: /^prose(?:-|$)/,
2191
+ reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
2192
+ }
1917
2193
  ];
1918
2194
  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])-/]
2195
+ {
2196
+ a: /^text-/,
2197
+ b: /^leading-/,
2198
+ reason: "`text-*` sets line-height via its size token; `leading-*` overrides it."
2199
+ },
2200
+ {
2201
+ a: /^text-/,
2202
+ b: /^tracking-/,
2203
+ reason: "`text-*` may set letter-spacing via its size token; `tracking-*` overrides it."
2204
+ },
2205
+ {
2206
+ a: /^border(?:-[0-9]|$)/,
2207
+ b: /^border-(?:solid|dashed|dotted|double|hidden|none)$/,
2208
+ reason: "`border-*` (width) composes with `border-{solid,dashed,…}` (style)."
2209
+ },
2210
+ {
2211
+ a: /^divide-/,
2212
+ b: /^border(?:-[trblxyse])?-/,
2213
+ reason: "`divide-*` styles direct children; `border-*` styles the element itself."
2214
+ },
2215
+ {
2216
+ a: /^prose(?:-|$)/,
2217
+ b: /^max-w-/,
2218
+ reason: "`prose` sets a default max-width; `max-w-*` overrides it."
2219
+ },
2220
+ {
2221
+ a: /^animate-in$/,
2222
+ b: /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/,
2223
+ reason: "`animate-in` initializes all `--tw-enter-*` vars; `*-in` modifiers each override one. (`tailwindcss-animate` / `tw-animate-css`.)"
2224
+ },
2225
+ {
2226
+ a: /^animate-out$/,
2227
+ b: /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/,
2228
+ reason: "`animate-out` initializes all `--tw-exit-*` vars; `*-out` modifiers each override one."
2229
+ },
2230
+ {
2231
+ a: /^mask-(?:add|subtract|intersect|exclude)$/,
2232
+ b: /^-?mask-(?:linear|radial|conic|[trblxy])-/,
2233
+ reason: "`mask-{add,subtract,intersect,exclude}` are mask-composite modes that compose with mask-gradient utilities."
2234
+ }
1927
2235
  ];
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
- }
2236
+ //#endregion
2237
+ //#region src/rules/no-conflicting-classes.ts
1933
2238
  /**
1934
2239
  * Two utilities compose via CSS custom properties if both define their own
1935
2240
  * --tw-* properties that don't overlap — they each contribute to a shared
@@ -1962,18 +2267,21 @@ function isNarrowingOverride(propsEarlier, propsLater) {
1962
2267
  function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
1963
2268
  if (isCompositionViaCssVars(propsA, propsB)) return true;
1964
2269
  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) {
2270
+ const ua = splitImportant(extractUtility(a)).bare;
2271
+ const ub = splitImportant(extractUtility(b)).bare;
2272
+ const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
2273
+ for (const { pattern: re } of groups) {
1969
2274
  const ma = ua.match(re);
1970
2275
  const mb = ub.match(re);
1971
2276
  if (!ma || !mb) continue;
1972
2277
  if (ma[1] === void 0) return true;
1973
2278
  if (ma[1] !== mb[1]) return true;
1974
2279
  }
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;
2280
+ const pairs = rules.compositionPairs !== void 0 ? rules.compositionPairs.map(([a, b]) => ({
2281
+ a,
2282
+ b
2283
+ })) : COMPOSITION_PAIRS;
2284
+ for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
1977
2285
  return false;
1978
2286
  }
1979
2287
  const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
@@ -1985,12 +2293,17 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
1985
2293
  properties: { entryPoint: { type: "string" } },
1986
2294
  additionalProperties: false
1987
2295
  }],
1988
- messages: { conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later)." }
2296
+ defaultOptions: [{}],
2297
+ messages: {
2298
+ conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2299
+ ...DS_UNAVAILABLE_MESSAGE
2300
+ }
1989
2301
  },
1990
2302
  createOnce(context) {
1991
2303
  const getDS = createLazyLoader(context);
1992
2304
  function check(locations) {
1993
- const ds = getDS();
2305
+ if (locations.length === 0) return;
2306
+ const ds = safeGetDS(getDS, context, locations[0].node);
1994
2307
  if (!ds) return;
1995
2308
  const { cache } = ds;
1996
2309
  for (const loc of locations) {
@@ -2007,7 +2320,7 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2007
2320
  if (variantClasses.length < 2) continue;
2008
2321
  const propsMap = /* @__PURE__ */ new Map();
2009
2322
  for (const cls of variantClasses) {
2010
- const props = cache.getCssProperties(stripImportant(extractUtility(cls)));
2323
+ const props = cache.getCssProperties(splitImportant(extractUtility(cls)).bare);
2011
2324
  propsMap.set(cls, props);
2012
2325
  }
2013
2326
  for (let i = 0; i < variantClasses.length; i++) {
@@ -2040,42 +2353,168 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
2040
2353
  }
2041
2354
  });
2042
2355
  //#endregion
2043
- //#region src/design-system/canonicalize-service.ts
2356
+ //#region src/design-system/ds-worker.ts
2044
2357
  /**
2045
- * Persistent canonicalize service using worker_threads + SharedArrayBuffer.
2046
- *
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().
2358
+ * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
2050
2359
  *
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.
2360
+ * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
2361
+ * (~500 LOC) — both spawned a worker that loaded the design system, then served
2362
+ * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
2363
+ * real difference was the body of the request loop: `getClassOrder` vs
2364
+ * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
2365
+ * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
2366
+ * service shrinks to ~40 LOC of singleton + public signature.
2053
2367
  *
2054
- * ## Per-class cache (process-wide)
2368
+ * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
2369
+ * of the process (per cssPath) so subsequent calls don't pay another
2370
+ * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
2371
+ * single `designSystemUnavailable` diagnostic.
2372
+ */
2373
+ const BUFFER_SIZE = 4 * 1024 * 1024;
2374
+ const HEADER_INTS = 4;
2375
+ const DATA_OFFSET = 20;
2376
+ const INIT_TIMEOUT = 6e4;
2377
+ const REQUEST_TIMEOUT = 3e4;
2378
+ var DesignSystemWorker = class {
2379
+ opts;
2380
+ ready = null;
2381
+ lastError = null;
2382
+ constructor(opts) {
2383
+ this.opts = opts;
2384
+ }
2385
+ /**
2386
+ * Ensure the worker is running and pointed at `cssPath`. Returns the
2387
+ * ready state. Throws `SortServiceError` on any failure (init timeout,
2388
+ * spawn error, DS-load error). Sticky: subsequent calls for the same
2389
+ * cssPath rethrow without retrying.
2390
+ */
2391
+ ensure(cssPath) {
2392
+ if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2393
+ if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2394
+ if (this.ready) this.cleanup();
2395
+ this.lastError = null;
2396
+ if (TAILWIND_NODE_PATH === null) {
2397
+ 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.");
2398
+ throw this.lastError;
2399
+ }
2400
+ const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2401
+ const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2402
+ const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2403
+ const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2404
+ let worker;
2405
+ try {
2406
+ worker = new node_worker_threads.Worker(this.opts.workerScript, {
2407
+ eval: true,
2408
+ workerData: {
2409
+ sharedBuffer,
2410
+ cssPath,
2411
+ tailwindNodePath: TAILWIND_NODE_PATH
2412
+ }
2413
+ });
2414
+ } catch (cause) {
2415
+ 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 });
2416
+ throw this.lastError;
2417
+ }
2418
+ worker.unref();
2419
+ worker.on("error", (err) => {
2420
+ 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 });
2421
+ });
2422
+ if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2423
+ 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.");
2424
+ this.terminateWorker(worker);
2425
+ throw this.lastError;
2426
+ }
2427
+ if (controlArray[2] === -1) {
2428
+ 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.");
2429
+ this.terminateWorker(worker);
2430
+ throw this.lastError;
2431
+ }
2432
+ this.ready = {
2433
+ worker,
2434
+ controlArray,
2435
+ lengthView,
2436
+ dataArea,
2437
+ cssPath
2438
+ };
2439
+ return this.ready;
2440
+ }
2441
+ /**
2442
+ * Send a request to the worker and synchronously wait for the response.
2443
+ * Throws `SortServiceError` on any failure.
2444
+ */
2445
+ callSync(cssPath, req) {
2446
+ const state = this.ensure(cssPath);
2447
+ const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
2448
+ 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.");
2449
+ state.dataArea.set(requestBytes, 0);
2450
+ state.lengthView.setUint32(0, requestBytes.length);
2451
+ Atomics.store(state.controlArray, 0, 1);
2452
+ Atomics.notify(state.controlArray, 0);
2453
+ if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2454
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow.");
2455
+ this.cleanup();
2456
+ throw this.lastError;
2457
+ }
2458
+ const responseLen = state.lengthView.getUint32(0);
2459
+ const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
2460
+ Atomics.store(state.controlArray, 1, 0);
2461
+ let parsed;
2462
+ try {
2463
+ parsed = JSON.parse(responseStr);
2464
+ } catch (cause) {
2465
+ 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 });
2466
+ this.cleanup();
2467
+ throw this.lastError;
2468
+ }
2469
+ if (parsed === null) {
2470
+ 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.");
2471
+ this.cleanup();
2472
+ throw this.lastError;
2473
+ }
2474
+ return parsed;
2475
+ }
2476
+ reset() {
2477
+ this.cleanup();
2478
+ this.lastError = null;
2479
+ }
2480
+ cleanup() {
2481
+ if (this.ready) {
2482
+ this.terminateWorker(this.ready.worker);
2483
+ this.ready = null;
2484
+ }
2485
+ }
2486
+ terminateWorker(worker) {
2487
+ try {
2488
+ worker.terminate();
2489
+ } catch {}
2490
+ }
2491
+ };
2492
+ //#endregion
2493
+ //#region src/design-system/canonicalize-service.ts
2494
+ /**
2495
+ * Persistent canonicalize service backed by `DesignSystemWorker`.
2055
2496
  *
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).
2497
+ * Calls `ds.canonicalizeCandidates([cls], { rem })` one class at a time
2498
+ * (the design system deduplicates its input, so batching changes the
2499
+ * result shape — see sync-loader.ts). The shared protocol lives in
2500
+ * `./ds-worker.ts`.
2059
2501
  *
2060
- * ## Per-class worker calls
2502
+ * ## Per-class cache (process-wide)
2061
2503
  *
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.
2504
+ * Results are cached by `${cssPath}\0${rem}\0${class}`. The worker is
2505
+ * invoked only for cache misses. In practice the cache converges quickly —
2506
+ * after the first few files any given class has been seen, and every
2507
+ * subsequent lookup is O(1).
2065
2508
  */
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 = `
2509
+ const canonWorker = new DesignSystemWorker({
2510
+ workerScript: `
2072
2511
  const { workerData } = require('worker_threads');
2073
2512
 
2074
2513
  async function main() {
2075
2514
  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});
2515
+ const control = new Int32Array(sharedBuffer, 0, 4);
2516
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2517
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2079
2518
 
2080
2519
  let ds;
2081
2520
  try {
@@ -2090,14 +2529,11 @@ async function main() {
2090
2529
  return;
2091
2530
  }
2092
2531
 
2093
- // Signal ready
2094
2532
  Atomics.store(control, 2, 1);
2095
2533
  Atomics.notify(control, 2);
2096
2534
 
2097
- // Request loop
2098
2535
  while (true) {
2099
2536
  Atomics.wait(control, 0, 0);
2100
-
2101
2537
  const len = lengthView.getUint32(0);
2102
2538
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2103
2539
  Atomics.store(control, 0, 0);
@@ -2119,117 +2555,32 @@ async function main() {
2119
2555
 
2120
2556
  dataArea.set(response, 0);
2121
2557
  lengthView.setUint32(0, response.length);
2122
-
2123
2558
  Atomics.store(control, 1, 1);
2124
2559
  Atomics.notify(control, 1);
2125
2560
  }
2126
2561
  }
2127
2562
  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
- }
2563
+ `,
2564
+ serviceName: "canonicalize"
2565
+ });
2191
2566
  /**
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.
2567
+ * Process-wide cache of canonicalized classes.
2568
+ * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
2569
+ * DSs) and different rem settings. Value: canonicalized class string.
2195
2570
  */
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
- }
2571
+ const canonCache = /* @__PURE__ */ new Map();
2223
2572
  /**
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.
2573
+ * Canonicalize classes via the worker thread.
2574
+ *
2575
+ * Throws `SortServiceError` on any worker failure (init timeout, request
2576
+ * timeout, worker crash). Callers should wrap via `safeGetDS` so the
2577
+ * failure surfaces as a single `designSystemUnavailable` diagnostic.
2227
2578
  *
2228
- * Uses a process-wide per-class cache: the worker is invoked only for classes
2579
+ * Returns an array the same length and order as `classes`. Uses a
2580
+ * process-wide per-class cache: the worker is invoked only for classes
2229
2581
  * not already seen with this (cssPath, rem) combination.
2230
2582
  */
2231
2583
  function canonicalizeClassesSync(cssPath, classes, rem) {
2232
- if (!ensureService$1(cssPath)) return null;
2233
2584
  const out = Array.from({ length: classes.length });
2234
2585
  const missingIdx = [];
2235
2586
  const missing = [];
@@ -2245,8 +2596,11 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2245
2596
  }
2246
2597
  if (missing.length === 0) return out;
2247
2598
  const uniqueMissing = [...new Set(missing)];
2248
- const fresh = callWorker(uniqueMissing, rem);
2249
- if (!fresh || fresh.length !== uniqueMissing.length) return null;
2599
+ const fresh = canonWorker.callSync(cssPath, {
2600
+ classes: uniqueMissing,
2601
+ rem
2602
+ });
2603
+ 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
2604
  const freshByClass = /* @__PURE__ */ new Map();
2251
2605
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2252
2606
  for (let j = 0; j < missing.length; j++) {
@@ -2260,20 +2614,20 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2260
2614
  //#endregion
2261
2615
  //#region src/rules/enforce-canonical.ts
2262
2616
  /**
2263
- * Preserve the user's ! position after canonicalization.
2264
- * canonicalizeCandidates always normalizes ! to suffix, but
2265
- * enforce-consistent-important-position handles that separately.
2617
+ * Preserve the user's `!` position after canonicalization.
2618
+ *
2619
+ * `canonicalizeCandidates` normalizes `!` to suffix; this restores the
2620
+ * original prefix-or-suffix-or-none position so `enforce-consistent-important-position`
2621
+ * remains the single source of truth for ! placement policy.
2622
+ *
2623
+ * Bracket-aware via `splitUtilityAndVariant` — arbitrary variants like
2624
+ * `[&>svg]:!w-4` round-trip correctly.
2266
2625
  */
2267
2626
  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 + "!";
2627
+ const { position } = splitImportant(splitUtilityAndVariant(original).utility);
2628
+ const { utility, variant } = splitUtilityAndVariant(canonicalized);
2629
+ const bare = splitImportant(utility).bare;
2630
+ return variant + reattachImportant(bare, position);
2277
2631
  }
2278
2632
  const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2279
2633
  meta: {
@@ -2286,9 +2640,11 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2286
2640
  additionalProperties: false
2287
2641
  }],
2288
2642
  hasSuggestions: true,
2643
+ defaultOptions: [{}],
2289
2644
  messages: {
2290
2645
  nonCanonical: "\"{{className}}\" can be written as \"{{canonical}}\". Use the canonical form.",
2291
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2646
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2647
+ ...DS_UNAVAILABLE_MESSAGE
2292
2648
  }
2293
2649
  },
2294
2650
  createOnce(context) {
@@ -2299,7 +2655,8 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2299
2655
  return _rem;
2300
2656
  }
2301
2657
  function check(locations) {
2302
- const ds = getDS();
2658
+ if (locations.length === 0) return;
2659
+ const ds = safeGetDS(getDS, context, locations[0].node);
2303
2660
  if (!ds) return;
2304
2661
  const { cache, entryPoint } = ds;
2305
2662
  for (const loc of locations) {
@@ -2313,51 +2670,18 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2313
2670
  arbitrary.push(classes[i]);
2314
2671
  } else canonicals[i] = cache.canonicalize(classes[i]);
2315
2672
  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
- }
2673
+ const rem = getRem();
2674
+ const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
2675
+ if (!dynamic) return;
2676
+ for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
2360
2677
  }
2678
+ reportClassReplacements(context, loc, split, classes, classes.flatMap((cls, i) => canonicals[i] === cls ? [] : [{
2679
+ cls,
2680
+ replacement: canonicals[i]
2681
+ }]), {
2682
+ messageId: "nonCanonical",
2683
+ replacementKey: "canonical"
2684
+ });
2361
2685
  }
2362
2686
  }
2363
2687
  return createExtractorVisitors(context, check);
@@ -2366,31 +2690,21 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2366
2690
  //#endregion
2367
2691
  //#region src/design-system/sort-service.ts
2368
2692
  /**
2369
- * Persistent sort service using worker_threads + SharedArrayBuffer.
2693
+ * Persistent sort service backed by `DesignSystemWorker`.
2370
2694
  *
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.
2374
- *
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.
2695
+ * Calls `ds.getClassOrder(classes)` and returns the class names in the
2696
+ * Tailwind-canonical order. The shared protocol (SharedArrayBuffer,
2697
+ * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2380
2698
  */
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 = `
2699
+ const sortWorker = new DesignSystemWorker({
2700
+ workerScript: `
2387
2701
  const { workerData } = require('worker_threads');
2388
2702
 
2389
2703
  async function main() {
2390
2704
  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});
2705
+ const control = new Int32Array(sharedBuffer, 0, 4);
2706
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2707
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2394
2708
 
2395
2709
  let ds;
2396
2710
  try {
@@ -2405,17 +2719,14 @@ async function main() {
2405
2719
  return;
2406
2720
  }
2407
2721
 
2408
- // Signal ready
2409
2722
  Atomics.store(control, 2, 1);
2410
2723
  Atomics.notify(control, 2);
2411
2724
 
2412
- // Request loop
2413
2725
  while (true) {
2414
- Atomics.wait(control, 0, 0); // wait for requestSignal !== 0
2415
-
2726
+ Atomics.wait(control, 0, 0);
2416
2727
  const len = lengthView.getUint32(0);
2417
2728
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2418
- Atomics.store(control, 0, 0); // consume request
2729
+ Atomics.store(control, 0, 0);
2419
2730
 
2420
2731
  let response;
2421
2732
  try {
@@ -2436,102 +2747,24 @@ async function main() {
2436
2747
 
2437
2748
  dataArea.set(response, 0);
2438
2749
  lengthView.setUint32(0, response.length);
2439
-
2440
- Atomics.store(control, 1, 1); // signal response
2750
+ Atomics.store(control, 1, 1);
2441
2751
  Atomics.notify(control, 1);
2442
2752
  }
2443
2753
  }
2444
2754
  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
- }
2755
+ `,
2756
+ serviceName: "sort"
2757
+ });
2507
2758
  /**
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.
2759
+ * Sort classes via worker thread using the official Tailwind class order.
2760
+ *
2761
+ * Throws `SortServiceError` on any failure (worker init timeout, request
2762
+ * timeout, worker crash, payload too large). Callers should wrap via
2763
+ * `safeGetDS` so the failure surfaces as a single `designSystemUnavailable`
2764
+ * diagnostic instead of crashing the lint.
2510
2765
  */
2511
2766
  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
- }
2767
+ return sortWorker.callSync(cssPath, classes);
2535
2768
  }
2536
2769
  //#endregion
2537
2770
  //#region src/rules/enforce-sort-order.ts
@@ -2551,31 +2784,23 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2551
2784
  },
2552
2785
  additionalProperties: false
2553
2786
  }],
2554
- messages: { unsorted: "Tailwind classes are not in the recommended order." }
2787
+ defaultOptions: [{ mode: "default" }],
2788
+ messages: {
2789
+ unsorted: "Tailwind classes are not in the recommended order.",
2790
+ ...DS_UNAVAILABLE_MESSAGE
2791
+ }
2555
2792
  },
2556
2793
  createOnce(context) {
2557
2794
  const getDS = createLazyLoader(context);
2558
- let _mode = null;
2559
- function getMode() {
2560
- if (_mode === null) _mode = safeOptions(context)?.mode ?? "default";
2561
- return _mode;
2562
- }
2795
+ const getMode = createLazyOptions(context, (o) => o?.mode ?? "default");
2563
2796
  function check(locations) {
2564
- const ds = getDS();
2797
+ if (locations.length === 0) return;
2798
+ const ds = safeGetDS(getDS, context, locations[0].node);
2565
2799
  if (!ds) return;
2566
2800
  const { cache, entryPoint } = ds;
2567
2801
  const mode = getMode();
2568
2802
  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);
2803
+ return sortClassesSync(entryPoint, classes);
2579
2804
  }
2580
2805
  function sortStrict(classes) {
2581
2806
  const groups = /* @__PURE__ */ new Map();
@@ -2619,7 +2844,8 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2619
2844
  const split = splitClassesWithSeparators(loc.value);
2620
2845
  const classes = split.classes;
2621
2846
  if (classes.length < 2) continue;
2622
- const sortedNames = mode === "strict" ? sortStrict(classes) : sortDefault(classes);
2847
+ const sortedNames = mode === "strict" ? sortStrict(classes) : safeGetDS(() => sortDefault(classes), context, loc.node);
2848
+ if (!sortedNames) return;
2623
2849
  if (classes.every((name, i) => name === sortedNames[i])) continue;
2624
2850
  context.report({
2625
2851
  node: loc.node,
@@ -2717,8 +2943,7 @@ const enforceShorthand = (0, _oxlint_plugins.defineRule)({
2717
2943
  const classSet = new Set(classes);
2718
2944
  const values = /* @__PURE__ */ new Set();
2719
2945
  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);
2946
+ const match = VALUE_RE.exec(splitImportant(cls).bare);
2722
2947
  if (match) values.add(match[1]);
2723
2948
  }
2724
2949
  for (const value of values) {
@@ -2752,180 +2977,234 @@ const enforceShorthand = (0, _oxlint_plugins.defineRule)({
2752
2977
  }
2753
2978
  });
2754
2979
  //#endregion
2980
+ //#region src/utils/allowlist.ts
2981
+ /**
2982
+ * Shared regex-allowlist helpers used by rules that accept an `allowlist`
2983
+ * option of regex source strings (currently enforce-logical / enforce-physical).
2984
+ *
2985
+ * Invalid regex sources are skipped rather than thrown so a typo in one
2986
+ * pattern doesn't blow up the entire lint run.
2987
+ */
2988
+ function compileRegexList(patterns) {
2989
+ if (!patterns || patterns.length === 0) return [];
2990
+ const compiled = [];
2991
+ for (const p of patterns) try {
2992
+ compiled.push(new RegExp(p));
2993
+ } catch {}
2994
+ return compiled;
2995
+ }
2996
+ function matchesAny(value, list) {
2997
+ return list.some((re) => re.test(value));
2998
+ }
2999
+ //#endregion
2755
3000
  //#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}}\"."
3001
+ const LOGICAL_PHYSICAL_SCHEMA = {
3002
+ type: "object",
3003
+ properties: {
3004
+ allowlist: {
3005
+ type: "array",
3006
+ items: { type: "string" }
3007
+ },
3008
+ direction: {
3009
+ type: "string",
3010
+ enum: [
3011
+ "inline",
3012
+ "block",
3013
+ "both"
3014
+ ]
2786
3015
  }
2787
3016
  },
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;
3017
+ additionalProperties: false
3018
+ };
3019
+ const PHYSICAL_TO_LOGICAL_MAPPINGS = [
3020
+ {
3021
+ from: "ml",
3022
+ to: "ms",
3023
+ axis: "inline"
3024
+ },
3025
+ {
3026
+ from: "mr",
3027
+ to: "me",
3028
+ axis: "inline"
3029
+ },
3030
+ {
3031
+ from: "pl",
3032
+ to: "ps",
3033
+ axis: "inline"
3034
+ },
3035
+ {
3036
+ from: "pr",
3037
+ to: "pe",
3038
+ axis: "inline"
3039
+ },
3040
+ {
3041
+ from: "left",
3042
+ to: "start",
3043
+ axis: "inline"
3044
+ },
3045
+ {
3046
+ from: "right",
3047
+ to: "end",
3048
+ axis: "inline"
3049
+ },
3050
+ {
3051
+ from: "border-l",
3052
+ to: "border-s",
3053
+ axis: "inline"
3054
+ },
3055
+ {
3056
+ from: "border-r",
3057
+ to: "border-e",
3058
+ axis: "inline"
3059
+ },
3060
+ {
3061
+ from: "rounded-l",
3062
+ to: "rounded-s",
3063
+ axis: "inline"
3064
+ },
3065
+ {
3066
+ from: "rounded-r",
3067
+ to: "rounded-e",
3068
+ axis: "inline"
3069
+ },
3070
+ {
3071
+ from: "rounded-tl",
3072
+ to: "rounded-ss",
3073
+ axis: "inline"
3074
+ },
3075
+ {
3076
+ from: "rounded-tr",
3077
+ to: "rounded-se",
3078
+ axis: "inline"
3079
+ },
3080
+ {
3081
+ from: "rounded-bl",
3082
+ to: "rounded-es",
3083
+ axis: "inline"
3084
+ },
3085
+ {
3086
+ from: "rounded-br",
3087
+ to: "rounded-ee",
3088
+ axis: "inline"
3089
+ },
3090
+ {
3091
+ from: "scroll-ml",
3092
+ to: "scroll-ms",
3093
+ axis: "inline"
3094
+ },
3095
+ {
3096
+ from: "scroll-mr",
3097
+ to: "scroll-me",
3098
+ axis: "inline"
3099
+ },
3100
+ {
3101
+ from: "scroll-pl",
3102
+ to: "scroll-ps",
3103
+ axis: "inline"
3104
+ },
3105
+ {
3106
+ from: "scroll-pr",
3107
+ to: "scroll-pe",
3108
+ axis: "inline"
3109
+ }
3110
+ ];
3111
+ /** Invert a directional table. enforce-physical consumes this. */
3112
+ function invertAxisMappings(mappings) {
3113
+ return mappings.map((m) => ({
3114
+ from: m.to,
3115
+ to: m.from,
3116
+ axis: m.axis
3117
+ }));
3118
+ }
3119
+ Object.fromEntries(PHYSICAL_TO_LOGICAL_MAPPINGS.map((m) => [m.from, m.to]));
3120
+ /**
3121
+ * Build the `check` callback for a directional-rewrite rule. Both
3122
+ * enforce-logical and enforce-physical instantiate this with their own
3123
+ * mapping table and messageId; the rule's `createOnce` wires it through
3124
+ * `createExtractorVisitors`.
3125
+ *
3126
+ * Owns: option compilation (allowlist + direction), per-class conversion
3127
+ * (linear scan of the mapping table respecting `!`-prefix/suffix), and
3128
+ * the `reportClassReplacements` dispatch.
3129
+ */
3130
+ function createDirectionalMapper(context, opts) {
3131
+ const getState = createLazyOptions(context, (o) => ({
3132
+ allowlist: compileRegexList(o?.allowlist),
3133
+ direction: o?.direction ?? "both"
3134
+ }));
3135
+ function convertClass(cls) {
3136
+ const { allowlist, direction } = getState();
3137
+ if (matchesAny(cls, allowlist)) return null;
3138
+ const { utility, variant } = splitUtilityAndVariant(cls);
3139
+ const { bare: bareUtility, position } = splitImportant(utility);
3140
+ for (const { from, to, axis } of opts.mappings) {
3141
+ if (direction !== "both" && direction !== axis) continue;
3142
+ if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
2799
3143
  }
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
- }
3144
+ return null;
3145
+ }
3146
+ function check(locations) {
3147
+ for (const loc of locations) {
3148
+ const split = splitClassesWithSeparators(loc.value);
3149
+ const offending = split.classes.flatMap((cls) => {
3150
+ const converted = convertClass(cls);
3151
+ return converted ? [{
3152
+ cls,
3153
+ replacement: converted
3154
+ }] : [];
3155
+ });
3156
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: opts.messageId });
2848
3157
  }
2849
- return createExtractorVisitors(context, check);
2850
3158
  }
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)({
3159
+ return { check };
3160
+ }
3161
+ const enforceLogical = (0, _oxlint_plugins.defineRule)({
2857
3162
  meta: {
2858
3163
  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
- }
3164
+ docs: { description: "Enforce logical (RTL-friendly) Tailwind CSS properties instead of physical ones" },
3165
+ fixable: "code",
3166
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
3167
+ hasSuggestions: true,
3168
+ defaultOptions: [{
3169
+ allowlist: [],
3170
+ direction: "both"
3171
+ }],
3172
+ messages: {
3173
+ useLogical: "\"{{className}}\" uses a physical property. Use \"{{replacement}}\" for LTR/RTL support.",
3174
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3175
+ }
3176
+ },
3177
+ createOnce(context) {
3178
+ const { check } = createDirectionalMapper(context, {
3179
+ mappings: PHYSICAL_TO_LOGICAL_MAPPINGS,
3180
+ messageId: "useLogical"
3181
+ });
3182
+ return createExtractorVisitors(context, check);
3183
+ }
3184
+ });
3185
+ //#endregion
3186
+ //#region src/rules/enforce-physical.ts
3187
+ const enforcePhysical = (0, _oxlint_plugins.defineRule)({
3188
+ meta: {
3189
+ type: "suggestion",
3190
+ docs: { description: "Enforce physical Tailwind CSS properties instead of logical ones for consistency in LTR-only projects" },
3191
+ fixable: "code",
3192
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
3193
+ hasSuggestions: true,
3194
+ defaultOptions: [{
3195
+ allowlist: [],
3196
+ direction: "both"
3197
+ }],
3198
+ messages: {
3199
+ usePhysical: "\"{{className}}\" uses a logical property. Use \"{{replacement}}\" for consistency.",
3200
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2928
3201
  }
3202
+ },
3203
+ createOnce(context) {
3204
+ const { check } = createDirectionalMapper(context, {
3205
+ mappings: invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS),
3206
+ messageId: "usePhysical"
3207
+ });
2929
3208
  return createExtractorVisitors(context, check);
2930
3209
  }
2931
3210
  });
@@ -2945,11 +3224,7 @@ const maxClassCount = (0, _oxlint_plugins.defineRule)({
2945
3224
  messages: { tooMany: "Too many Tailwind classes ({{count}}). Maximum allowed is {{max}}. Consider extracting into a component or utility." }
2946
3225
  },
2947
3226
  createOnce(context) {
2948
- let _max = null;
2949
- function getMax() {
2950
- if (_max === null) _max = safeOptions(context)?.max ?? DEFAULT_MAX;
2951
- return _max;
2952
- }
3227
+ const getMax = createLazyOptions(context, (o) => o?.max ?? DEFAULT_MAX);
2953
3228
  function check(locations) {
2954
3229
  const max = getMax();
2955
3230
  for (const loc of locations) {
@@ -2995,26 +3270,23 @@ const noRestrictedClasses = (0, _oxlint_plugins.defineRule)({
2995
3270
  },
2996
3271
  additionalProperties: false
2997
3272
  }],
3273
+ defaultOptions: [{
3274
+ classes: [],
3275
+ patterns: []
3276
+ }],
2998
3277
  messages: {
2999
3278
  restricted: "\"{{className}}\" is restricted.",
3000
3279
  restrictedWithMessage: "\"{{className}}\" is restricted: {{message}}"
3001
3280
  }
3002
3281
  },
3003
3282
  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
- }
3283
+ const getConfig = createLazyOptions(context, (o) => ({
3284
+ restrictedClasses: new Set(o?.classes ?? []),
3285
+ patterns: (o?.patterns ?? []).map((p) => ({
3286
+ regex: new RegExp(p.pattern),
3287
+ message: p.message
3288
+ }))
3289
+ }));
3018
3290
  function check(locations) {
3019
3291
  const { restrictedClasses, patterns } = getConfig();
3020
3292
  if (restrictedClasses.size === 0 && patterns.length === 0) return;
@@ -3065,14 +3337,11 @@ const noArbitraryValue = (0, _oxlint_plugins.defineRule)({
3065
3337
  } },
3066
3338
  additionalProperties: false
3067
3339
  }],
3340
+ defaultOptions: [{ allow: [] }],
3068
3341
  messages: { noArbitrary: "\"{{className}}\" uses an arbitrary value. Use a design token or extend your theme instead." }
3069
3342
  },
3070
3343
  createOnce(context) {
3071
- let _allowPrefixes = null;
3072
- function getAllowPrefixes() {
3073
- if (_allowPrefixes === null) _allowPrefixes = safeOptions(context)?.allow ?? [];
3074
- return _allowPrefixes;
3075
- }
3344
+ const getAllowPrefixes = createLazyOptions(context, (o) => o?.allow ?? []);
3076
3345
  function isAllowed(utility) {
3077
3346
  return getAllowPrefixes().some((prefix) => utility.startsWith(prefix));
3078
3347
  }
@@ -3081,9 +3350,7 @@ const noArbitraryValue = (0, _oxlint_plugins.defineRule)({
3081
3350
  const classes = splitClasses(loc.value);
3082
3351
  for (const cls of classes) {
3083
3352
  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);
3353
+ const utility = splitImportant(extractUtility(cls)).bare;
3087
3354
  if (isAllowed(utility)) continue;
3088
3355
  context.report({
3089
3356
  node: loc.node,
@@ -3120,11 +3387,7 @@ const enforceConsistentImportantPosition = (0, _oxlint_plugins.defineRule)({
3120
3387
  }
3121
3388
  },
3122
3389
  createOnce(context) {
3123
- let _position = null;
3124
- function getPosition() {
3125
- if (_position === null) _position = safeOptions(context)?.position ?? "suffix";
3126
- return _position;
3127
- }
3390
+ const getPosition = createLazyOptions(context, (o) => o?.position ?? "suffix");
3128
3391
  function fixUtility(utility, variantPfx) {
3129
3392
  const position = getPosition();
3130
3393
  if (position === "prefix" && utility.endsWith("!") && !utility.startsWith("!")) return `${variantPfx}!${utility.slice(0, -1)}`;
@@ -3132,54 +3395,18 @@ const enforceConsistentImportantPosition = (0, _oxlint_plugins.defineRule)({
3132
3395
  return null;
3133
3396
  }
3134
3397
  function check(locations) {
3135
- const position = getPosition();
3398
+ const messageId = getPosition() === "prefix" ? "usePrefix" : "useSuffix";
3136
3399
  for (const loc of locations) {
3137
3400
  const split = splitClassesWithSeparators(loc.value);
3138
- const classes = split.classes;
3139
- const offending = [];
3140
- for (const cls of classes) {
3401
+ const offending = split.classes.flatMap((cls) => {
3141
3402
  const { utility, variant } = splitUtilityAndVariant(cls);
3142
3403
  const fixed = fixUtility(utility, variant);
3143
- if (fixed) offending.push({
3404
+ return fixed ? [{
3144
3405
  cls,
3145
3406
  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
- }
3407
+ }] : [];
3408
+ });
3409
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3183
3410
  }
3184
3411
  }
3185
3412
  return createExtractorVisitors(context, check);
@@ -3222,50 +3449,14 @@ const enforceNegativeArbitraryValues = (0, _oxlint_plugins.defineRule)({
3222
3449
  function check(locations) {
3223
3450
  for (const loc of locations) {
3224
3451
  const split = splitClassesWithSeparators(loc.value);
3225
- const classes = split.classes;
3226
- const offending = [];
3227
- for (const cls of classes) {
3452
+ const offending = split.classes.flatMap((cls) => {
3228
3453
  const fixed = fixClass(cls);
3229
- if (fixed) offending.push({
3454
+ return fixed ? [{
3230
3455
  cls,
3231
3456
  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
- }
3457
+ }] : [];
3458
+ });
3459
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "moveNegative" });
3269
3460
  }
3270
3461
  }
3271
3462
  return createExtractorVisitors(context, check);
@@ -3277,22 +3468,18 @@ const EXPLICIT_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\[var\((--[a-zA-Z0-9-
3277
3468
  const SHORTHAND_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\((--[a-zA-Z0-9-]+)\)$/;
3278
3469
  function convertClass(cls, syntax) {
3279
3470
  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 ? "!" : "";
3471
+ const { bare: bareUtility, position } = splitImportant(utility);
3285
3472
  if (syntax === "shorthand") {
3286
3473
  const match = EXPLICIT_VAR_RE.exec(bareUtility);
3287
3474
  if (match) {
3288
3475
  const [, prefix, varName] = match;
3289
- return `${variant}${importantStart}${prefix}-(${varName})${importantEnd}`;
3476
+ return `${variant}${reattachImportant(`${prefix}-(${varName})`, position)}`;
3290
3477
  }
3291
3478
  } else {
3292
3479
  const match = SHORTHAND_VAR_RE.exec(bareUtility);
3293
3480
  if (match) {
3294
3481
  const [, prefix, varName] = match;
3295
- return `${variant}${importantStart}${prefix}-[var(${varName})]${importantEnd}`;
3482
+ return `${variant}${reattachImportant(`${prefix}-[var(${varName})]`, position)}`;
3296
3483
  }
3297
3484
  }
3298
3485
  return null;
@@ -3319,60 +3506,20 @@ const enforceConsistentVariableSyntax = (0, _oxlint_plugins.defineRule)({
3319
3506
  }
3320
3507
  },
3321
3508
  createOnce(context) {
3322
- let _syntax = null;
3323
- function getSyntax() {
3324
- if (_syntax === null) _syntax = safeOptions(context)?.syntax ?? "shorthand";
3325
- return _syntax;
3326
- }
3509
+ const getSyntax = createLazyOptions(context, (o) => o?.syntax ?? "shorthand");
3327
3510
  function check(locations) {
3328
3511
  const syntax = getSyntax();
3512
+ const messageId = syntax === "shorthand" ? "useShorthand" : "useExplicit";
3329
3513
  for (const loc of locations) {
3330
3514
  const split = splitClassesWithSeparators(loc.value);
3331
- const classes = split.classes;
3332
- const offending = [];
3333
- for (const cls of classes) {
3515
+ const offending = split.classes.flatMap((cls) => {
3334
3516
  const converted = convertClass(cls, syntax);
3335
- if (converted) offending.push({
3517
+ return converted ? [{
3336
3518
  cls,
3337
3519
  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
- }
3520
+ }] : [];
3521
+ });
3522
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3376
3523
  }
3377
3524
  }
3378
3525
  return createExtractorVisitors(context, check);
@@ -3418,9 +3565,7 @@ const KNOWN_PREFIXES = [
3418
3565
  * Used to group utilities by their property type.
3419
3566
  */
3420
3567
  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);
3568
+ let u = splitImportant(utility).bare;
3424
3569
  if (u.startsWith("-")) u = u.slice(1);
3425
3570
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3426
3571
  const dashIdx = u.indexOf("-");
@@ -3442,14 +3587,7 @@ const noDarkWithoutLight = (0, _oxlint_plugins.defineRule)({
3442
3587
  messages: { missingBase: "\"{{className}}\" uses the {{variant}} variant, but there is no base \"{{prefix}}-*\" class on this element." }
3443
3588
  },
3444
3589
  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
- }
3590
+ const getWatchedVariants = createLazyOptions(context, (o) => new Set(o?.variants ?? DEFAULT_VARIANTS));
3453
3591
  function check(locations) {
3454
3592
  const watchedVariants = getWatchedVariants();
3455
3593
  for (const loc of locations) {
@@ -3545,17 +3683,11 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3545
3683
  },
3546
3684
  additionalProperties: false
3547
3685
  }],
3686
+ defaultOptions: [{ allow: [] }],
3548
3687
  messages: { noHardcoded: "\"{{className}}\" uses a hardcoded color value. Use a design token from your theme instead." }
3549
3688
  },
3550
3689
  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
- }
3690
+ const getAllowlist = createLazyOptions(context, (o) => new Set(o?.allow ?? []));
3559
3691
  function check(locations) {
3560
3692
  const allowlist = getAllowlist();
3561
3693
  for (const loc of locations) {
@@ -3563,9 +3695,7 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3563
3695
  for (const cls of classes) {
3564
3696
  if (allowlist.has(cls)) continue;
3565
3697
  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);
3698
+ const utility = splitImportant(extractUtility(cls)).bare;
3569
3699
  if (!isColorUtility(utility)) continue;
3570
3700
  const value = getArbitraryValue(cls);
3571
3701
  if (!value) continue;
@@ -3736,6 +3866,7 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3736
3866
  additionalProperties: false
3737
3867
  }],
3738
3868
  hasSuggestions: true,
3869
+ defaultOptions: [{}],
3739
3870
  messages: {
3740
3871
  wrongOrder: "\"{{className}}\" has variants in wrong order. Use \"{{replacement}}\" instead.",
3741
3872
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
@@ -3743,54 +3874,33 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3743
3874
  },
3744
3875
  createOnce(context) {
3745
3876
  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
- }
3877
+ const getPriority = createLazyOptions(context, (o) => {
3878
+ let dsCache = null;
3879
+ try {
3880
+ dsCache = getDS().cache;
3881
+ } catch (err) {
3882
+ if (!isFatalError(err)) throw err;
3883
+ }
3884
+ if (o?.order) {
3885
+ const map = /* @__PURE__ */ new Map();
3886
+ for (let i = 0; i < o.order.length; i++) map.set(o.order[i], i);
3887
+ const fallback = o.order.length;
3888
+ return (v) => map.get(v) ?? fallback;
3777
3889
  }
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
3890
  if (dsCache && dsCache.hasVariantOrder()) {
3785
- const dsPriority = dsCache.getVariantPriority(variant);
3786
- if (dsPriority !== null) return dsPriority;
3891
+ const ds = dsCache;
3892
+ return (v) => ds.getVariantPriority(v) ?? Number.MAX_SAFE_INTEGER;
3787
3893
  }
3788
- return fallbackPriority;
3789
- }
3894
+ const map = /* @__PURE__ */ new Map();
3895
+ for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3896
+ const fallback = DEFAULT_VARIANT_ORDER.length;
3897
+ return (v) => map.get(v) ?? fallback;
3898
+ });
3790
3899
  function reorderClass(cls) {
3791
3900
  const variants = extractVariants(cls);
3792
3901
  if (variants.length < 2) return null;
3793
- const sorted = [...variants].sort((a, b) => getVariantPriority(a) - getVariantPriority(b));
3902
+ const priorityOf = getPriority();
3903
+ const sorted = [...variants].sort((a, b) => priorityOf(a) - priorityOf(b));
3794
3904
  const nonPseudo = [];
3795
3905
  const pseudo = [];
3796
3906
  for (const v of sorted) if (PSEUDO_ELEMENTS.has(v)) pseudo.push(v);
@@ -3875,16 +3985,8 @@ const enforceConsistentLineWrapping = (0, _oxlint_plugins.defineRule)({
3875
3985
  }
3876
3986
  },
3877
3987
  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
- }
3988
+ const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
3989
+ const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
3888
3990
  function check(locations) {
3889
3991
  const printWidth = getPrintWidth();
3890
3992
  const classesPerLine = getClassesPerLine();
@@ -3943,69 +4045,33 @@ const noUnnecessaryArbitraryValue = (0, _oxlint_plugins.defineRule)({
3943
4045
  additionalProperties: false
3944
4046
  }],
3945
4047
  hasSuggestions: true,
4048
+ defaultOptions: [{}],
3946
4049
  messages: {
3947
4050
  unnecessaryArbitrary: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named class instead.",
3948
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
4051
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
4052
+ ...DS_UNAVAILABLE_MESSAGE
3949
4053
  }
3950
4054
  },
3951
4055
  createOnce(context) {
3952
4056
  const getDS = createLazyLoader(context);
3953
4057
  function check(locations) {
3954
- const ds = getDS();
4058
+ if (locations.length === 0) return;
4059
+ const ds = safeGetDS(getDS, context, locations[0].node);
3955
4060
  if (!ds) return;
3956
4061
  const { cache } = ds;
3957
4062
  for (const loc of locations) {
3958
4063
  const split = splitClassesWithSeparators(loc.value);
3959
- const classes = split.classes;
3960
- const offending = [];
3961
- for (const cls of classes) {
3962
- if (!hasArbitraryValue(cls)) continue;
4064
+ const offending = split.classes.flatMap((cls) => {
4065
+ if (!hasArbitraryValue(cls)) return [];
3963
4066
  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;
4067
+ const { bare: bareUtility, position } = splitImportant(utility);
3967
4068
  const named = cache.getNamedEquivalent(bareUtility);
3968
- if (!named) continue;
3969
- offending.push({
4069
+ return named ? [{
3970
4070
  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
- }
4071
+ replacement: variant + reattachImportant(named, position)
4072
+ }] : [];
4073
+ });
4074
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "unnecessaryArbitrary" });
4009
4075
  }
4010
4076
  }
4011
4077
  return createExtractorVisitors(context, check);
@@ -4049,73 +4115,37 @@ const preferThemeTokens = (0, _oxlint_plugins.defineRule)({
4049
4115
  additionalProperties: false
4050
4116
  }],
4051
4117
  hasSuggestions: true,
4118
+ defaultOptions: [{}],
4052
4119
  messages: {
4053
4120
  preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
4054
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
4121
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
4122
+ ...DS_UNAVAILABLE_MESSAGE
4055
4123
  }
4056
4124
  },
4057
4125
  createOnce(context) {
4058
4126
  const getDS = createLazyLoader(context);
4059
4127
  function check(locations) {
4060
- const ds = getDS();
4128
+ if (locations.length === 0) return;
4129
+ const ds = safeGetDS(getDS, context, locations[0].node);
4061
4130
  if (!ds) return;
4062
4131
  const { cache } = ds;
4063
4132
  for (const loc of locations) {
4064
4133
  const split = splitClassesWithSeparators(loc.value);
4065
- const classes = split.classes;
4066
- const offending = [];
4067
- for (const cls of classes) {
4134
+ const offending = split.classes.flatMap((cls) => {
4068
4135
  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;
4136
+ const { bare: bareUtility, position } = splitImportant(utility);
4072
4137
  const match = detectRawVariable(bareUtility);
4073
- if (!match) continue;
4138
+ if (!match) return [];
4074
4139
  const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
4075
- if (!cache.isValid(candidate)) continue;
4140
+ if (!cache.isValid(candidate)) return [];
4076
4141
  const namedEquivalent = cache.getNamedEquivalent(bareUtility);
4077
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) continue;
4078
- const replacement = variant + (hasImportantPrefix ? "!" : "") + candidate + (hasImportantSuffix ? "!" : "");
4079
- offending.push({
4142
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
4143
+ return [{
4080
4144
  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
- }
4145
+ replacement: variant + reattachImportant(candidate, position)
4146
+ }];
4147
+ });
4148
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
4119
4149
  }
4120
4150
  }
4121
4151
  return createExtractorVisitors(context, check);