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.
- package/CHANGELOG.md +68 -0
- package/CONTRIBUTING.md +2 -2
- package/README.md +4 -4
- package/SECURITY.md +14 -0
- package/agents/claude-code/SKILL.md +14 -1
- package/agents/copilot/{copilot-instructions.md → rhythmguard.instructions.md} +7 -1
- package/agents/cursor/rhythmguard.mdc +5 -3
- package/package.json +2 -2
- package/src/audit/args.js +30 -8
- package/src/audit/baseline.js +44 -2
- package/src/audit/codemod.js +2 -0
- package/src/audit/config.js +7 -0
- package/src/audit/contract.js +131 -17
- package/src/audit/next-steps.js +86 -0
- package/src/audit/non-authored.js +1 -0
- package/src/audit/render-github.js +52 -15
- package/src/audit/render-markdown.js +58 -17
- package/src/audit/render-text.js +76 -6
- package/src/audit/render-utils.js +14 -0
- package/src/audit/report.js +235 -10
- package/src/audit/scan/files.js +5 -0
- package/src/audit/scan/stylesheets.js +63 -59
- package/src/audit/scan/templates.js +2 -0
- package/src/audit/shared.js +7 -1
- package/src/audit/token-chains.js +1 -0
- package/src/cli/audit.js +20 -11
- package/src/cli/doctor.js +853 -237
- package/src/cli/first-run.js +210 -0
- package/src/cli/index.js +25 -1
- package/src/cli/index.mjs +3 -0
- package/src/cli/init.js +75 -26
- package/src/cli/quickstart.js +109 -118
- package/src/cli/scale.js +223 -0
- package/src/configs/recommended.js +3 -1
- package/src/configs/strict.js +3 -1
- package/src/configs/tailwind.js +15 -0
- package/src/core/decisions.js +18 -5
- package/src/core/fs-cache.js +1 -0
- package/src/core/options.js +2 -1
- package/src/core/scale-inference.js +72 -52
- package/src/core/tailwind-class-analysis.js +56 -13
- package/src/core/token-index.js +55 -14
- package/src/core/token-map.js +140 -88
- package/src/core/token-sources.js +461 -40
- package/src/core/value-nodes.js +4 -2
- package/src/eslint/class-context.js +330 -0
- package/src/eslint/literal-spans.js +5 -4
- package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
- package/src/presets/default-scale.js +42 -0
- package/src/presets/scales.js +6 -1
- package/src/rules/no-offscale-transform/index.js +17 -5
- package/src/rules/prefer-token/index.js +51 -15
- package/src/rules/use-scale/index.js +7 -4
- package/types/__checks__/consumer.ts +17 -0
- package/types/__checks__/eslint-config.ts +5 -0
- package/types/audit.d.ts +42 -3
- package/types/cli.d.ts +77 -1
- package/types/shared.d.ts +10 -0
package/src/cli/quickstart.js
CHANGED
|
@@ -9,12 +9,20 @@
|
|
|
9
9
|
* process on findings; this is a report, not a gate.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
const fs = require('node:fs');
|
|
13
12
|
const path = require('node:path');
|
|
14
13
|
|
|
15
|
-
const {
|
|
14
|
+
const { auditCommand, eslintInstallLine, lintGlob, stylelintInstallLine } = require('../audit/next-steps');
|
|
16
15
|
const { detect } = require('./init');
|
|
17
16
|
const { discoverTokenPackages } = require('../core/scale-inference');
|
|
17
|
+
const {
|
|
18
|
+
RC_FILE,
|
|
19
|
+
findTokenFiles,
|
|
20
|
+
inferFirstRun,
|
|
21
|
+
rcFor,
|
|
22
|
+
stylelintConfigFor,
|
|
23
|
+
tailwindMajor,
|
|
24
|
+
toPosix,
|
|
25
|
+
} = require('./first-run');
|
|
18
26
|
|
|
19
27
|
const HELP = `Usage: rhythmguard [quickstart]
|
|
20
28
|
|
|
@@ -26,120 +34,68 @@ Options:
|
|
|
26
34
|
--help Show this help message
|
|
27
35
|
`;
|
|
28
36
|
|
|
29
|
-
const TOKEN_FILE_PATTERN = /(^|[.-])tokens?\.json$/i;
|
|
30
|
-
const TOKEN_DIRS = ['tokens', 'design-tokens', path.join('src', 'tokens'), path.join('dist', 'tokens')];
|
|
31
37
|
const MAX_LISTED = 5;
|
|
32
38
|
|
|
33
|
-
function readPackage(cwd) {
|
|
34
|
-
try {
|
|
35
|
-
return JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
|
|
36
|
-
} catch {
|
|
37
|
-
return {};
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function tailwindMajor(pkg) {
|
|
42
|
-
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
43
|
-
if (deps['@tailwindcss/postcss'] || deps['@tailwindcss/vite']) {
|
|
44
|
-
return 4;
|
|
45
|
-
}
|
|
46
|
-
const spec = deps.tailwindcss;
|
|
47
|
-
if (!spec) {
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
const match = String(spec).match(/(\d+)/);
|
|
51
|
-
return match ? Number(match[1]) : null;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function findTokenFiles(cwd) {
|
|
55
|
-
const found = new Set();
|
|
56
|
-
const consider = (dir) => {
|
|
57
|
-
let entries;
|
|
58
|
-
try {
|
|
59
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
60
|
-
} catch {
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
for (const entry of entries) {
|
|
64
|
-
if (entry.isFile() && TOKEN_FILE_PATTERN.test(entry.name)) {
|
|
65
|
-
found.add(path.relative(cwd, path.join(dir, entry.name)));
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
consider(cwd);
|
|
70
|
-
for (const sub of TOKEN_DIRS) {
|
|
71
|
-
consider(path.join(cwd, sub));
|
|
72
|
-
}
|
|
73
|
-
return Array.from(found).sort();
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function hasRhythmguardConfig(cwd) {
|
|
77
|
-
return fs.existsSync(path.join(cwd, '.rhythmguardrc.json'));
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function toPosix(relativePath) {
|
|
81
|
-
return `./${relativePath.split(path.sep).join('/')}`;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
39
|
function topEntries(counts, limit = MAX_LISTED) {
|
|
85
40
|
return Object.entries(counts || {})
|
|
86
41
|
.sort((a, b) => b[1] - a[1])
|
|
87
42
|
.slice(0, limit);
|
|
88
43
|
}
|
|
89
44
|
|
|
45
|
+
/** The config to paste; kept under its 3.x name for callers of this module. */
|
|
46
|
+
function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profile, scss = false, tokenFiles }) {
|
|
47
|
+
const scale = Array.isArray(fallbackScale)
|
|
48
|
+
? { files: [], source: 'fallback', values: fallbackScale }
|
|
49
|
+
: { files: tokenFiles, source: 'token-sources', values: [] };
|
|
50
|
+
return stylelintConfigFor({ nextjs, profile, scale, scss, tokenFiles });
|
|
51
|
+
}
|
|
52
|
+
|
|
90
53
|
/**
|
|
91
|
-
* The config
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
* `scale: "auto"` would fall back to the `rhythmic-4` preset instead, which is
|
|
95
|
-
* a longer scale, and the pasted config would not reproduce this report (#246).
|
|
54
|
+
* The eslint.config.js block. It imports the package the printed install line
|
|
55
|
+
* installs. With TypeScript files it lints .ts and .tsx through typescript-eslint's
|
|
56
|
+
* parser: the default parser reads no TSX, so a JS-only block linted nothing (dx-04).
|
|
96
57
|
*/
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if (!fallbackScale && tokenFiles.length > 0) {
|
|
100
|
-
ruleOptions.scaleSources = tokenFiles.map(toPosix);
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
extends: [`stylelint-plugin-rhythmguard/configs/${profile}`],
|
|
104
|
-
...(nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
|
|
105
|
-
rules: {
|
|
106
|
-
'rhythmguard/use-scale': [true, ruleOptions],
|
|
107
|
-
},
|
|
108
|
-
};
|
|
109
|
-
}
|
|
58
|
+
// Written this way so the snippet's import lines are not read as imports of this file.
|
|
59
|
+
const quoted = (name) => `'${name}'`;
|
|
110
60
|
|
|
111
|
-
function eslintSnippet(scaleValues) {
|
|
112
|
-
|
|
61
|
+
function eslintSnippet(scaleValues, { typescript = false } = {}) {
|
|
62
|
+
// No project scale: the rule's default, Tailwind's ladder, which the audit
|
|
63
|
+
// also checked class strings against (cs-05).
|
|
64
|
+
const options = Array.isArray(scaleValues)
|
|
65
|
+
? `, { scale: [${scaleValues.filter((value) => typeof value === 'number').join(', ')}] }`
|
|
66
|
+
: '';
|
|
113
67
|
return [
|
|
114
68
|
"// eslint.config.js",
|
|
115
|
-
|
|
69
|
+
`import rhythmguard from ${quoted('eslint-plugin-rhythmguard')};`,
|
|
70
|
+
...(typescript ? [`import tseslint from ${quoted('typescript-eslint')};`] : []),
|
|
116
71
|
'',
|
|
117
72
|
'export default [',
|
|
118
73
|
' {',
|
|
119
74
|
// Without `files` and JSX parsing, a flat config lints no .jsx at all (#243).
|
|
120
|
-
" files: ['**/*.{js,jsx,mjs,cjs}'],",
|
|
121
|
-
|
|
75
|
+
typescript ? " files: ['**/*.{js,jsx,mjs,cjs,ts,tsx}']," : " files: ['**/*.{js,jsx,mjs,cjs}'],",
|
|
76
|
+
typescript
|
|
77
|
+
? ' languageOptions: { parser: tseslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },'
|
|
78
|
+
: ' languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },',
|
|
122
79
|
" plugins: { 'rhythmguard-tailwind': rhythmguard },",
|
|
123
|
-
` rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['warn'
|
|
80
|
+
` rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['warn'${options}] },`,
|
|
124
81
|
' },',
|
|
125
82
|
'];',
|
|
126
83
|
].join('\n');
|
|
127
84
|
}
|
|
128
85
|
|
|
129
|
-
function shellQuote(value) {
|
|
130
|
-
return /^[\w./@%+=:,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
86
|
/**
|
|
134
87
|
* The commands to run next. The audit commands pass what quickstart passed,
|
|
135
88
|
* `--scale auto` and the token files it read, so they report the same scale
|
|
136
89
|
* and the same findings; `audit .` alone would use the default scale (#287).
|
|
137
90
|
*/
|
|
138
|
-
function nextCommands(tokenSources) {
|
|
139
|
-
const audit =
|
|
91
|
+
function nextCommands(tokenSources, { eslint = false, glob = '**/*.css', stylelint = true, tailwindConfig = null } = {}) {
|
|
92
|
+
const audit = auditCommand({ dir: '.', scale: 'auto', tailwindConfig: tailwindConfig ? toPosix(tailwindConfig) : null, tokenSources: tokenSources.map(toPosix) });
|
|
140
93
|
// Each note on its own line above its command, so a long command copies whole.
|
|
141
94
|
return [
|
|
142
|
-
['Lint with the config above:',
|
|
95
|
+
...(stylelint ? [['Lint stylesheets with the config above:', `npx stylelint "${glob}"`]] : []),
|
|
96
|
+
...(eslint ? [['Lint class strings with the ESLint config above:', 'npx eslint .']] : []),
|
|
97
|
+
// Snapping a value can move layout: decide per value, then rewrite (dx-11).
|
|
98
|
+
['Propose one decision per off-scale value, before changing any:', `${audit} --plan`],
|
|
143
99
|
['PR-ready report:', `${audit} --format markdown`],
|
|
144
100
|
['Then gate only new drift in CI, with the same flags:', `${audit} --write-baseline`],
|
|
145
101
|
['Check the setup:', 'npx rhythmguard doctor'],
|
|
@@ -167,12 +123,17 @@ async function run() {
|
|
|
167
123
|
}
|
|
168
124
|
|
|
169
125
|
const cwd = process.cwd();
|
|
170
|
-
const pkg = readPackage(cwd);
|
|
171
126
|
const stack = detect();
|
|
172
|
-
const twMajor = stack.tailwind ? tailwindMajor(pkg) : null;
|
|
173
|
-
const tokenFiles = findTokenFiles(cwd);
|
|
174
|
-
const rcPresent = hasRhythmguardConfig(cwd);
|
|
175
127
|
const out = [];
|
|
128
|
+
let inferred;
|
|
129
|
+
try {
|
|
130
|
+
inferred = await inferFirstRun({ cwd, stack });
|
|
131
|
+
} catch (error) {
|
|
132
|
+
process.stderr.write(`Quickstart could not audit ${cwd}: ${error.message}\n`);
|
|
133
|
+
process.exitCode = 1;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const { auditTokenSources, rcPresent, report, tailwindConfig, tokenFiles, twMajor } = inferred;
|
|
176
137
|
|
|
177
138
|
out.push('', ' Rhythmguard quickstart', ` ${cwd}`, '');
|
|
178
139
|
out.push(' Detected');
|
|
@@ -183,28 +144,18 @@ async function run() {
|
|
|
183
144
|
const tokenPackages = [...new Set(discoverTokenPackages(cwd).map((source) => source.package))];
|
|
184
145
|
out.push(` Token packages ${tokenPackages.length > 0 ? tokenPackages.join(', ') : 'none installed'}`);
|
|
185
146
|
out.push(` .rhythmguardrc ${rcPresent ? 'present (its token sources are used)' : 'none'}`);
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
// With an rc file its token sources are used; otherwise the token files found here.
|
|
189
|
-
const auditTokenSources = rcPresent ? [] : tokenFiles;
|
|
190
|
-
let report;
|
|
191
|
-
try {
|
|
192
|
-
report = await createAuditReport({
|
|
193
|
-
dir: '.',
|
|
194
|
-
scale: 'auto',
|
|
195
|
-
...(auditTokenSources.length > 0 ? { tokenSources: auditTokenSources } : {}),
|
|
196
|
-
});
|
|
197
|
-
} catch (error) {
|
|
198
|
-
process.stderr.write(`Quickstart could not audit ${cwd}: ${error.message}\n`);
|
|
199
|
-
process.exitCode = 1;
|
|
200
|
-
return;
|
|
147
|
+
if (tailwindConfig) {
|
|
148
|
+
out.push(` Tailwind config ${tailwindConfig} (not loaded here: loading it runs it; the config below reads it)`);
|
|
201
149
|
}
|
|
150
|
+
out.push('');
|
|
202
151
|
|
|
203
152
|
const scanned = report.scanned || {};
|
|
204
|
-
const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0);
|
|
153
|
+
const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0) + (scanned.stylelintMissing || 0);
|
|
154
|
+
// An ESLint-only project: class strings were audited, stylesheets were not.
|
|
155
|
+
const withoutStylelint = (scanned.stylelintMissing || 0) > 0;
|
|
205
156
|
if (report.cssFilesScanned === 0 && report.templateFilesScanned === 0 && skippedStylesheets === 0) {
|
|
206
157
|
out.push(' No CSS files found here. Run from your project root, or audit a directory directly:');
|
|
207
|
-
out.push(' npx rhythmguard audit
|
|
158
|
+
out.push(' npx rhythmguard audit <directory>', '');
|
|
208
159
|
process.stdout.write(`${out.join('\n')}\n`);
|
|
209
160
|
return;
|
|
210
161
|
}
|
|
@@ -216,10 +167,20 @@ async function run() {
|
|
|
216
167
|
if (scale.source === 'fallback' && scale.rejected) {
|
|
217
168
|
out.push(` Note Spacing tokens were found but do not form a scale (${scale.rejected.reasons.join(', ')}); the audit's default scale is being used.`);
|
|
218
169
|
out.push(' Point scaleSources at your real token file, or tighten tokenPattern.');
|
|
170
|
+
} else if (scale.source === 'fallback' && tailwindConfig) {
|
|
171
|
+
out.push(` Note No spacing tokens found; the default scale is shown. The config below reads ${tailwindConfig};`);
|
|
172
|
+
out.push(` audit with it: npx rhythmguard audit . --scale auto --tailwind-config ${toPosix(tailwindConfig)}`);
|
|
219
173
|
} else if (scale.source === 'fallback') {
|
|
220
174
|
out.push(" Note No spacing tokens found; the audit's default scale is being used.");
|
|
221
175
|
out.push(' Add scaleSources or define --space-*/--spacing-* custom properties to lint against your own scale.');
|
|
222
176
|
}
|
|
177
|
+
// Every loader warning, so a token file that was found but not read says why (tf-12).
|
|
178
|
+
for (const warning of new Set(report.tokenSourceWarnings || [])) {
|
|
179
|
+
out.push(` ! ${warning}`);
|
|
180
|
+
}
|
|
181
|
+
if (scale.classStrings) {
|
|
182
|
+
out.push(` Class strings ${scale.classStrings.name} (the ESLint rule's default)`);
|
|
183
|
+
}
|
|
223
184
|
out.push('');
|
|
224
185
|
|
|
225
186
|
const offScale = report.findings.css.filter((finding) => finding.type === 'off-scale');
|
|
@@ -228,6 +189,7 @@ async function run() {
|
|
|
228
189
|
out.push(` Template files ${report.templateFilesScanned}`);
|
|
229
190
|
if (skippedStylesheets > 0) {
|
|
230
191
|
const reasons = [
|
|
192
|
+
...(withoutStylelint ? [`${scanned.stylelintMissing} because Stylelint is not installed`] : []),
|
|
231
193
|
...(scanned.scssSkipped > 0 ? [`${scanned.scssSkipped} SCSS without postcss-scss`] : []),
|
|
232
194
|
...(scanned.stylelintIgnored > 0 ? [`${scanned.stylelintIgnored} in .stylelintignore`] : []),
|
|
233
195
|
...(scanned.nonAuthoredSkipped > 0 ? [`${scanned.nonAuthoredSkipped} vendored, minified or built`] : []),
|
|
@@ -256,21 +218,50 @@ async function run() {
|
|
|
256
218
|
out.push('');
|
|
257
219
|
|
|
258
220
|
const profile = stack.tailwind ? 'tailwind' : 'recommended';
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
out.push(
|
|
267
|
-
out.push(
|
|
268
|
-
out.push('
|
|
221
|
+
const files = report.files || { cssFiles: [], templateFiles: [] };
|
|
222
|
+
const scss = files.cssFiles.some((file) => file.endsWith('.scss'));
|
|
223
|
+
const templateExtensions = new Set(files.templateFiles.map((file) => path.extname(file)));
|
|
224
|
+
const typescript = templateExtensions.has('.ts') || templateExtensions.has('.tsx');
|
|
225
|
+
const otherTemplates = ['.vue', '.svelte', '.astro'].filter((extension) => templateExtensions.has(extension));
|
|
226
|
+
const glob = lintGlob(cwd, files.cssFiles);
|
|
227
|
+
const printStylelint = () => {
|
|
228
|
+
out.push(withoutStylelint ? ' To audit your stylesheets too, install Stylelint and the plugin:' : ' Install:', '');
|
|
229
|
+
out.push(` ${stylelintInstallLine({ scss, tailwindConfig: profile === 'tailwind' })}`, '');
|
|
230
|
+
out.push(` ${withoutStylelint ? 'then paste' : 'Then paste'} this into .stylelintrc.json${stack.hasExistingConfig ? ' (merge with your existing config)' : ''}:`, '');
|
|
231
|
+
out.push(JSON.stringify(stylelintConfigFor({ nextjs: stack.nextjs, profile, scale, scss, tailwindConfig, tokenFiles }), null, 2).replace(/^/gm, ' '));
|
|
232
|
+
out.push('');
|
|
233
|
+
if (!rcPresent) {
|
|
234
|
+
// So a bare `npx rhythmguard audit .`, CI and an agent use this scale too (ai-01).
|
|
235
|
+
out.push(` And this into ${RC_FILE}, so \`npx rhythmguard audit .\` uses the same scale:`, '');
|
|
236
|
+
out.push(JSON.stringify(rcFor({ tailwindConfig, tokenFiles }), null, 2).replace(/^/gm, ' '));
|
|
237
|
+
out.push('');
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
const printEslint = () => {
|
|
241
|
+
out.push(' Tailwind class strings need the ESLint companion. Install:', '');
|
|
242
|
+
out.push(` ${eslintInstallLine({ typescript })}`, '');
|
|
243
|
+
out.push(' Then paste this into eslint.config.js:', '');
|
|
244
|
+
out.push(eslintSnippet(scale.classStrings ? null : scale.values, { typescript }).replace(/^/gm, ' '));
|
|
245
|
+
if (otherTemplates.length > 0) {
|
|
246
|
+
out.push('', ` ${otherTemplates.join(', ')} files need their parser in a block of their own; see the`);
|
|
247
|
+
out.push(' eslint-plugin-rhythmguard README, "Other file types".');
|
|
248
|
+
}
|
|
269
249
|
out.push('');
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// Without Stylelint the class strings are what was audited, so their config comes first.
|
|
253
|
+
if (stack.tailwind && withoutStylelint) {
|
|
254
|
+
printEslint();
|
|
255
|
+
printStylelint();
|
|
256
|
+
} else {
|
|
257
|
+
printStylelint();
|
|
258
|
+
if (stack.tailwind) {
|
|
259
|
+
printEslint();
|
|
260
|
+
}
|
|
270
261
|
}
|
|
271
262
|
|
|
272
263
|
out.push(' Next');
|
|
273
|
-
out.push(...nextCommands(auditTokenSources).map((line) => ` ${line}`));
|
|
264
|
+
out.push(...nextCommands(auditTokenSources, { eslint: stack.tailwind, glob, stylelint: !withoutStylelint, tailwindConfig }).map((line) => ` ${line}`));
|
|
274
265
|
out.push('');
|
|
275
266
|
|
|
276
267
|
process.stdout.write(`${out.join('\n')}\n`);
|
package/src/cli/scale.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `rhythmguard scale`: the scale the audit would check against, where it came
|
|
5
|
+
* from, and the tokens that hold each step, without scanning for findings
|
|
6
|
+
* (ai-04). It resolves the scale through the audit's own path (flags,
|
|
7
|
+
* `.rhythmguardrc.json`, `--scale auto`), so the two never disagree.
|
|
8
|
+
*/
|
|
9
|
+
const { OPTIONS, parseArgs, renderOptionLines } = require('../audit/args');
|
|
10
|
+
const { normalizeCreateAuditOptions, prepareAuditRun, tokenScaleSources } = require('../audit/report');
|
|
11
|
+
const { formatLength, parseLengthToken, toPx } = require('../core/length');
|
|
12
|
+
const { discoverTokenPackages } = require('../core/scale-inference');
|
|
13
|
+
const { tokenIndexFromDefinitions } = require('../core/token-index');
|
|
14
|
+
const { parseTokenSources } = require('../core/token-sources');
|
|
15
|
+
|
|
16
|
+
const SCALE_FLAGS = new Set([
|
|
17
|
+
'--format',
|
|
18
|
+
'--json',
|
|
19
|
+
'--config',
|
|
20
|
+
'--no-config',
|
|
21
|
+
'--ignore',
|
|
22
|
+
'--ignore-path',
|
|
23
|
+
'--include-non-authored',
|
|
24
|
+
'--token-source',
|
|
25
|
+
'--token-source-format',
|
|
26
|
+
'--scale',
|
|
27
|
+
'--base-font-size',
|
|
28
|
+
'--help',
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const SCALE_OPTIONS = OPTIONS
|
|
32
|
+
.filter((option) => SCALE_FLAGS.has(option.flag))
|
|
33
|
+
.map((option) => (option.flag === '--format'
|
|
34
|
+
? { ...option, value: '<text|json>', help: 'Output format (default: text)' }
|
|
35
|
+
: option));
|
|
36
|
+
|
|
37
|
+
const SCALE_FORMATS = new Set(['text', 'json']);
|
|
38
|
+
|
|
39
|
+
const HELP = [
|
|
40
|
+
'Usage: rhythmguard scale [dir] [options]',
|
|
41
|
+
'',
|
|
42
|
+
'Print the spacing scale `rhythmguard audit` would check <dir> against (default: .),',
|
|
43
|
+
'where it came from, and the tokens that hold each step. Resolved as the audit does:',
|
|
44
|
+
'--scale, then .rhythmguardrc.json, then the built-in default; --scale auto infers it',
|
|
45
|
+
'from token sources, then scanned stylesheets, then installed token packages.',
|
|
46
|
+
'Exits 2 when a configured token source does not exist, as the audit does.',
|
|
47
|
+
'',
|
|
48
|
+
'Options:',
|
|
49
|
+
...renderOptionLines(SCALE_OPTIONS),
|
|
50
|
+
'',
|
|
51
|
+
'Examples:',
|
|
52
|
+
' npx rhythmguard scale',
|
|
53
|
+
' npx rhythmguard scale ./src --scale auto --format json',
|
|
54
|
+
' npx rhythmguard scale --token-source ./tokens/tokens.json --scale auto',
|
|
55
|
+
'',
|
|
56
|
+
].join('\n');
|
|
57
|
+
|
|
58
|
+
const SOURCE_NOTES = Object.freeze({
|
|
59
|
+
default: 'the built-in default; pass --scale auto to infer one from your tokens',
|
|
60
|
+
explicit: 'set by --scale, audit.scale or audit.scales.spacing',
|
|
61
|
+
fallback: 'no tokens found, so the built-in default',
|
|
62
|
+
'scanned-css': 'spacing custom properties and Sass tokens in the scanned stylesheets',
|
|
63
|
+
tailwind: 'the configured Tailwind config',
|
|
64
|
+
'token-package': 'an installed design-token package',
|
|
65
|
+
'token-sources': 'the configured token sources',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** The px value of a scale entry (a number is px; a string is a length), or null. */
|
|
69
|
+
function entryPx(entry, baseFontSize) {
|
|
70
|
+
if (typeof entry === 'number') {
|
|
71
|
+
return entry;
|
|
72
|
+
}
|
|
73
|
+
const parsed = parseLengthToken(String(entry));
|
|
74
|
+
return parsed ? toPx(parsed.number, parsed.unit || 'px', baseFontSize) : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The tokens that hold each step: from the token sources, the stylesheets
|
|
79
|
+
* that declare tokens, and installed token packages, the places prefer-token
|
|
80
|
+
* reads in an audit. Only tokens defined everywhere count: one declared in a
|
|
81
|
+
* component block or under a media query does not stand for a step.
|
|
82
|
+
*/
|
|
83
|
+
function tokensByStep(run, parsed) {
|
|
84
|
+
const entries = tokenScaleSources({
|
|
85
|
+
baseFontSize: parsed.baseFontSize,
|
|
86
|
+
cssFiles: run.cssFiles,
|
|
87
|
+
isNonAuthored: run.isNonAuthored,
|
|
88
|
+
readSource: run.readSource,
|
|
89
|
+
tokenSources: parsed.tokenSources,
|
|
90
|
+
});
|
|
91
|
+
const definitions = parseTokenSources({
|
|
92
|
+
baseFontSize: parsed.baseFontSize,
|
|
93
|
+
sources: [...entries, ...discoverTokenPackages(process.cwd())],
|
|
94
|
+
tokenKind: 'spacing',
|
|
95
|
+
}).definitions;
|
|
96
|
+
const index = tokenIndexFromDefinitions(definitions, parsed.baseFontSize)
|
|
97
|
+
.filter((entry) => entry.token.startsWith('--') && entry.fixScopes.some((scope) => scope.global));
|
|
98
|
+
|
|
99
|
+
return run.scale.values.map((value) => {
|
|
100
|
+
const px = entryPx(value, parsed.baseFontSize);
|
|
101
|
+
const seen = new Set();
|
|
102
|
+
const tokens = [];
|
|
103
|
+
for (const entry of index) {
|
|
104
|
+
if (px === null || Math.abs(entry.px - px) > 1e-6 || seen.has(entry.token)) {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
seen.add(entry.token);
|
|
108
|
+
tokens.push({ file: entry.file, token: entry.token, value: entry.raw });
|
|
109
|
+
}
|
|
110
|
+
tokens.sort((a, b) => a.token.localeCompare(b.token, 'en', { numeric: true }));
|
|
111
|
+
return { px, tokens, value };
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The scale report: what `--format json` prints. */
|
|
116
|
+
function resolveScaleReport(parsedArgs) {
|
|
117
|
+
const parsed = normalizeCreateAuditOptions({ ...parsedArgs, dir: parsedArgs.dir || '.' });
|
|
118
|
+
const run = prepareAuditRun(parsed);
|
|
119
|
+
const { scale } = run;
|
|
120
|
+
return {
|
|
121
|
+
baseFontSize: parsed.baseFontSize,
|
|
122
|
+
command: {
|
|
123
|
+
config: parsed.config,
|
|
124
|
+
directory: parsed.dir,
|
|
125
|
+
},
|
|
126
|
+
scale: {
|
|
127
|
+
classStrings: scale.classStrings || null,
|
|
128
|
+
files: scale.files,
|
|
129
|
+
rejected: scale.rejected || null,
|
|
130
|
+
source: scale.source,
|
|
131
|
+
tokenCount: scale.tokenCount,
|
|
132
|
+
values: scale.values,
|
|
133
|
+
},
|
|
134
|
+
schemaVersion: '1.0',
|
|
135
|
+
steps: tokensByStep(run, parsed),
|
|
136
|
+
warnings: run.spacingSourceResult.warnings,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function renderScaleText(report) {
|
|
141
|
+
const { scale } = report;
|
|
142
|
+
const files = scale.files.length > 0 ? ` (${scale.files.join(', ')})` : '';
|
|
143
|
+
const lines = [
|
|
144
|
+
'',
|
|
145
|
+
' Rhythmguard scale',
|
|
146
|
+
'',
|
|
147
|
+
` Scale ${scale.values.join(', ')}`,
|
|
148
|
+
` Source ${scale.source}${files}: ${SOURCE_NOTES[scale.source] || scale.source}`,
|
|
149
|
+
];
|
|
150
|
+
if (scale.tokenCount > 0) {
|
|
151
|
+
lines.push(` Tokens read ${scale.tokenCount}`);
|
|
152
|
+
}
|
|
153
|
+
if (scale.rejected) {
|
|
154
|
+
lines.push(` Rejected ${scale.rejected.source} (${scale.rejected.values.join(', ')}): ${scale.rejected.reasons.join(', ')}`);
|
|
155
|
+
}
|
|
156
|
+
if (scale.classStrings) {
|
|
157
|
+
lines.push(` Class strings ${scale.classStrings.name} (${scale.classStrings.values.join(', ')})`);
|
|
158
|
+
}
|
|
159
|
+
lines.push(` Config ${report.command.config ? report.command.config.file : 'none'}`);
|
|
160
|
+
lines.push('');
|
|
161
|
+
lines.push(' Steps');
|
|
162
|
+
for (const step of report.steps) {
|
|
163
|
+
const label = typeof step.value === 'number' ? formatLength(step.value, 'px') : String(step.value);
|
|
164
|
+
const tokens = step.tokens.length > 0
|
|
165
|
+
? step.tokens.map((entry) => `var(${entry.token})${entry.file ? ` ${entry.file}` : ''}`).join(', ')
|
|
166
|
+
: '';
|
|
167
|
+
lines.push(` ${label.padEnd(10)}${tokens}`.trimEnd());
|
|
168
|
+
}
|
|
169
|
+
if (report.warnings.length > 0) {
|
|
170
|
+
lines.push('');
|
|
171
|
+
for (const warning of report.warnings) {
|
|
172
|
+
lines.push(` Warning: ${warning}`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
lines.push('');
|
|
176
|
+
return `${lines.join('\n')}\n`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function run(argv = process.argv.slice(3)) {
|
|
180
|
+
let parsed;
|
|
181
|
+
try {
|
|
182
|
+
parsed = parseArgs(argv, SCALE_OPTIONS);
|
|
183
|
+
if (!SCALE_FORMATS.has(parsed.format)) {
|
|
184
|
+
throw new Error(`Invalid format "${parsed.format}". Expected text or json.`);
|
|
185
|
+
}
|
|
186
|
+
} catch (err) {
|
|
187
|
+
process.stderr.write(`${err.message}\n\n${HELP}`);
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (parsed.help) {
|
|
192
|
+
process.stdout.write(HELP);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
let report;
|
|
197
|
+
try {
|
|
198
|
+
report = resolveScaleReport(parsed);
|
|
199
|
+
} catch (err) {
|
|
200
|
+
process.stderr.write(`${err.message}\n`);
|
|
201
|
+
process.exit(1);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
process.stdout.write(parsed.format === 'json' ? `${JSON.stringify(report, null, 2)}\n` : renderScaleText(report));
|
|
205
|
+
|
|
206
|
+
const missing = report.warnings.filter((warning) => warning.startsWith('Token source not found:'));
|
|
207
|
+
if (missing.length > 0) {
|
|
208
|
+
process.stderr.write(`${missing.join('\n')}\nA configured token source does not exist, so the scale above is not the one configured. Fix the path in --token-source or audit.tokenSources.\n`);
|
|
209
|
+
process.exitCode = 2;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
module.exports = {
|
|
214
|
+
HELP,
|
|
215
|
+
SCALE_OPTIONS,
|
|
216
|
+
renderScaleText,
|
|
217
|
+
resolveScaleReport,
|
|
218
|
+
run,
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (require.main === module) {
|
|
222
|
+
run();
|
|
223
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { DEFAULT_SCALE } = require('../presets/default-scale');
|
|
4
|
+
|
|
3
5
|
/** @type {import('../../types/shared').RhythmguardStylelintConfig} */
|
|
4
6
|
module.exports = {
|
|
5
7
|
plugins: ['stylelint-plugin-rhythmguard'],
|
|
@@ -7,7 +9,7 @@ module.exports = {
|
|
|
7
9
|
'rhythmguard/use-scale': [
|
|
8
10
|
true,
|
|
9
11
|
{
|
|
10
|
-
scale: [
|
|
12
|
+
scale: [...DEFAULT_SCALE],
|
|
11
13
|
},
|
|
12
14
|
],
|
|
13
15
|
},
|
package/src/configs/strict.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { DEFAULT_SCALE } = require('../presets/default-scale');
|
|
4
|
+
|
|
3
5
|
/** @type {import('../../types/shared').RhythmguardStylelintConfig} */
|
|
4
6
|
module.exports = {
|
|
5
7
|
plugins: ['stylelint-plugin-rhythmguard'],
|
|
@@ -19,7 +21,7 @@ module.exports = {
|
|
|
19
21
|
/^scroll-margin(?:-.+)?$/,
|
|
20
22
|
/^scroll-padding(?:-.+)?$/,
|
|
21
23
|
],
|
|
22
|
-
scale: [
|
|
24
|
+
scale: [...DEFAULT_SCALE],
|
|
23
25
|
},
|
|
24
26
|
],
|
|
25
27
|
'rhythmguard/no-offscale-transform': [
|
package/src/configs/tailwind.js
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const strict = require('./strict');
|
|
4
|
+
|
|
5
|
+
// Tailwind projects: the scale is read from the project's tokens (`@theme`
|
|
6
|
+
// `--spacing` and `--spacing-*`, `scaleSources`, the rc), and when none are
|
|
7
|
+
// found it is Tailwind's default ladder, not rhythmic-4, so standard steps
|
|
8
|
+
// such as 20px (p-5), 28px (p-7) and 44px (p-11) are on the scale (css-01).
|
|
9
|
+
const SCALE = /** @type {const} */ ({ preset: 'tailwind', scale: 'auto' });
|
|
10
|
+
// The spacing properties strict checks; transforms stay in no-offscale-transform.
|
|
11
|
+
const { properties } = /** @type {any} */ (strict.rules)['rhythmguard/use-scale'][1];
|
|
12
|
+
|
|
3
13
|
/** @type {import('../../types/shared').RhythmguardStylelintConfig} */
|
|
4
14
|
module.exports = {
|
|
5
15
|
extends: [
|
|
@@ -7,6 +17,11 @@ module.exports = {
|
|
|
7
17
|
'stylelint-plugin-rhythmguard/configs/strict',
|
|
8
18
|
],
|
|
9
19
|
rules: {
|
|
20
|
+
'rhythmguard/use-scale': [
|
|
21
|
+
true,
|
|
22
|
+
{ properties, ...SCALE },
|
|
23
|
+
],
|
|
24
|
+
'rhythmguard/no-offscale-transform': [true, { ...SCALE }],
|
|
10
25
|
'rhythmguard/prefer-token': [
|
|
11
26
|
true,
|
|
12
27
|
{
|
package/src/core/decisions.js
CHANGED
|
@@ -97,26 +97,39 @@ function decisionFor(px, prop, decisions) {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
/** Decisions from the .rhythmguardrc.json in cwd, cached and revalidated by mtime. Invalid entries throw. */
|
|
100
|
-
|
|
100
|
+
/** The rc decisions and why they could not be read, cached on the rc file. */
|
|
101
|
+
function readRcDecisions(cwd, baseFontSize) {
|
|
101
102
|
const rcPath = path.join(cwd, RC_FILE);
|
|
102
103
|
return cachedByFiles(`decisions:${rcPath}:${baseFontSize}`, (consult) => {
|
|
103
104
|
consult(rcPath);
|
|
104
105
|
if (!fs.existsSync(rcPath)) {
|
|
105
|
-
return [];
|
|
106
|
+
return { decisions: [], warnings: [] };
|
|
106
107
|
}
|
|
107
108
|
let config;
|
|
108
109
|
try {
|
|
109
110
|
config = readJsonFile(rcPath);
|
|
110
|
-
} catch {
|
|
111
|
-
|
|
111
|
+
} catch (error) {
|
|
112
|
+
// A malformed rc loses its adopt and allow decisions: say so (cq-05).
|
|
113
|
+
return { decisions: [], warnings: [`${RC_FILE} could not be read, so its decisions are not applied: ${error.message}`] };
|
|
112
114
|
}
|
|
113
|
-
|
|
115
|
+
// An invalid decisions section throws, and the rules report it as a problem.
|
|
116
|
+
return { decisions: normalizeDecisions(config && typeof config === 'object' ? config.decisions : undefined, { baseFontSize }), warnings: [] };
|
|
114
117
|
});
|
|
115
118
|
}
|
|
116
119
|
|
|
120
|
+
function loadRcDecisions(cwd = process.cwd(), { baseFontSize = 16 } = {}) {
|
|
121
|
+
return readRcDecisions(cwd, baseFontSize).decisions;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Why the rc decisions were not applied, for the lint note; empty when they were. */
|
|
125
|
+
function loadRcDecisionWarnings(cwd = process.cwd(), { baseFontSize = 16 } = {}) {
|
|
126
|
+
return readRcDecisions(cwd, baseFontSize).warnings;
|
|
127
|
+
}
|
|
128
|
+
|
|
117
129
|
module.exports = {
|
|
118
130
|
DECISIONS,
|
|
119
131
|
decisionFor,
|
|
132
|
+
loadRcDecisionWarnings,
|
|
120
133
|
loadRcDecisions,
|
|
121
134
|
normalizeDecisions,
|
|
122
135
|
};
|