stylelint-plugin-rhythmguard 3.19.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 +37 -0
- package/README.md +3 -3
- package/SECURITY.md +2 -1
- package/agents/claude-code/SKILL.md +1 -1
- package/package.json +1 -1
- package/src/audit/args.js +30 -8
- package/src/audit/baseline.js +37 -3
- package/src/audit/codemod.js +2 -0
- package/src/audit/config.js +7 -0
- package/src/audit/contract.js +124 -14
- package/src/audit/next-steps.js +3 -1
- package/src/audit/non-authored.js +1 -0
- package/src/audit/render-github.js +16 -11
- package/src/audit/render-markdown.js +8 -2
- package/src/audit/render-text.js +41 -2
- package/src/audit/render-utils.js +14 -0
- package/src/audit/report.js +230 -10
- package/src/audit/scan/files.js +5 -0
- package/src/audit/scan/stylesheets.js +48 -53
- 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 +2 -2
- 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 +39 -11
- package/src/cli/quickstart.js +53 -102
- 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 +136 -28
- 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 +40 -3
- package/types/cli.d.ts +77 -1
- package/types/shared.d.ts +10 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the quickstart prints and `init` writes, computed once (dx-02, dx-06,
|
|
5
|
+
* tf-06): the audit's own scale inference, the Stylelint config that
|
|
6
|
+
* reproduces it, and the `.rhythmguardrc.json` that makes a bare
|
|
7
|
+
* `rhythmguard audit .` (and an agent) use the same scale.
|
|
8
|
+
*/
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const path = require('node:path');
|
|
11
|
+
|
|
12
|
+
const { createAuditReport } = require('../audit/report');
|
|
13
|
+
|
|
14
|
+
// tokens.json, *.tokens.json, *-tokens.json and the same as CSS (tf-12).
|
|
15
|
+
const TOKEN_FILE_PATTERN = /(^|[.-])tokens?\.(json|css)$/i;
|
|
16
|
+
// Style Dictionary's CSS output: build/css/variables.css and dist/css/variables.css.
|
|
17
|
+
const BUILT_VARIABLES = /^variables\.css$/i;
|
|
18
|
+
const TOKEN_DIRS = ['tokens', 'design-tokens', path.join('src', 'tokens'), path.join('dist', 'tokens'), 'src', 'styles', path.join('src', 'styles')];
|
|
19
|
+
const BUILT_DIRS = [path.join('build', 'css'), path.join('dist', 'css')];
|
|
20
|
+
const TAILWIND_CONFIG_FILES = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.mjs', 'tailwind.config.ts'];
|
|
21
|
+
const RC_FILE = '.rhythmguardrc.json';
|
|
22
|
+
|
|
23
|
+
function readPackage(cwd) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
|
|
26
|
+
} catch {
|
|
27
|
+
// No readable package.json: no dependencies to read.
|
|
28
|
+
return {};
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function tailwindMajor(pkg) {
|
|
33
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
34
|
+
if (deps['@tailwindcss/postcss'] || deps['@tailwindcss/vite']) {
|
|
35
|
+
return 4;
|
|
36
|
+
}
|
|
37
|
+
const spec = deps.tailwindcss;
|
|
38
|
+
if (!spec) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const match = String(spec).match(/(\d+)/);
|
|
42
|
+
return match ? Number(match[1]) : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function findTokenFiles(cwd) {
|
|
46
|
+
const found = new Set();
|
|
47
|
+
const consider = (dir, pattern) => {
|
|
48
|
+
let entries;
|
|
49
|
+
try {
|
|
50
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
51
|
+
} catch {
|
|
52
|
+
// A directory that does not exist holds no token files.
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
if (entry.isFile() && pattern.test(entry.name)) {
|
|
57
|
+
found.add(path.relative(cwd, path.join(dir, entry.name)));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
consider(cwd, TOKEN_FILE_PATTERN);
|
|
62
|
+
for (const sub of TOKEN_DIRS) {
|
|
63
|
+
consider(path.join(cwd, sub), TOKEN_FILE_PATTERN);
|
|
64
|
+
}
|
|
65
|
+
for (const sub of BUILT_DIRS) {
|
|
66
|
+
consider(path.join(cwd, sub), BUILT_VARIABLES);
|
|
67
|
+
}
|
|
68
|
+
return Array.from(found).sort();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The Tailwind config at the project root, relative to it, or null. Found, never loaded. */
|
|
72
|
+
function findTailwindConfig(cwd) {
|
|
73
|
+
return TAILWIND_CONFIG_FILES.find((file) => fs.existsSync(path.join(cwd, file))) || null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function toPosix(relativePath) {
|
|
77
|
+
return relativePath.startsWith('./') ? relativePath : `./${relativePath.split(path.sep).join('/')}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Run the audit's scale inference on `cwd`, as the quickstart and `init` both
|
|
82
|
+
* do. A Tailwind v3 config is found but not loaded: loading it runs it, which
|
|
83
|
+
* Rhythmguard does only when asked (SECURITY.md). The config this returns
|
|
84
|
+
* names it, so Stylelint reads it once the user pastes or writes that config.
|
|
85
|
+
*/
|
|
86
|
+
async function inferFirstRun({ cwd = process.cwd(), stack }) {
|
|
87
|
+
const pkg = readPackage(cwd);
|
|
88
|
+
const twMajor = stack.tailwind ? tailwindMajor(pkg) : null;
|
|
89
|
+
const tokenFiles = findTokenFiles(cwd);
|
|
90
|
+
const rcPresent = fs.existsSync(path.join(cwd, RC_FILE));
|
|
91
|
+
const tailwindConfig = stack.tailwind && twMajor !== null && twMajor < 4 ? findTailwindConfig(cwd) : null;
|
|
92
|
+
// With an rc file its token sources are used; otherwise the token files found here.
|
|
93
|
+
const auditTokenSources = rcPresent ? [] : tokenFiles;
|
|
94
|
+
const report = await createAuditReport({
|
|
95
|
+
dir: path.relative(process.cwd(), cwd) || '.',
|
|
96
|
+
scale: 'auto',
|
|
97
|
+
...(auditTokenSources.length > 0 ? { tokenSources: auditTokenSources.map((file) => path.relative(process.cwd(), path.join(cwd, file))) } : {}),
|
|
98
|
+
});
|
|
99
|
+
return { auditTokenSources, rcPresent, report, tailwindConfig, tokenFiles, twMajor };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The files `scaleSources` should name so Stylelint infers the audit's scale
|
|
104
|
+
* on every file, not only on the one that declares the tokens (dx-02): the
|
|
105
|
+
* token files the audit read, or the stylesheets it took the tokens from.
|
|
106
|
+
*/
|
|
107
|
+
function scaleSourcesFor(scale, tokenFiles) {
|
|
108
|
+
if (scale.source === 'token-sources') {
|
|
109
|
+
return tokenFiles.length > 0 ? tokenFiles.map(toPosix) : scale.files.map(toPosix);
|
|
110
|
+
}
|
|
111
|
+
if (scale.source === 'scanned-css') {
|
|
112
|
+
return scale.files.map(toPosix);
|
|
113
|
+
}
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The Stylelint config that reproduces the audit. With a scale inferred from
|
|
119
|
+
* tokens it is `scale: "auto"` pointed at the same files. With a Tailwind v3
|
|
120
|
+
* config it is `scale: "auto"` with `tailwindConfigPath`. When the audit fell
|
|
121
|
+
* back to the default scale, that scale is written out: `configs/tailwind`
|
|
122
|
+
* would otherwise fall back to Tailwind's ladder, and the pasted config would
|
|
123
|
+
* not reproduce this report (#246).
|
|
124
|
+
*/
|
|
125
|
+
function stylelintConfigFor({ nextjs = false, profile, scale, scss = false, tailwindConfig = null, tokenFiles = [] }) {
|
|
126
|
+
const sources = scaleSourcesFor(scale, tokenFiles);
|
|
127
|
+
let ruleOptions = null;
|
|
128
|
+
if (tailwindConfig && sources.length === 0) {
|
|
129
|
+
ruleOptions = { scale: 'auto', tailwindConfigPath: toPosix(tailwindConfig) };
|
|
130
|
+
} else if (scale.source === 'fallback' && tokenFiles.length > 0) {
|
|
131
|
+
// Token files that gave no scale: point at them anyway, so every lint
|
|
132
|
+
// names why they were not read until they are fixed (tf-12). The fallback
|
|
133
|
+
// is the profile's, as in the audit.
|
|
134
|
+
ruleOptions = { scale: 'auto', scaleSources: tokenFiles.map(toPosix), ...(profile === 'tailwind' ? { preset: 'tailwind' } : {}) };
|
|
135
|
+
} else if (scale.source === 'explicit') {
|
|
136
|
+
ruleOptions = { scale: [...scale.values] };
|
|
137
|
+
} else if (scale.source !== 'fallback' && scale.source !== 'default') {
|
|
138
|
+
ruleOptions = { scale: 'auto', ...(sources.length > 0 ? { scaleSources: sources } : {}) };
|
|
139
|
+
}
|
|
140
|
+
// On a fallback the profile's own scale is the audit's (DEFAULT_SCALE for
|
|
141
|
+
// recommended, Tailwind's ladder for tailwind), so no rule is written.
|
|
142
|
+
return {
|
|
143
|
+
extends: [`stylelint-plugin-rhythmguard/configs/${profile}`],
|
|
144
|
+
// postcss-scss also parses plain CSS, so a mixed project needs only this.
|
|
145
|
+
...(scss ? { customSyntax: 'postcss-scss' } : {}),
|
|
146
|
+
...(nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
|
|
147
|
+
...(ruleOptions ? { rules: { 'rhythmguard/use-scale': [true, ruleOptions] } } : {}),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The `.rhythmguardrc.json` that makes a bare `npx rhythmguard audit .` use
|
|
153
|
+
* the scale this run found (ai-01): `scale: "auto"` with the token files.
|
|
154
|
+
* Read by the audit and, for token sources, by the rules. It never names a
|
|
155
|
+
* Tailwind config: a file in the repository must not make the audit run code
|
|
156
|
+
* (only `--tailwind-config` on the command line does).
|
|
157
|
+
*/
|
|
158
|
+
function rcFor({ tokenFiles = [] }) {
|
|
159
|
+
return {
|
|
160
|
+
audit: {
|
|
161
|
+
scale: 'auto',
|
|
162
|
+
...(tokenFiles.length > 0 ? { tokenSources: tokenFiles.map(toPosix) } : {}),
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** A line diff of two texts, `-` and `+` marked, for showing what a write replaces. */
|
|
168
|
+
function lineDiff(before, after) {
|
|
169
|
+
const a = before.replace(/\n$/, '').split('\n');
|
|
170
|
+
const b = after.replace(/\n$/, '').split('\n');
|
|
171
|
+
const lengths = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
|
|
172
|
+
for (let i = a.length - 1; i >= 0; i -= 1) {
|
|
173
|
+
for (let j = b.length - 1; j >= 0; j -= 1) {
|
|
174
|
+
lengths[i][j] = a[i] === b[j] ? lengths[i + 1][j + 1] + 1 : Math.max(lengths[i + 1][j], lengths[i][j + 1]);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const lines = [];
|
|
178
|
+
let i = 0;
|
|
179
|
+
let j = 0;
|
|
180
|
+
while (i < a.length && j < b.length) {
|
|
181
|
+
if (a[i] === b[j]) {
|
|
182
|
+
lines.push(` ${a[i]}`);
|
|
183
|
+
i += 1;
|
|
184
|
+
j += 1;
|
|
185
|
+
} else if (lengths[i + 1][j] >= lengths[i][j + 1]) {
|
|
186
|
+
lines.push(`- ${a[i]}`);
|
|
187
|
+
i += 1;
|
|
188
|
+
} else {
|
|
189
|
+
lines.push(`+ ${b[j]}`);
|
|
190
|
+
j += 1;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
while (i < a.length) lines.push(`- ${a[i++]}`);
|
|
194
|
+
while (j < b.length) lines.push(`+ ${b[j++]}`);
|
|
195
|
+
return lines;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = {
|
|
199
|
+
RC_FILE,
|
|
200
|
+
findTailwindConfig,
|
|
201
|
+
findTokenFiles,
|
|
202
|
+
inferFirstRun,
|
|
203
|
+
lineDiff,
|
|
204
|
+
rcFor,
|
|
205
|
+
readPackage,
|
|
206
|
+
scaleSourcesFor,
|
|
207
|
+
stylelintConfigFor,
|
|
208
|
+
tailwindMajor,
|
|
209
|
+
toPosix,
|
|
210
|
+
};
|
package/src/cli/index.js
CHANGED
|
@@ -9,6 +9,8 @@ the spacing scale, audits the current directory and prints a config to paste.
|
|
|
9
9
|
Commands:
|
|
10
10
|
quickstart Same as running with no command
|
|
11
11
|
audit <dir> Report design-system drift across CSS and Tailwind class strings
|
|
12
|
+
scale [dir] Print the scale the audit checks against, its source and the
|
|
13
|
+
tokens that hold each step (--format json for agents)
|
|
12
14
|
fix <dir> Replace one off-scale value everywhere, or execute snap decisions
|
|
13
15
|
init Scaffold a Rhythmguard config for your project
|
|
14
16
|
--agents <claude|cursor|copilot|all> installs the agent instruction packs instead
|
|
@@ -22,6 +24,7 @@ Examples:
|
|
|
22
24
|
npx rhythmguard
|
|
23
25
|
npx rhythmguard audit ./src
|
|
24
26
|
npx rhythmguard audit ./src --format markdown
|
|
27
|
+
npx rhythmguard scale --scale auto --format json
|
|
25
28
|
npx rhythmguard fix ./src --value 10px --to "var(--space-sm)" --write
|
|
26
29
|
npx rhythmguard init
|
|
27
30
|
npx rhythmguard init --agents all
|
|
@@ -47,6 +50,8 @@ function main() {
|
|
|
47
50
|
require('./quickstart').run();
|
|
48
51
|
} else if (command === 'audit') {
|
|
49
52
|
require('./audit').run();
|
|
53
|
+
} else if (command === 'scale') {
|
|
54
|
+
require('./scale').run();
|
|
50
55
|
} else if (command === 'fix') {
|
|
51
56
|
require('./fix').run();
|
|
52
57
|
} else if (command === 'init') {
|
|
@@ -60,7 +65,26 @@ function main() {
|
|
|
60
65
|
}
|
|
61
66
|
}
|
|
62
67
|
|
|
63
|
-
|
|
68
|
+
/**
|
|
69
|
+
* The doctor's checks as a function: `runDoctor({ cwd })` resolves to typed
|
|
70
|
+
* checks instead of printing them (cq-11). Loaded on first call, so the CLI
|
|
71
|
+
* does not pay for it on other commands.
|
|
72
|
+
*/
|
|
73
|
+
function runDoctor(options) {
|
|
74
|
+
return require('./doctor').runDoctor(options);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The text `rhythmguard doctor` prints for a runDoctor result. */
|
|
78
|
+
function formatDoctorReport(result) {
|
|
79
|
+
return require('./doctor').formatDoctorReport(result);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A short summary of a runDoctor result (or its checks) for another command to print. */
|
|
83
|
+
function doctorSummary(resultOrChecks) {
|
|
84
|
+
return require('./doctor').doctorSummary(resultOrChecks);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { HELP, doctorSummary, formatDoctorReport, main, runDoctor };
|
|
64
88
|
|
|
65
89
|
if (require.main === module) {
|
|
66
90
|
main();
|
package/src/cli/index.mjs
CHANGED
|
@@ -6,3 +6,6 @@ const cli = require('./index.js');
|
|
|
6
6
|
export default cli;
|
|
7
7
|
export const HELP = cli.HELP;
|
|
8
8
|
export const main = cli.main;
|
|
9
|
+
export const runDoctor = cli.runDoctor;
|
|
10
|
+
export const formatDoctorReport = cli.formatDoctorReport;
|
|
11
|
+
export const doctorSummary = cli.doctorSummary;
|
package/src/cli/init.js
CHANGED
|
@@ -4,9 +4,10 @@ const fs = require('node:fs');
|
|
|
4
4
|
const path = require('node:path');
|
|
5
5
|
|
|
6
6
|
const { lintGlob, stylelintInstallLine } = require('../audit/next-steps');
|
|
7
|
-
const { getScanFiles } = require('../audit/scan/files');
|
|
8
7
|
const readline = require('node:readline');
|
|
9
8
|
|
|
9
|
+
const { RC_FILE, inferFirstRun, lineDiff, rcFor, stylelintConfigFor } = require('./first-run');
|
|
10
|
+
|
|
10
11
|
function createPrompter() {
|
|
11
12
|
if (!process.stdin.isTTY) {
|
|
12
13
|
const answers = fs.readFileSync(0, 'utf8').split(/\r?\n/);
|
|
@@ -127,6 +128,7 @@ function findActiveStylelintConfig(cwd = process.cwd()) {
|
|
|
127
128
|
try {
|
|
128
129
|
content = fs.readFileSync(path.join(cwd, file), 'utf8');
|
|
129
130
|
} catch {
|
|
131
|
+
// Not in this directory: Stylelint skips it too.
|
|
130
132
|
continue;
|
|
131
133
|
}
|
|
132
134
|
|
|
@@ -167,6 +169,7 @@ function configKind(file, content) {
|
|
|
167
169
|
JSON.parse(content);
|
|
168
170
|
return 'json';
|
|
169
171
|
} catch {
|
|
172
|
+
// Not JSON: a .stylelintrc holds YAML.
|
|
170
173
|
return 'yaml';
|
|
171
174
|
}
|
|
172
175
|
}
|
|
@@ -179,8 +182,11 @@ function configSnippet(kind, config) {
|
|
|
179
182
|
return JSON.stringify({ stylelint: config }, null, 2).split('\n').slice(1, -1).map((line) => line.slice(2)).join('\n');
|
|
180
183
|
}
|
|
181
184
|
if (kind === 'yaml') {
|
|
185
|
+
// A list of strings as a YAML list; anything else in JSON flow style, which is YAML too.
|
|
182
186
|
return Object.entries(config)
|
|
183
|
-
.map(([key, values]) =>
|
|
187
|
+
.map(([key, values]) => (Array.isArray(values) && values.every((value) => typeof value === 'string')
|
|
188
|
+
? `${key}:\n${values.map((value) => ` - ${JSON.stringify(value)}`).join('\n')}`
|
|
189
|
+
: `${key}: ${JSON.stringify(values)}`))
|
|
184
190
|
.join('\n');
|
|
185
191
|
}
|
|
186
192
|
return Object.entries(config)
|
|
@@ -340,15 +346,16 @@ async function run() {
|
|
|
340
346
|
}
|
|
341
347
|
|
|
342
348
|
const profile = selectProfile(stack);
|
|
349
|
+
// The quickstart's inference: init writes exactly the config the quickstart
|
|
350
|
+
// pastes, scale or scaleSources included, so the two never disagree (dx-06).
|
|
351
|
+
const inferred = await inferFirstRun({ cwd: process.cwd(), stack });
|
|
352
|
+
const scale = inferred.report.scale;
|
|
343
353
|
// The stylesheets here decide the glob, and whether SCSS needs its syntax (dx-05, dx-10).
|
|
344
|
-
const stylesheets =
|
|
354
|
+
const stylesheets = (inferred.report.files || { cssFiles: [] }).cssFiles;
|
|
345
355
|
const scss = stylesheets.some((file) => file.endsWith('.scss'));
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
// Next.js build output is generated CSS; never lint it.
|
|
350
|
-
...(stack.nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
|
|
351
|
-
};
|
|
356
|
+
// Next.js build output is generated CSS; never lint it.
|
|
357
|
+
const config = stylelintConfigFor({ nextjs: stack.nextjs, profile, scale, scss, tailwindConfig: inferred.tailwindConfig, tokenFiles: inferred.tokenFiles });
|
|
358
|
+
process.stdout.write(`Scale: ${scale.values.join(', ')} (${scale.source}${scale.files && scale.files.length > 0 ? `: ${scale.files.slice(0, 3).join(', ')}` : ''})\n`);
|
|
352
359
|
|
|
353
360
|
// A .stylelintrc.json next to the config Stylelint actually loads is either
|
|
354
361
|
// never read (package.json, a YAML .stylelintrc) or silently takes over
|
|
@@ -368,9 +375,20 @@ async function run() {
|
|
|
368
375
|
return;
|
|
369
376
|
}
|
|
370
377
|
|
|
371
|
-
|
|
378
|
+
const nextText = JSON.stringify(config, null, 2) + '\n';
|
|
379
|
+
|
|
380
|
+
// Warn about existing config, and show what the write replaces (dx-06).
|
|
372
381
|
if (stack.hasExistingConfig) {
|
|
373
382
|
process.stdout.write('\n⚠ Existing Stylelint config found.\n');
|
|
383
|
+
let current = '';
|
|
384
|
+
try {
|
|
385
|
+
current = fs.readFileSync(path.join(process.cwd(), active.file), 'utf8');
|
|
386
|
+
} catch {
|
|
387
|
+
// Not readable: nothing to compare.
|
|
388
|
+
}
|
|
389
|
+
if (current) {
|
|
390
|
+
process.stdout.write(`\nChanges to ${active.file}:\n\n${lineDiff(current, nextText).map((line) => ` ${line}`).join('\n')}\n\n`);
|
|
391
|
+
}
|
|
374
392
|
const answer = await prompter.ask('Overwrite? (y/n) ');
|
|
375
393
|
if (answer !== 'y' && answer !== 'yes') {
|
|
376
394
|
process.stdout.write('Aborted.\n');
|
|
@@ -388,9 +406,19 @@ async function run() {
|
|
|
388
406
|
}
|
|
389
407
|
|
|
390
408
|
const configPath = path.join(process.cwd(), targetFile);
|
|
391
|
-
fs.writeFileSync(configPath,
|
|
409
|
+
fs.writeFileSync(configPath, nextText);
|
|
392
410
|
|
|
393
411
|
process.stdout.write(`\n✓ Wrote ${configPath}\n`);
|
|
412
|
+
|
|
413
|
+
// The rc makes a bare `npx rhythmguard audit .` (CI, an agent) use this scale (ai-01).
|
|
414
|
+
if (!inferred.rcPresent) {
|
|
415
|
+
const rcAnswer = await prompter.ask(`Write ${RC_FILE} so \`npx rhythmguard audit .\` uses the same scale? (y/n) `);
|
|
416
|
+
if (rcAnswer === 'y' || rcAnswer === 'yes') {
|
|
417
|
+
const rcPath = path.join(process.cwd(), RC_FILE);
|
|
418
|
+
fs.writeFileSync(rcPath, JSON.stringify(rcFor({ tailwindConfig: inferred.tailwindConfig, tokenFiles: inferred.tokenFiles }), null, 2) + '\n');
|
|
419
|
+
process.stdout.write(`✓ Wrote ${rcPath}\n`);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
394
422
|
process.stdout.write(`\nNext steps:\n`);
|
|
395
423
|
process.stdout.write(` ${stylelintInstallLine({ scss, tailwindConfig: profile === 'tailwind' })}\n`);
|
|
396
424
|
process.stdout.write(` npx stylelint "${lintGlob(process.cwd(), stylesheets)}"\n\n`);
|
package/src/cli/quickstart.js
CHANGED
|
@@ -9,13 +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
14
|
const { auditCommand, eslintInstallLine, lintGlob, stylelintInstallLine } = require('../audit/next-steps');
|
|
16
|
-
const { createAuditReport } = require('../audit/report');
|
|
17
15
|
const { detect } = require('./init');
|
|
18
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');
|
|
19
26
|
|
|
20
27
|
const HELP = `Usage: rhythmguard [quickstart]
|
|
21
28
|
|
|
@@ -27,88 +34,20 @@ Options:
|
|
|
27
34
|
--help Show this help message
|
|
28
35
|
`;
|
|
29
36
|
|
|
30
|
-
const TOKEN_FILE_PATTERN = /(^|[.-])tokens?\.json$/i;
|
|
31
|
-
const TOKEN_DIRS = ['tokens', 'design-tokens', path.join('src', 'tokens'), path.join('dist', 'tokens')];
|
|
32
37
|
const MAX_LISTED = 5;
|
|
33
38
|
|
|
34
|
-
function readPackage(cwd) {
|
|
35
|
-
try {
|
|
36
|
-
return JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
|
|
37
|
-
} catch {
|
|
38
|
-
return {};
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function tailwindMajor(pkg) {
|
|
43
|
-
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
44
|
-
if (deps['@tailwindcss/postcss'] || deps['@tailwindcss/vite']) {
|
|
45
|
-
return 4;
|
|
46
|
-
}
|
|
47
|
-
const spec = deps.tailwindcss;
|
|
48
|
-
if (!spec) {
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
const match = String(spec).match(/(\d+)/);
|
|
52
|
-
return match ? Number(match[1]) : null;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function findTokenFiles(cwd) {
|
|
56
|
-
const found = new Set();
|
|
57
|
-
const consider = (dir) => {
|
|
58
|
-
let entries;
|
|
59
|
-
try {
|
|
60
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
61
|
-
} catch {
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
for (const entry of entries) {
|
|
65
|
-
if (entry.isFile() && TOKEN_FILE_PATTERN.test(entry.name)) {
|
|
66
|
-
found.add(path.relative(cwd, path.join(dir, entry.name)));
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
consider(cwd);
|
|
71
|
-
for (const sub of TOKEN_DIRS) {
|
|
72
|
-
consider(path.join(cwd, sub));
|
|
73
|
-
}
|
|
74
|
-
return Array.from(found).sort();
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function hasRhythmguardConfig(cwd) {
|
|
78
|
-
return fs.existsSync(path.join(cwd, '.rhythmguardrc.json'));
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function toPosix(relativePath) {
|
|
82
|
-
return `./${relativePath.split(path.sep).join('/')}`;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
39
|
function topEntries(counts, limit = MAX_LISTED) {
|
|
86
40
|
return Object.entries(counts || {})
|
|
87
41
|
.sort((a, b) => b[1] - a[1])
|
|
88
42
|
.slice(0, limit);
|
|
89
43
|
}
|
|
90
44
|
|
|
91
|
-
/**
|
|
92
|
-
* The config to paste. With a scale inferred from tokens it is `scale: "auto"`
|
|
93
|
-
* pointed at the same token files, so Stylelint infers what the audit did.
|
|
94
|
-
* When the audit fell back to its default scale, that scale is written out:
|
|
95
|
-
* `scale: "auto"` would fall back to the `rhythmic-4` preset instead, which is
|
|
96
|
-
* a longer scale, and the pasted config would not reproduce this report (#246).
|
|
97
|
-
*/
|
|
45
|
+
/** The config to paste; kept under its 3.x name for callers of this module. */
|
|
98
46
|
function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profile, scss = false, tokenFiles }) {
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
}
|
|
103
|
-
return {
|
|
104
|
-
extends: [`stylelint-plugin-rhythmguard/configs/${profile}`],
|
|
105
|
-
// postcss-scss also parses plain CSS, so a mixed project needs only this.
|
|
106
|
-
...(scss ? { customSyntax: 'postcss-scss' } : {}),
|
|
107
|
-
...(nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
|
|
108
|
-
rules: {
|
|
109
|
-
'rhythmguard/use-scale': [true, ruleOptions],
|
|
110
|
-
},
|
|
111
|
-
};
|
|
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 });
|
|
112
51
|
}
|
|
113
52
|
|
|
114
53
|
/**
|
|
@@ -120,7 +59,11 @@ function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profil
|
|
|
120
59
|
const quoted = (name) => `'${name}'`;
|
|
121
60
|
|
|
122
61
|
function eslintSnippet(scaleValues, { typescript = false } = {}) {
|
|
123
|
-
|
|
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
|
+
: '';
|
|
124
67
|
return [
|
|
125
68
|
"// eslint.config.js",
|
|
126
69
|
`import rhythmguard from ${quoted('eslint-plugin-rhythmguard')};`,
|
|
@@ -134,7 +77,7 @@ function eslintSnippet(scaleValues, { typescript = false } = {}) {
|
|
|
134
77
|
? ' languageOptions: { parser: tseslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },'
|
|
135
78
|
: ' languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },',
|
|
136
79
|
" plugins: { 'rhythmguard-tailwind': rhythmguard },",
|
|
137
|
-
` rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['warn'
|
|
80
|
+
` rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['warn'${options}] },`,
|
|
138
81
|
' },',
|
|
139
82
|
'];',
|
|
140
83
|
].join('\n');
|
|
@@ -145,8 +88,8 @@ function eslintSnippet(scaleValues, { typescript = false } = {}) {
|
|
|
145
88
|
* `--scale auto` and the token files it read, so they report the same scale
|
|
146
89
|
* and the same findings; `audit .` alone would use the default scale (#287).
|
|
147
90
|
*/
|
|
148
|
-
function nextCommands(tokenSources, { eslint = false, glob = '**/*.css', stylelint = true } = {}) {
|
|
149
|
-
const audit = auditCommand({ dir: '.', scale: 'auto', tokenSources: tokenSources.map(toPosix) });
|
|
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) });
|
|
150
93
|
// Each note on its own line above its command, so a long command copies whole.
|
|
151
94
|
return [
|
|
152
95
|
...(stylelint ? [['Lint stylesheets with the config above:', `npx stylelint "${glob}"`]] : []),
|
|
@@ -180,12 +123,17 @@ async function run() {
|
|
|
180
123
|
}
|
|
181
124
|
|
|
182
125
|
const cwd = process.cwd();
|
|
183
|
-
const pkg = readPackage(cwd);
|
|
184
126
|
const stack = detect();
|
|
185
|
-
const twMajor = stack.tailwind ? tailwindMajor(pkg) : null;
|
|
186
|
-
const tokenFiles = findTokenFiles(cwd);
|
|
187
|
-
const rcPresent = hasRhythmguardConfig(cwd);
|
|
188
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;
|
|
189
137
|
|
|
190
138
|
out.push('', ' Rhythmguard quickstart', ` ${cwd}`, '');
|
|
191
139
|
out.push(' Detected');
|
|
@@ -196,22 +144,10 @@ async function run() {
|
|
|
196
144
|
const tokenPackages = [...new Set(discoverTokenPackages(cwd).map((source) => source.package))];
|
|
197
145
|
out.push(` Token packages ${tokenPackages.length > 0 ? tokenPackages.join(', ') : 'none installed'}`);
|
|
198
146
|
out.push(` .rhythmguardrc ${rcPresent ? 'present (its token sources are used)' : 'none'}`);
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
// With an rc file its token sources are used; otherwise the token files found here.
|
|
202
|
-
const auditTokenSources = rcPresent ? [] : tokenFiles;
|
|
203
|
-
let report;
|
|
204
|
-
try {
|
|
205
|
-
report = await createAuditReport({
|
|
206
|
-
dir: '.',
|
|
207
|
-
scale: 'auto',
|
|
208
|
-
...(auditTokenSources.length > 0 ? { tokenSources: auditTokenSources } : {}),
|
|
209
|
-
});
|
|
210
|
-
} catch (error) {
|
|
211
|
-
process.stderr.write(`Quickstart could not audit ${cwd}: ${error.message}\n`);
|
|
212
|
-
process.exitCode = 1;
|
|
213
|
-
return;
|
|
147
|
+
if (tailwindConfig) {
|
|
148
|
+
out.push(` Tailwind config ${tailwindConfig} (not loaded here: loading it runs it; the config below reads it)`);
|
|
214
149
|
}
|
|
150
|
+
out.push('');
|
|
215
151
|
|
|
216
152
|
const scanned = report.scanned || {};
|
|
217
153
|
const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0) + (scanned.stylelintMissing || 0);
|
|
@@ -231,10 +167,20 @@ async function run() {
|
|
|
231
167
|
if (scale.source === 'fallback' && scale.rejected) {
|
|
232
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.`);
|
|
233
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)}`);
|
|
234
173
|
} else if (scale.source === 'fallback') {
|
|
235
174
|
out.push(" Note No spacing tokens found; the audit's default scale is being used.");
|
|
236
175
|
out.push(' Add scaleSources or define --space-*/--spacing-* custom properties to lint against your own scale.');
|
|
237
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
|
+
}
|
|
238
184
|
out.push('');
|
|
239
185
|
|
|
240
186
|
const offScale = report.findings.css.filter((finding) => finding.type === 'off-scale');
|
|
@@ -282,15 +228,20 @@ async function run() {
|
|
|
282
228
|
out.push(withoutStylelint ? ' To audit your stylesheets too, install Stylelint and the plugin:' : ' Install:', '');
|
|
283
229
|
out.push(` ${stylelintInstallLine({ scss, tailwindConfig: profile === 'tailwind' })}`, '');
|
|
284
230
|
out.push(` ${withoutStylelint ? 'then paste' : 'Then paste'} this into .stylelintrc.json${stack.hasExistingConfig ? ' (merge with your existing config)' : ''}:`, '');
|
|
285
|
-
|
|
286
|
-
out.push(JSON.stringify(suggestedStylelintConfig({ fallbackScale, nextjs: stack.nextjs, profile, scss, tokenFiles }), null, 2).replace(/^/gm, ' '));
|
|
231
|
+
out.push(JSON.stringify(stylelintConfigFor({ nextjs: stack.nextjs, profile, scale, scss, tailwindConfig, tokenFiles }), null, 2).replace(/^/gm, ' '));
|
|
287
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
|
+
}
|
|
288
239
|
};
|
|
289
240
|
const printEslint = () => {
|
|
290
241
|
out.push(' Tailwind class strings need the ESLint companion. Install:', '');
|
|
291
242
|
out.push(` ${eslintInstallLine({ typescript })}`, '');
|
|
292
243
|
out.push(' Then paste this into eslint.config.js:', '');
|
|
293
|
-
out.push(eslintSnippet(scale.values, { typescript }).replace(/^/gm, ' '));
|
|
244
|
+
out.push(eslintSnippet(scale.classStrings ? null : scale.values, { typescript }).replace(/^/gm, ' '));
|
|
294
245
|
if (otherTemplates.length > 0) {
|
|
295
246
|
out.push('', ` ${otherTemplates.join(', ')} files need their parser in a block of their own; see the`);
|
|
296
247
|
out.push(' eslint-plugin-rhythmguard README, "Other file types".');
|
|
@@ -310,7 +261,7 @@ async function run() {
|
|
|
310
261
|
}
|
|
311
262
|
|
|
312
263
|
out.push(' Next');
|
|
313
|
-
out.push(...nextCommands(auditTokenSources, { eslint: stack.tailwind, glob, stylelint: !withoutStylelint }).map((line) => ` ${line}`));
|
|
264
|
+
out.push(...nextCommands(auditTokenSources, { eslint: stack.tailwind, glob, stylelint: !withoutStylelint, tailwindConfig }).map((line) => ` ${line}`));
|
|
314
265
|
out.push('');
|
|
315
266
|
|
|
316
267
|
process.stdout.write(`${out.join('\n')}\n`);
|