stylelint-plugin-rhythmguard 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +4 -4
  4. package/SECURITY.md +14 -0
  5. package/agents/claude-code/SKILL.md +14 -1
  6. package/agents/copilot/{copilot-instructions.md → rhythmguard.instructions.md} +7 -1
  7. package/agents/cursor/rhythmguard.mdc +5 -3
  8. package/package.json +2 -2
  9. package/src/audit/args.js +30 -8
  10. package/src/audit/baseline.js +44 -2
  11. package/src/audit/codemod.js +2 -0
  12. package/src/audit/config.js +7 -0
  13. package/src/audit/contract.js +131 -17
  14. package/src/audit/next-steps.js +86 -0
  15. package/src/audit/non-authored.js +1 -0
  16. package/src/audit/render-github.js +52 -15
  17. package/src/audit/render-markdown.js +58 -17
  18. package/src/audit/render-text.js +76 -6
  19. package/src/audit/render-utils.js +14 -0
  20. package/src/audit/report.js +235 -10
  21. package/src/audit/scan/files.js +5 -0
  22. package/src/audit/scan/stylesheets.js +63 -59
  23. package/src/audit/scan/templates.js +2 -0
  24. package/src/audit/shared.js +7 -1
  25. package/src/audit/token-chains.js +1 -0
  26. package/src/cli/audit.js +20 -11
  27. package/src/cli/doctor.js +853 -237
  28. package/src/cli/first-run.js +210 -0
  29. package/src/cli/index.js +25 -1
  30. package/src/cli/index.mjs +3 -0
  31. package/src/cli/init.js +75 -26
  32. package/src/cli/quickstart.js +109 -118
  33. package/src/cli/scale.js +223 -0
  34. package/src/configs/recommended.js +3 -1
  35. package/src/configs/strict.js +3 -1
  36. package/src/configs/tailwind.js +15 -0
  37. package/src/core/decisions.js +18 -5
  38. package/src/core/fs-cache.js +1 -0
  39. package/src/core/options.js +2 -1
  40. package/src/core/scale-inference.js +72 -52
  41. package/src/core/tailwind-class-analysis.js +56 -13
  42. package/src/core/token-index.js +55 -14
  43. package/src/core/token-map.js +140 -88
  44. package/src/core/token-sources.js +461 -40
  45. package/src/core/value-nodes.js +4 -2
  46. package/src/eslint/class-context.js +330 -0
  47. package/src/eslint/literal-spans.js +5 -4
  48. package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
  49. package/src/presets/default-scale.js +42 -0
  50. package/src/presets/scales.js +6 -1
  51. package/src/rules/no-offscale-transform/index.js +17 -5
  52. package/src/rules/prefer-token/index.js +51 -15
  53. package/src/rules/use-scale/index.js +7 -4
  54. package/types/__checks__/consumer.ts +17 -0
  55. package/types/__checks__/eslint-config.ts +5 -0
  56. package/types/audit.d.ts +42 -3
  57. package/types/cli.d.ts +77 -1
  58. package/types/shared.d.ts +10 -0
@@ -4,13 +4,19 @@ const {
4
4
  sortCountMap,
5
5
  sumCounts,
6
6
  } = require('./contract');
7
+ const { auditCommand, shellQuote } = require('./next-steps');
7
8
  const {
8
9
  histBar,
10
+ newFindingsPhrase,
9
11
  scoreBar,
10
12
  truncate,
11
13
  } = require('./render-utils');
12
14
 
13
- function renderText(report) {
15
+ /**
16
+ * `options.auditCommand` is the command that reproduces this run (its directory
17
+ * and scale flags); the footer builds on it so the next step uses the same scale.
18
+ */
19
+ function renderText(report, options = {}) {
14
20
  const lines = [
15
21
  '',
16
22
  ' ┌─ RHYTHMGUARD DESIGN-SYSTEM AUDIT ─────────────────────────┐',
@@ -21,6 +27,7 @@ function renderText(report) {
21
27
  ` Template files scanned ${String(report.templateFilesScanned).padStart(4)}`,
22
28
  ...(report.scanned && report.scanned.scssFiles > 0 ? [` SCSS files scanned ${String(report.scanned.scssFiles - report.scanned.scssSkipped).padStart(4)}`] : []),
23
29
  ...(report.scanned && report.scanned.scssSkipped > 0 ? [` SCSS files skipped ${String(report.scanned.scssSkipped).padStart(4)} (install postcss-scss to audit them)`] : []),
30
+ ...(report.scanned && report.scanned.stylelintMissing > 0 ? [` Stylesheets not audited ${String(report.scanned.stylelintMissing).padStart(4)} (Stylelint is not installed: npm install --save-dev stylelint)`] : []),
24
31
  ...(report.scanned && report.scanned.stylelintIgnored > 0 ? [` Ignored by .stylelintignore ${String(report.scanned.stylelintIgnored).padStart(4)} (not audited)`] : []),
25
32
  ...(report.scanned && report.scanned.nonAuthoredSkipped > 0 ? [` Non-authored skipped ${String(report.scanned.nonAuthoredSkipped).padStart(4)} (vendored, minified or built CSS; --include-non-authored audits them)`] : []),
26
33
  ...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [` Links not followed ${String(report.scanned.linksOutsideRoot).padStart(4)} (they point outside the scanned directory)`] : []),
@@ -32,14 +39,27 @@ function renderText(report) {
32
39
  if (report.scale) {
33
40
  lines.push(` Scale ${report.scale.values.join(', ')}`);
34
41
  const files = report.scale.files.length > 0 ? ` (${report.scale.files.join(', ')})` : '';
35
- const rejected = report.scale.rejected ? ` (${report.scale.rejected.source} rejected: ${report.scale.rejected.reasons.join(', ')})` : '';
42
+ // Configured token sources that gave no scale: their warnings are printed under the token contract.
43
+ const rejected = !report.scale.rejected ? ''
44
+ : report.scale.rejected.source === 'token-sources' ? ' (token sources gave no scale; see the warnings)'
45
+ : ` (${report.scale.rejected.source} rejected: ${report.scale.rejected.reasons.join(', ')})`;
36
46
  lines.push(` Scale source ${report.scale.source}${files}${rejected}`);
47
+ // Warnings that belong to no token source, such as a Tailwind config that could not be loaded (cq-05).
48
+ const sourceWarnings = new Set(((report.tokenContract && report.tokenContract.sources) || []).flatMap((source) => source.warnings || []));
49
+ for (const warning of new Set(report.tokenSourceWarnings || [])) {
50
+ if (!sourceWarnings.has(warning)) {
51
+ lines.push(` ! ${warning}`);
52
+ }
53
+ }
54
+ if (report.scale.classStrings) {
55
+ lines.push(` Class-string scale ${report.scale.classStrings.name} (${report.scale.classStrings.values.join(', ')})`);
56
+ }
37
57
  }
38
58
  if (report.decisions) {
39
59
  lines.push(` Decisions ${report.decisions.adopt + report.decisions.allow + report.decisions.snap + report.decisions.undecided} (${report.decisions.adopt} adopt, ${report.decisions.allow} allow, ${report.decisions.snap} snap, ${report.decisions.undecided} undecided); ${report.decisions.suppressed} findings suppressed`);
40
60
  }
41
61
  if (report.baseline) {
42
- lines.push(` Since baseline ${report.baseline.resolvedFindingsCount} resolved, ${report.baseline.newFindingsCount} new`);
62
+ lines.push(` Since baseline ${report.baseline.resolvedFindingsCount} resolved, ${newFindingsPhrase(report.baseline)}`);
43
63
  }
44
64
  lines.push('');
45
65
 
@@ -48,6 +68,8 @@ function renderText(report) {
48
68
  appendHistogram(lines, 'CSS TOKEN OPPORTUNITIES', report.tokenOpportunities);
49
69
  appendHistogram(lines, 'TAILWIND CLASS-STRING DRIFT', report.tailwindArbitraryValues);
50
70
  appendHistogram(lines, 'MOTION RHYTHM DRIFT', report.motion.values);
71
+ appendFindingList(lines, 'MISSING TOKENS IN USE', report.findings.css.filter((finding) => finding.type === 'missing-token'));
72
+ appendFindingList(lines, 'UNCLASSIFIED WARNINGS', report.findings.css.filter((finding) => finding.type === 'unclassified'));
51
73
  appendTokenContractText(lines, report.tokenContract);
52
74
  if (report.tokenContract.chains && report.tokenContract.chains.summary.total > 0) {
53
75
  const { summary } = report.tokenContract.chains;
@@ -72,19 +94,42 @@ function renderText(report) {
72
94
  lines.push('');
73
95
  }
74
96
 
75
- if (report.totalWarnings === 0 && parseErrors(report).length > 0) {
97
+ if (nothingAudited(report)) {
98
+ lines.push(` ! Nothing was audited: ${nothingAuditedReasons(report).join('; ')}. The cleanliness above counts no files.`);
99
+ } else if (report.totalWarnings === 0 && parseErrors(report).length > 0) {
76
100
  lines.push(` ! No findings in the stylesheets that parsed; ${parseErrors(report).length} could not be parsed and were not audited.`);
77
101
  } else if (report.totalWarnings === 0) {
78
102
  lines.push(' ✓ No issues found. Your design-system rhythm is clean.');
79
103
  } else {
80
- lines.push(' → Run "npx stylelint --fix" for CSS declaration fixes.');
81
- lines.push(' → Use "npx rhythmguard audit ./src --format markdown" for PR/design review.');
104
+ // Snapping a value can move layout, so the footer offers the reviewable
105
+ // path: one decision per value, then a rewrite of each decided value.
106
+ const command = options.auditCommand || auditCommand({ dir: report.directory });
107
+ lines.push(` → Propose one decision per off-scale value: ${command} --plan`);
108
+ lines.push(` → Then rewrite each value you decided on: npx rhythmguard fix ${shellQuote(report.directory)} --value <px> --to <step or token>`);
109
+ lines.push(` → PR or design review: ${command} --format markdown`);
82
110
  }
83
111
  lines.push('');
84
112
 
85
113
  return `${lines.join('\n')}\n`;
86
114
  }
87
115
 
116
+ /** No stylesheet and no template file was read, though the run may have found some (dx-09). */
117
+ function nothingAudited(report) {
118
+ return (report.cssFilesScanned || 0) === 0 && (report.templateFilesScanned || 0) === 0;
119
+ }
120
+
121
+ function nothingAuditedReasons(report) {
122
+ const scanned = report.scanned || {};
123
+ const reasons = [
124
+ ...(scanned.stylelintMissing > 0 ? [`${scanned.stylelintMissing} stylesheets need Stylelint, which is not installed`] : []),
125
+ ...(scanned.scssSkipped > 0 ? [`${scanned.scssSkipped} SCSS files need postcss-scss, which is not installed`] : []),
126
+ ...(scanned.stylelintIgnored > 0 ? [`${scanned.stylelintIgnored} stylesheets are in .stylelintignore`] : []),
127
+ ...(scanned.nonAuthoredSkipped > 0 ? [`${scanned.nonAuthoredSkipped} stylesheets look vendored, minified or built`] : []),
128
+ ...(parseErrors(report).length > 0 ? [`${parseErrors(report).length} stylesheets could not be parsed`] : []),
129
+ ];
130
+ return reasons.length > 0 ? reasons : [`no .css, .scss or template files under ${report.directory}`];
131
+ }
132
+
88
133
  function parseErrors(report) {
89
134
  return (report.findings && report.findings.parseErrors) || [];
90
135
  }
@@ -180,6 +225,9 @@ function appendBaselineText(lines, report) {
180
225
  lines.push('');
181
226
  lines.push(` Baseline findings ${String(report.baseline.baselineFindings).padStart(4)}`);
182
227
  lines.push(` New findings ${String(report.baseline.newFindingsCount).padStart(4)}`);
228
+ if (report.baseline.newTokenDebtCount > 0) {
229
+ lines.push(` of which token debt ${String(report.baseline.newTokenDebtCount).padStart(4)} (not drift; --fail-on-new-token-debt gates it)`);
230
+ }
183
231
  lines.push(` Resolved findings ${String(report.baseline.resolvedFindingsCount).padStart(4)}`);
184
232
  lines.push('');
185
233
  }
@@ -190,6 +238,26 @@ function appendBaselineText(lines, report) {
190
238
  }
191
239
  }
192
240
 
241
+ /**
242
+ * Findings that have no value to count by: missing-token uses (with
243
+ * --report-missing-tokens) and Stylelint warnings the audit could not read
244
+ * (cq-02). Ten lines, then a count.
245
+ */
246
+ function appendFindingList(lines, title, findings) {
247
+ if (findings.length === 0) {
248
+ return;
249
+ }
250
+ lines.push(` ── ${title} ── ${findings.length} total`);
251
+ lines.push('');
252
+ for (const finding of findings.slice(0, 10)) {
253
+ lines.push(` ${finding.file}:${finding.line}:${finding.column} ${finding.text}`);
254
+ }
255
+ if (findings.length > 10) {
256
+ lines.push(` ${findings.length - 10} more in --format json`);
257
+ }
258
+ lines.push('');
259
+ }
260
+
193
261
  function appendHistogram(lines, title, counts = {}) {
194
262
  const entries = sortCountMap(counts || {});
195
263
  const total = sumCounts(counts || {});
@@ -208,6 +276,8 @@ function appendHistogram(lines, title, counts = {}) {
208
276
  }
209
277
 
210
278
  module.exports = {
279
+ nothingAudited,
280
+ nothingAuditedReasons,
211
281
  appendBaselineText,
212
282
  appendHistogram,
213
283
  appendParseErrorsText,
@@ -57,11 +57,25 @@ function escapeHtml(value) {
57
57
  .replace(/"/g, '&quot;');
58
58
  }
59
59
 
60
+ /**
61
+ * "N new", and when some of them are token debt, how many are drift and how
62
+ * many token debt: --fail-on-new-drift counts only the drift (dx-08).
63
+ */
64
+ function newFindingsPhrase(baseline) {
65
+ const total = baseline.newFindingsCount;
66
+ const debt = Number.isInteger(baseline.newTokenDebtCount) ? baseline.newTokenDebtCount : 0;
67
+ if (debt === 0) {
68
+ return `${total} new`;
69
+ }
70
+ return `${total} new (${total - debt} drift, ${debt} token debt)`;
71
+ }
72
+
60
73
  module.exports = {
61
74
  escapeHtml,
62
75
  escapeMarkdown,
63
76
  histBar,
64
77
  markdownCode,
78
+ newFindingsPhrase,
65
79
  tableCode,
66
80
  scoreBar,
67
81
  truncate,
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('node:fs');
3
4
  const path = require('node:path');
4
5
 
5
6
  const {
@@ -18,11 +19,33 @@ const {
18
19
  } = require('./config');
19
20
  const { buildReport, collectTokenDefinitions } = require('./contract');
20
21
  const { DEFAULT_SCALE, formatPath } = require('./shared');
22
+ const { TAILWIND_SCALE_NAME, TAILWIND_SPACING_UNIT_REM, tailwindSpacingLadder } = require('../presets/default-scale');
23
+
24
+ const TAILWIND_CONFIG_FILES = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.mjs', 'tailwind.config.ts'];
25
+
26
+ /**
27
+ * Whether the project in `cwd` uses Tailwind: a `tailwindcss` or
28
+ * `@tailwindcss/*` dependency, or a Tailwind config file (found, not loaded).
29
+ * Its `--scale auto` fallback is then Tailwind's ladder, as in configs/tailwind.
30
+ */
31
+ function isTailwindProject(cwd) {
32
+ try {
33
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
34
+ const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies });
35
+ if (deps.some((name) => name === 'tailwindcss' || name.startsWith('@tailwindcss/'))) {
36
+ return true;
37
+ }
38
+ } catch {
39
+ // No readable package.json: decide by the config file alone.
40
+ }
41
+ return TAILWIND_CONFIG_FILES.some((file) => fs.existsSync(path.join(cwd, file)));
42
+ }
21
43
  const {
22
44
  assessScale,
23
45
  discoverTokenPackages,
24
46
  inferScaleFromDefinitions,
25
47
  scaleFromDefinitions,
48
+ scaleFromTailwindConfig,
26
49
  } = require('../core/scale-inference');
27
50
  const { buildGroupScales } = require('../core/options');
28
51
  const { applyDecisions, buildDecisionPlan } = require('./decisions');
@@ -33,14 +56,19 @@ const { nonAuthoredReason } = require('./non-authored');
33
56
  const { collectCssFindings, runStylelintAudit } = require('./scan/stylesheets');
34
57
  const { collectTailwindFindings, collectTailwindMotionFindings } = require('./scan/templates');
35
58
 
36
- async function createAuditReport(options) {
37
- const parsed = normalizeCreateAuditOptions(options);
59
+ /**
60
+ * What an audit run reads before it lints anything: the files, the token
61
+ * sources and the one resolved scale. `rhythmguard scale` prints the scale
62
+ * from here, so it always names the scale the audit would check against.
63
+ * `parsed` is the options after normalizeCreateAuditOptions.
64
+ */
65
+ function prepareAuditRun(parsed) {
38
66
  const resolvedDir = assertDirectory(parsed.dir);
39
67
  const ignorePatterns = resolveIgnorePatterns(parsed);
40
68
 
41
69
  const scanFiles = getScanFiles(resolvedDir, ignorePatterns, parsed);
42
70
 
43
- const { scanScope, templateFiles } = scanFiles;
71
+ const { templateFiles } = scanFiles;
44
72
  // A --staged run reads each changed file as the index holds it.
45
73
  const readSource = scanFiles.readSource || readSourceFromDisk;
46
74
 
@@ -63,6 +91,12 @@ async function createAuditReport(options) {
63
91
  warnWhenEmpty: true,
64
92
  });
65
93
 
94
+ // A configured Tailwind config that does not exist is a configuration error,
95
+ // as a missing token source is (the CLI exits 2 on either).
96
+ if (parsed.tailwindConfigPath && !fs.existsSync(path.resolve(process.cwd(), parsed.tailwindConfigPath))) {
97
+ tokenSourceResult.warnings.push(`Tailwind config not found: ${parsed.tailwindConfigPath}`);
98
+ }
99
+
66
100
  // The spacing scale always reads spacing tokens; --token-kind shapes the token contract only (issue #260).
67
101
  const spacingSourceResult = parsed.tokenKind === 'spacing'
68
102
  ? tokenSourceResult
@@ -72,15 +106,109 @@ async function createAuditReport(options) {
72
106
  // against, so it is the scale the report names and prefer-token reads (#283).
73
107
  const groupScales = buildGroupScales(parsed.scales);
74
108
  const spacingOverride = groupScales.spacing && Array.isArray(groupScales.spacing.scale) ? groupScales.spacing.scale : null;
109
+ const isNonAuthored = (file) => nonAuthored.has(file);
75
110
  const scale = resolveAuditScale({
76
111
  baseFontSize: parsed.baseFontSize,
77
112
  cssFiles,
78
- isNonAuthored: (file) => nonAuthored.has(file),
113
+ isNonAuthored,
79
114
  readSource,
80
115
  requested: spacingOverride || parsed.scale,
116
+ tailwindConfigPath: parsed.tailwindConfigPath,
81
117
  tokenSourceResult: spacingSourceResult,
118
+ // Loader warnings (a Tailwind config that throws) join the token source warnings (cq-05).
119
+ warnings: tokenSourceResult.warnings,
82
120
  });
83
121
 
122
+ // Class strings follow the ESLint rule: with no scale of the project's own
123
+ // (the default, or "auto" finding none), they are judged by Tailwind's
124
+ // default ladder, so the audit and `tailwind-class-use-scale` agree (cs-05).
125
+ const classScale = classStringScale(scale, templateFiles, parsed.baseFontSize);
126
+ if (classScale) {
127
+ scale.classStrings = classScale;
128
+ }
129
+
130
+ return {
131
+ classScale,
132
+ cssFiles,
133
+ groupScales,
134
+ isNonAuthored,
135
+ nonAuthored,
136
+ nonAuthoredSkipped,
137
+ readSource,
138
+ resolvedDir,
139
+ scale,
140
+ scanFiles,
141
+ spacingSourceResult,
142
+ templateFiles,
143
+ tokenSourceResult,
144
+ };
145
+ }
146
+
147
+ /**
148
+ * The places the audit knows spacing tokens from, as `scaleSources` entries
149
+ * for prefer-token: the configured token sources that exist, then every
150
+ * authored stylesheet that declares a spacing custom property or Sass token.
151
+ * prefer-token then names the token that holds a raw value, and the file it
152
+ * comes from, as the token contract does (dx-08, ci-01). A token declared in
153
+ * a component block or under a media query in another file is never offered
154
+ * outside it: the rule's token index keeps each declaration's scope.
155
+ */
156
+ function tokenScaleSources({ baseFontSize, cssFiles, isNonAuthored, readSource, tokenSources }) {
157
+ const entries = [];
158
+ for (const source of tokenSources || []) {
159
+ if (!source || typeof source !== 'object' || !source.path) {
160
+ continue;
161
+ }
162
+ const resolved = path.resolve(source.baseDir || process.cwd(), source.path);
163
+ if (!fs.existsSync(resolved)) {
164
+ continue;
165
+ }
166
+ entries.push({
167
+ format: source.format || 'auto',
168
+ path: resolved,
169
+ ...(source.tokenPattern ? { tokenPattern: source.tokenPattern } : {}),
170
+ });
171
+ }
172
+
173
+ const matchesKind = createTokenKindMatcher('spacing');
174
+ for (const filePath of cssFiles) {
175
+ if (isNonAuthored(filePath)) {
176
+ continue;
177
+ }
178
+ let text;
179
+ try {
180
+ text = readSource(filePath);
181
+ } catch {
182
+ // Unreadable since the scan (deleted, permissions): this pass reads only what it can.
183
+ continue;
184
+ }
185
+ const definitions = new Map();
186
+ collectTokenDefinitions(text, formatPath(filePath), definitions, matchesKind, baseFontSize);
187
+ if (definitions.size > 0) {
188
+ entries.push({ format: 'css', path: path.resolve(filePath) });
189
+ }
190
+ }
191
+ return entries;
192
+ }
193
+
194
+ async function createAuditReport(options) {
195
+ const parsed = normalizeCreateAuditOptions(options);
196
+ const run = prepareAuditRun(parsed);
197
+ const {
198
+ classScale,
199
+ cssFiles,
200
+ groupScales,
201
+ nonAuthored,
202
+ nonAuthoredSkipped,
203
+ readSource,
204
+ resolvedDir,
205
+ scale,
206
+ scanFiles,
207
+ templateFiles,
208
+ tokenSourceResult,
209
+ } = run;
210
+ const { scanScope } = scanFiles;
211
+
84
212
  const lintOptions = {
85
213
  baseFontSize: parsed.baseFontSize,
86
214
  checkMathBounds: parsed.checkMathBounds,
@@ -88,8 +216,17 @@ async function createAuditReport(options) {
88
216
  readSource: scanFiles.readSource,
89
217
  scale: scale.values,
90
218
  scales: parsed.scales,
219
+ tokenScaleSources: tokenScaleSources({
220
+ baseFontSize: parsed.baseFontSize,
221
+ cssFiles,
222
+ isNonAuthored: run.isNonAuthored,
223
+ readSource,
224
+ tokenSources: parsed.tokenSources,
225
+ }),
91
226
  };
92
227
 
228
+ const classOptions = classScale ? { ...lintOptions, scale: classScale.values } : lintOptions;
229
+
93
230
  const cssResults = await runStylelintAudit(cssFiles, lintOptions);
94
231
  const collectedCssFindings = collectCssFindings(cssResults, readSource);
95
232
  // A stylesheet that failed to parse was not audited; it is reported apart
@@ -100,7 +237,7 @@ async function createAuditReport(options) {
100
237
  baseFontSize: parsed.baseFontSize,
101
238
  cssFindings: stylelintFindings.filter((finding) => !finding.type.startsWith('motion-')),
102
239
  decisions: parsed.decisions || [],
103
- tailwindFindings: collectTailwindFindings(templateFiles, lintOptions),
240
+ tailwindFindings: collectTailwindFindings(templateFiles, classOptions),
104
241
  });
105
242
  const cssFindings = decided.cssFindings;
106
243
  const motionFindings = [
@@ -108,6 +245,9 @@ async function createAuditReport(options) {
108
245
  ...collectTailwindMotionFindings(templateFiles, lintOptions),
109
246
  ];
110
247
 
248
+ // Every token a chain can end in: token sources of any kind and installed
249
+ // token packages. Read once, for the chains and for missing tokens.
250
+ const knownDefinitions = chainDefinitions(parsed);
111
251
  const report = buildReport({
112
252
  baseFontSize: parsed.baseFontSize,
113
253
  config: parsed.config,
@@ -116,24 +256,37 @@ async function createAuditReport(options) {
116
256
  dir: parsed.dir,
117
257
  externalTokenDefinitions: tokenSourceResult.definitions,
118
258
  includeMotion: parsed.includeMotion,
259
+ knownTokens: parsed.reportMissingTokens === true
260
+ ? knownTokenNames(knownDefinitions, nonAuthoredSkipped, readSource)
261
+ : new Set(),
119
262
  linksOutsideRoot: scanFiles.linksOutsideRoot || [],
120
263
  motionFindings,
121
264
  nonAuthoredFiles: nonAuthoredSkipped.map((file) => ({ file: formatPath(file), reason: nonAuthored.get(file) })),
122
265
  parseErrorFindings,
123
266
  readSource,
267
+ reportMissingTokens: parsed.reportMissingTokens === true,
124
268
  scale,
125
269
  scanScope,
126
270
  scssFiles: cssResults.scssFiles || 0,
127
271
  scssSkipped: cssResults.scssSkipped || 0,
128
272
  stylelintIgnored: cssResults.stylelintIgnored || 0,
273
+ stylelintMissing: cssResults.stylelintMissing || 0,
129
274
  tailwindFindings: decided.tailwindFindings,
130
275
  templateFiles,
131
276
  tokenCandidateMinCount: parsed.tokenCandidateMinCount,
132
277
  tokenKind: parsed.tokenKind,
133
278
  tokenSourceReports: tokenSourceResult.sources,
134
279
  tokenSourceWarnings: tokenSourceResult.warnings,
280
+ unauditedFiles: new Set([
281
+ ...(cssResults.unauditedFiles || []),
282
+ ...parseErrorFindings.map((finding) => path.resolve(process.cwd(), finding.file)),
283
+ ]),
135
284
  });
136
285
 
286
+ // The files this run scanned, for the CLI's next-step commands (lint globs,
287
+ // parsers). Not enumerable, so no JSON output carries the lists.
288
+ Object.defineProperty(report, 'files', { enumerable: false, value: { cssFiles: [...cssFiles], templateFiles: [...templateFiles] } });
289
+
137
290
  const declarations = collectDeclarations({
138
291
  cssFiles,
139
292
  externalDefinitions: tokenSourceResult.definitions,
@@ -143,7 +296,7 @@ async function createAuditReport(options) {
143
296
  report.tokenContract.chains = toChainsContract(resolveTokenChains({
144
297
  baseFontSize: parsed.baseFontSize,
145
298
  declarations,
146
- references: collectDeclarations({ cssFiles: [], externalDefinitions: chainDefinitions(parsed) }),
299
+ references: collectDeclarations({ cssFiles: [], externalDefinitions: knownDefinitions }),
147
300
  scale: scale.values,
148
301
  }));
149
302
  report.tokenContract.ladders = toLaddersContract(resolveTokenLadders({
@@ -158,7 +311,7 @@ async function createAuditReport(options) {
158
311
  groupScales,
159
312
  offScaleFindings: [
160
313
  ...stylelintFindings.filter((finding) => finding.type === 'off-scale'),
161
- ...collectTailwindFindings(templateFiles, lintOptions),
314
+ ...collectTailwindFindings(templateFiles, classOptions),
162
315
  ],
163
316
  scale: scale.values,
164
317
  });
@@ -190,6 +343,31 @@ async function createAuditReport(options) {
190
343
  return report;
191
344
  }
192
345
 
346
+ /**
347
+ * Token names defined outside the token contract's own definitions: token
348
+ * sources of any kind, installed token packages, and the vendored or built
349
+ * stylesheets the audit skips. A `var()` of one of these is not a missing token.
350
+ */
351
+ function knownTokenNames(knownDefinitions, skippedCssFiles, readSource) {
352
+ const names = new Set(knownDefinitions.keys());
353
+ const matchesAll = createTokenKindMatcher('all');
354
+ for (const filePath of skippedCssFiles) {
355
+ let text;
356
+ try {
357
+ text = readSource(filePath);
358
+ } catch {
359
+ // Unreadable since the scan (deleted, permissions): this pass reads only what it can.
360
+ continue;
361
+ }
362
+ const definitions = new Map();
363
+ collectTokenDefinitions(text, formatPath(filePath), definitions, matchesAll, 16);
364
+ for (const token of definitions.keys()) {
365
+ names.add(token);
366
+ }
367
+ }
368
+ return names;
369
+ }
370
+
193
371
  /**
194
372
  * Every custom property a chain can end in: all tokens in the token sources,
195
373
  * whatever --token-kind says and whatever name pattern a source sets, plus
@@ -224,12 +402,28 @@ function classifyNonAuthored(cssFiles, rootDir, readSource) {
224
402
  return classified;
225
403
  }
226
404
 
405
+ /**
406
+ * The scale class strings are checked against when it differs from the
407
+ * stylesheet scale: Tailwind's default ladder, when the stylesheet scale is the
408
+ * built-in default or the fallback and there are template files to check.
409
+ */
410
+ function classStringScale(scale, templateFiles, baseFontSize) {
411
+ if (templateFiles.length === 0 || (scale.source !== 'default' && scale.source !== 'fallback')) {
412
+ return null;
413
+ }
414
+ return {
415
+ name: TAILWIND_SCALE_NAME,
416
+ source: 'tailwind-default',
417
+ values: tailwindSpacingLadder(baseFontSize * TAILWIND_SPACING_UNIT_REM),
418
+ };
419
+ }
420
+
227
421
  /**
228
422
  * One project-level scale for the whole audit, with provenance.
229
423
  * "auto": external token sources, then spacing custom properties across the scanned
230
424
  * CSS, then the default scale. First source that yields values wins.
231
425
  */
232
- function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false, readSource = readSourceFromDisk, requested, tokenSourceResult }) {
426
+ function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false, readSource = readSourceFromDisk, requested, tailwindConfigPath = null, tokenSourceResult, warnings = [] }) {
233
427
  if (Array.isArray(requested)) {
234
428
  return {
235
429
  files: [],
@@ -251,7 +445,18 @@ function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false
251
445
  }
252
446
  }
253
447
 
448
+ // Configured token sources that gave no scale are a rejection with reasons,
449
+ // as an inferred set is, not a silent fallback (tf-02).
254
450
  let rejected = null;
451
+ if (tokenSourceResult.sources.length > 0) {
452
+ const reasons = tokenSourceResult.sources.flatMap((source) => source.warnings || []);
453
+ rejected = {
454
+ files: tokenSourceResult.sources.map((source) => source.file),
455
+ reasons: reasons.length > 0 ? reasons : ['no spacing token carries a length'],
456
+ source: 'token-sources',
457
+ values: [],
458
+ };
459
+ }
255
460
  const definitions = new Map();
256
461
  const matchesKind = createTokenKindMatcher('spacing');
257
462
  for (const filePath of cssFiles) {
@@ -264,6 +469,7 @@ function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false
264
469
  try {
265
470
  text = readSource(filePath);
266
471
  } catch {
472
+ // Unreadable since the scan (deleted, permissions): this pass reads only what it can.
267
473
  continue;
268
474
  }
269
475
  collectTokenDefinitions(text, formatPath(filePath), definitions, matchesKind, baseFontSize);
@@ -289,7 +495,15 @@ function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false
289
495
  values,
290
496
  };
291
497
  }
292
- rejected = { files: sortedFiles, reasons: assessment.reasons, source: 'scanned-css', values };
498
+ rejected = rejected || { files: sortedFiles, reasons: assessment.reasons, source: 'scanned-css', values };
499
+ }
500
+ }
501
+
502
+ // A Tailwind v3 config, only when one is configured: loading it runs it (tf-06).
503
+ if (tailwindConfigPath && fs.existsSync(path.resolve(process.cwd(), tailwindConfigPath))) {
504
+ const values = scaleFromTailwindConfig(path.resolve(process.cwd(), tailwindConfigPath), baseFontSize, { warnings });
505
+ if (values) {
506
+ return { files: [formatPath(path.resolve(process.cwd(), tailwindConfigPath))], source: 'tailwind', tokenCount: values.length - 1, values };
293
507
  }
294
508
  }
295
509
 
@@ -307,7 +521,16 @@ function resolveAuditScale({ baseFontSize, cssFiles, isNonAuthored = () => false
307
521
  }
308
522
  }
309
523
 
310
- return { files: [], ...(rejected ? { rejected } : {}), source: 'fallback', tokenCount: 0, values: DEFAULT_SCALE };
524
+ // The fallback the rules use: configs/tailwind falls back to Tailwind's ladder, the rest to DEFAULT_SCALE.
525
+ const tailwind = isTailwindProject(process.cwd());
526
+ return {
527
+ files: [],
528
+ preset: tailwind ? 'tailwind' : 'rhythmic-4',
529
+ ...(rejected ? { rejected } : {}),
530
+ source: 'fallback',
531
+ tokenCount: 0,
532
+ values: tailwind ? tailwindSpacingLadder(baseFontSize * TAILWIND_SPACING_UNIT_REM) : DEFAULT_SCALE,
533
+ };
311
534
  }
312
535
 
313
536
  function normalizeCreateAuditOptions(rawOptions) {
@@ -343,4 +566,6 @@ function normalizeCreateAuditOptions(rawOptions) {
343
566
  module.exports = {
344
567
  createAuditReport,
345
568
  normalizeCreateAuditOptions,
569
+ prepareAuditRun,
570
+ tokenScaleSources,
346
571
  };
@@ -59,6 +59,7 @@ function walkFiles(rootDir, ignorePatterns = []) {
59
59
  try {
60
60
  kind = fs.statSync(fullPath);
61
61
  } catch {
62
+ // A dangling symbolic link: nothing to scan.
62
63
  continue;
63
64
  }
64
65
  }
@@ -123,6 +124,7 @@ function realPathOf(filePath) {
123
124
  try {
124
125
  return fs.realpathSync(filePath);
125
126
  } catch {
127
+ // A path that cannot be resolved has no real path.
126
128
  return null;
127
129
  }
128
130
  }
@@ -247,6 +249,7 @@ function isFileOnDisk(filePath) {
247
249
  try {
248
250
  return fs.statSync(filePath).isFile();
249
251
  } catch {
252
+ // Absent or unreadable: not a file.
250
253
  return false;
251
254
  }
252
255
  }
@@ -255,6 +258,7 @@ function isSymbolicLink(filePath) {
255
258
  try {
256
259
  return fs.lstatSync(filePath).isSymbolicLink();
257
260
  } catch {
261
+ // Absent: not a link.
258
262
  return false;
259
263
  }
260
264
  }
@@ -351,6 +355,7 @@ function findGitTopLevel(dir) {
351
355
  }).replace(/\r?\n$/, '');
352
356
  return output ? path.resolve(output) : null;
353
357
  } catch {
358
+ // Not a git repository, or no git: there is no repository root.
354
359
  return null;
355
360
  }
356
361
  }