stylelint-plugin-rhythmguard 3.18.0 → 3.19.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 CHANGED
@@ -6,6 +6,37 @@ The format follows Keep a Changelog principles and semantic versioning.
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.19.0] - 2026-11-09
10
+
11
+ ### Changed
12
+
13
+ - The agent packs follow each tool's format and audit against the project's scale. The audit command in them is `npx rhythmguard audit . --scale auto --format json`; without `--scale auto` it checked a built-in scale, and an agent snapped correct 40px, 48px and 64px values. A new line tells agents never to invent a token name and where defined and missing tokens are listed. The Claude Code skill gains `when_to_use`, `paths` (it loads for stylesheet and component files) and `allowed-tools` for `npx rhythmguard audit` only: Stylelint and ESLint load JavaScript configs and plugins, and `fix` and `init` write files, so those runs keep the user's approval. The Cursor rule is attached by its globs (`alwaysApply: false`; with `true` Cursor ignored the globs and loaded it into every chat). Copilot gets its own `.github/instructions/rhythmguard.instructions.md` with `applyTo` globs, and `init --agents copilot` removes the block that older versions appended to `.github/copilot-instructions.md`. A contract test checks each pack's frontmatter against the keys its tool documents.
14
+ - The GitHub Action, `PetriLahdelma/rhythmguard-action@v1`, is at 1.1.0. Since 3.16.0 it had failed on every project with a stylesheet: it ran the plugin package, which no longer brings Stylelint. It now runs the `rhythmguard` package at `^3`, and a new `require-baseline` input fails the job when the baseline file is missing.
15
+
16
+ - A configured token source that does not exist (`--token-source` or `audit.tokenSources`) makes `rhythmguard audit` exit 2, after printing its report, with `Token source not found: <path>` on stderr. Before, it exited 0 against whichever scale came next, so a typo in a CI path passed silently.
17
+ - A run that read no stylesheet and no template file says "Nothing was audited" and why (no matching files, or stylesheets skipped for Stylelint, postcss-scss, `.stylelintignore`, vendored code or parse errors), in the text and Markdown reports, instead of "No issues found". The quickstart's hint for an empty directory no longer names a `./src` that may not exist. Cleanliness, which counts no files in that case, and the exit code under a gate change in 4.0.
18
+
19
+ - `--format github` puts the summary notice first, and with a baseline it annotates only the new findings, as errors. GitHub shows 10 annotations of each type per step and drops the rest without saying so, so the output stops at 10 per type and adds a notice with the number left out. Before, every finding was a warning, and the one new line in a pull request could be annotation 4,695 of 5,987. Above about 100,000 findings the renderer also overflowed the stack; it no longer does.
20
+ - `--format markdown` starts with the new findings when there is a baseline (up to 25, then a count) and lists at most five files per row. On a 300-stylesheet project the report drops from 64 KB, just under GitHub's 65,536-character comment limit, to 6 KB. Its next actions propose `--plan` and `rhythmguard fix --value` instead of a blanket autofix.
21
+
22
+ - The quickstart's and `init`'s next steps work when pasted. Before, four of five first-run stacks failed at the quickstart's own next command. Now:
23
+ - Above each config the quickstart prints the install line that config needs: Stylelint at the plugin's peer range, `stylelint-config-tailwindcss` for the `tailwind` config, `postcss-scss` when it found SCSS, and `eslint eslint-plugin-rhythmguard`, plus `typescript-eslint` when it found TypeScript.
24
+ - A project with SCSS gets `"customSyntax": "postcss-scss"`.
25
+ - In a project with `.ts` or `.tsx` files, the ESLint snippet lints them through typescript-eslint's parser and imports `eslint-plugin-rhythmguard`, the package the install line names. Before, the snippet linted only JavaScript files, so it found nothing in a TypeScript project.
26
+ - The Stylelint glob comes from where the stylesheets are (`styles/**/*.scss`, not `**/*.css`).
27
+ - `init` writes the same syntax and prints the same install line and glob.
28
+ - The `rhythmguard` package depends on `postcss-scss`, so `npx rhythmguard` audits SCSS on first contact instead of skipping it.
29
+ - The text report's last lines repeat the run's own directory and scale flags, so the next command uses the same scale. They propose `--plan` (one decision per off-scale value) and `rhythmguard fix --value <px> --to <step or token>` instead of `npx stylelint --fix`, which snaps every value without a review. The quickstart's next steps include `--plan` too.
30
+ - `docs/FRAMEWORKS.md` says that component `<style>` blocks in Vue, Svelte and Astro are not tested yet and are not in the audit's numbers.
31
+
32
+ - `rhythmguard audit` and the quickstart work in a project without Stylelint. Installing `eslint-plugin-rhythmguard` puts the plugin's `rhythmguard` command on the path without Stylelint, and the audit used to stop at the first stylesheet, so `npx rhythmguard` and the agent pack's audit command failed in every ESLint-only Tailwind app. Now the audit reads the class strings, lists the stylesheets it could not read as "Stylesheets not audited" with `npm install --save-dev stylelint` (`scanned.stylelintMissing` in JSON), and leaves them out of cleanliness and the baseline. It exits 0, except that `--max-findings`, `--min-cleanliness` and `--fail-on-new-drift` fail and say why, since a gate must not pass on a partial read. The quickstart prints the ESLint config first in that case, and the agent packs say to run `npx eslint .` there.
33
+
34
+ - `tailwindConfigPath` loads the config with `require()` only. The fallback that imported it in a child `node` process with a 5-second timeout is gone: `require()` loads CommonJS and ES module configs alike on every supported Node, so it ran only for a config that uses top-level await, and no test exercised it. Such a config is no longer read; point `scaleSources` at the CSS it builds instead.
35
+ - `SECURITY.md` says what the packages do on your machine: no network requests and no telemetry (a new contract test fails the build otherwise), no install scripts, which files they read, the one config they run as code and only when asked, `git` as the only program they start, and which commands write files. The rule docs say the same next to `tailwindConfigPath`.
36
+ - The workflows pin every action by commit digest, give the token read-only permissions by default, and do not leave credentials in the checkout; the publish job pins npm to the version the last green publish ran. A `renovate.json` keeps action digests current and leaves the benchmark trees, whose tools are pinned on purpose, to be bumped by hand.
37
+
38
+ - The release verify matrix and the post-publish smoke run on GitHub-hosted runners by default (`RELEASE_ON_FARM=true` moves them back to the self-hosted farm), and the release verify now runs the typecheck. `node scripts/release/prepare.mjs X.Y.Z` makes the release edits and runs the local gate, and refuses a release within 24 hours of the last one. Pull requests get a GitHub-hosted fast gate when the repository variable `HOSTED_GATE` is set, as a trial; the local gate stays the merge gate. Node 20, end of life since 2026-04-30 but still the engines floor until 4.0, keeps one CI row, the full suite on Stylelint 17. A non-blocking Windows job runs on pushes to `main`, and the weekly job checks the newest Stylelint, ESLint and Oxlint separately.
39
+
9
40
  ## [3.18.0] - 2026-11-05
10
41
 
11
42
  ### Changed
package/CONTRIBUTING.md CHANGED
@@ -38,7 +38,7 @@ npm ci
38
38
  npm test
39
39
  ```
40
40
 
41
- Node 20.19 or newer; `.nvmrc` pins 22 for development, so `nvm use` picks it up. A [dev container](./.devcontainer/devcontainer.json) gives the same setup in Codespaces or VS Code. No build step; the source runs as is. Tests use `node --test` through `scripts/test.mjs` and take about fifteen seconds. They are grouped by what they prove:
41
+ Node 20.19 or newer; `.nvmrc` pins 24 for development, so `nvm use` picks it up. A [dev container](./.devcontainer/devcontainer.json) gives the same setup in Codespaces or VS Code. No build step; the source runs as is. Tests use `node --test` through `scripts/test.mjs` and take about fifteen seconds. They are grouped by what they prove:
42
42
 
43
43
  | Folder | Proves | Run one |
44
44
  | --- | --- | --- |
@@ -74,7 +74,7 @@ npm run build:playground # after changing anything under src/ the rules us
74
74
  npm run bench:agents -- --dry-run --limit 4 # the agent eval pipeline, no API key needed
75
75
  ```
76
76
 
77
- The local gate runs on whatever Node you have installed; CI runs Node 20 and 22 against Stylelint 16.7.0, 16 and 17, Node 22, 24 and 26 against Stylelint 18, the ESLint companion rules on ESLint 9, and once a week the full suite against the newest Stylelint (`next` while a major is in prerelease, else `latest`). Node 20.19 is the floor, so avoid features that arrived in Node 21 or later. Glob patterns for `node --test` were one such feature, and they took a release run down.
77
+ The local gate runs on whatever Node you have installed; CI runs Node 22 against Stylelint 16.7.0, 16, 17 and 18, Node 24 and 26 against 18, Node 20 against Stylelint 17 (the full suite, since Node 20.19 is still the engines floor), the ESLint companion rules on ESLint 9, a non-blocking Windows job on pushes to `main`, and once a week the newest Stylelint, ESLint and Oxlint. Pull requests from forks get one GitHub-hosted job (lint, typecheck, tests); with the repository variable `HOSTED_GATE` set, same-repo pull requests get the same job as an advisory fast gate and the farm matrix runs after merge. The local gate is the merge gate either way. Node 20.19 is the floor, so avoid features that arrived in Node 21 or later. Glob patterns for `node --test` were one such feature, and they took a release run down.
78
78
 
79
79
  If your shell's npm registry is overridden by a corporate `.npmrc`, add `--registry https://registry.npmjs.org` to `npm ci` and prefix `test:pack-smoke` with `npm_config_registry=https://registry.npmjs.org`.
80
80
 
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  Nobody chose 13px. Rhythmguard catches off-scale spacing in CSS and Tailwind class strings, tells you the nearest steps on your scale, and snaps to them or to your tokens when you ask.
8
8
 
9
9
  [![CI](https://img.shields.io/github/actions/workflow/status/petrilahdelma/stylelint-plugin-rhythmguard/ci.yml?branch=main&label=ci)](https://github.com/petrilahdelma/stylelint-plugin-rhythmguard/actions/workflows/ci.yml)
10
- [![npm version](https://img.shields.io/npm/v/stylelint-plugin-rhythmguard?label=npm&color=1f6feb&r=3180)](https://www.npmjs.com/package/stylelint-plugin-rhythmguard)
10
+ [![npm version](https://img.shields.io/npm/v/stylelint-plugin-rhythmguard?label=npm&color=1f6feb&r=3190)](https://www.npmjs.com/package/stylelint-plugin-rhythmguard)
11
11
  [![npm downloads](https://img.shields.io/npm/dm/stylelint-plugin-rhythmguard.svg)](https://www.npmjs.com/package/stylelint-plugin-rhythmguard)
12
12
  [![License: MIT](https://img.shields.io/badge/license-MIT-white.svg)](./LICENSE)
13
13
 
@@ -144,7 +144,7 @@ The two do not overlap. Rhythmguard reports the `13px` padding and the `17px` he
144
144
 
145
145
  ## Compatibility
146
146
 
147
- Stylelint 16.7 to 18. The floor is 16.7.0 because Stylelint reads a rule's fix callback from that version on; on 16.0 to 16.6 `--fix` changed nothing. Node 20.19 or newer; Node 20 itself is end of life, and 4.0 raises the floor to 22.22 ([#172](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/172)). Stylelint 18 needs Node 22.22, 24.15 or 26, and on an older Node npm installs Stylelint 17 for `npx rhythmguard`. The ESLint companion needs ESLint 8 or newer, is tested on ESLint 9 and 10, and is tested in CI on Oxlint 1.88.0. Three runtime dependencies (`known-css-properties`, `postcss`, `postcss-value-parser`); `stylelint` is a peer you need only for the Stylelint rules and the stylesheet audit, so an ESLint-only project installs without it, and `npx rhythmguard` brings its own; `postcss-scss`, `stylelint-config-tailwindcss` and `stylelint-plugin-logical-css` are optional peers (`stylelint-plugin-logical-css` itself still peers on Stylelint 17 or older). CommonJS and ESM entry points, TypeScript declarations for every export. The CI matrix runs Node 20 and 22 against Stylelint 16.7.0, 16.x and 17.x, and Node 22, 24 and 26 against 18.x; a weekly job runs the suite against the latest Stylelint. Upgrading from 2.x: [docs/MIGRATING_TO_3.md](docs/MIGRATING_TO_3.md).
147
+ Stylelint 16.7 to 18. The floor is 16.7.0 because Stylelint reads a rule's fix callback from that version on; on 16.0 to 16.6 `--fix` changed nothing. Node 20.19 or newer; Node 20 itself is end of life, and 4.0 raises the floor to 22.22 ([#172](https://github.com/PetriLahdelma/stylelint-plugin-rhythmguard/issues/172)). Stylelint 18 needs Node 22.22, 24.15 or 26, and on an older Node npm installs Stylelint 17 for `npx rhythmguard`. The ESLint companion needs ESLint 8 or newer, is tested on ESLint 9 and 10, and is tested in CI on Oxlint 1.88.0. Three runtime dependencies (`known-css-properties`, `postcss`, `postcss-value-parser`); `stylelint` is a peer you need only for the Stylelint rules and the stylesheet audit, so an ESLint-only project installs without it, and `npx rhythmguard` brings its own; `postcss-scss`, `stylelint-config-tailwindcss` and `stylelint-plugin-logical-css` are optional peers (`stylelint-plugin-logical-css` itself still peers on Stylelint 17 or older). CommonJS and ESM entry points, TypeScript declarations for every export. The CI matrix runs Node 22 against Stylelint 16.7.0, 16.x, 17.x and 18.x, Node 24 and 26 against 18.x, and Node 20 against 17.x; a weekly job runs the suite against the newest Stylelint, ESLint and Oxlint. Upgrading from 2.x: [docs/MIGRATING_TO_3.md](docs/MIGRATING_TO_3.md).
148
148
 
149
149
  ### Stylelint 18's custom-property rule
150
150
 
package/SECURITY.md CHANGED
@@ -8,6 +8,19 @@
8
8
  | 2.x | Security fixes only until 2027-03-01 |
9
9
  | < 2.0 | No, upgrade to 3.x |
10
10
 
11
+ ## What this package does on your machine
12
+
13
+ This applies to all three packages: `stylelint-plugin-rhythmguard`, `rhythmguard` and `eslint-plugin-rhythmguard`.
14
+
15
+ - **No network requests and no telemetry.** Nothing in the packages opens a connection, and nothing is collected or sent. `test/contracts/no-network.test.js` fails the build if any source file imports a network module or calls `fetch`.
16
+ - **No install scripts.** None of the three packages runs code when it is installed.
17
+ - **It reads** the stylesheets and class-string files it lints or audits, the token files and packages you point it at (`scaleSources`, `tokenMapFile`, `--token-source`, `.rhythmguardrc.json`), and installed design-token packages that your `package.json` lists directly.
18
+ - **It runs one file of yours as code, and only when you ask.** With `tailwindConfigPath` set, the rules load that Tailwind config with `require()` to read `theme.spacing`. A config that uses top-level await is not loaded. To avoid running it at all, point `scaleSources` at the CSS it builds instead.
19
+ - **It starts one program: `git`,** and only for `rhythmguard audit --since` and `--staged`, to list changed files and read staged contents. The source test above allows no other process.
20
+ - **It writes files only when you ask:** `stylelint --fix` and `eslint --fix` through the host linter, `rhythmguard fix --write`, `audit --write-baseline` and `audit --output <file>`, and `rhythmguard init`, which asks before writing a config or agent files.
21
+ - **Provenance.** Every release is published from this repository's `release.yml` through npm trusted publishing, with no npm token anywhere, and carries an npm provenance attestation. Check it with `npm audit signatures` in a project that installs the package, or `npm view stylelint-plugin-rhythmguard dist.attestations`.
22
+ - **CI.** The workflows pin every action by commit digest, give the token read-only permissions unless a job needs more, and do not leave credentials in the checkout. The CI result collector in `.github/scripts/report-ci.sh` reports this repository's own job results to the maintainer's dashboard; it is not part of any package.
23
+
11
24
  ## Reporting a Vulnerability
12
25
 
13
26
  Please do **not** open public GitHub issues for security reports.
@@ -1,14 +1,27 @@
1
1
  ---
2
2
  name: rhythmguard
3
3
  description: Keep CSS and Tailwind spacing on the project scale. Use when writing or changing CSS, SCSS, CSS Modules or Tailwind class strings, and before finishing any such change.
4
+ when_to_use: Adding or changing padding, margin, gap, inset or other spacing in a stylesheet or a class string; reviewing a diff that does.
5
+ allowed-tools: Bash(npx rhythmguard audit:*)
6
+ paths:
7
+ - "**/*.css"
8
+ - "**/*.scss"
9
+ - "**/*.jsx"
10
+ - "**/*.tsx"
11
+ - "**/*.vue"
12
+ - "**/*.svelte"
13
+ - "**/*.astro"
14
+ - "**/*.html"
4
15
  ---
5
16
 
6
17
  ## Spacing scale
7
18
 
8
19
  This project enforces its spacing scale with stylelint-plugin-rhythmguard.
9
20
 
10
- - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding.
21
+ - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --scale auto --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding. Without `--scale auto` the audit checks a built-in scale, not this project's.
22
+ - In a project with ESLint or Oxlint and no Stylelint, the audit reads class strings only and lists the stylesheets it skipped; run `npx eslint .` (or `npx oxlint`) as well, and do not install Stylelint unless the task asks for it.
11
23
  - A finding names the value and the two nearest on-scale values. Prefer the design token for that value when one exists; otherwise use the nearest on-scale value. Never invent a new spacing value.
24
+ - Never invent a token name. Use a token only if the project defines it: the audit lists them under `contracts.tokens.definedTokens`, and any `var()` it cannot find under `contracts.tokens.missingTokens`. A `var()` that points at nothing renders no spacing at all.
12
25
  - Do not use `--fix` on spacing findings unless the task says so. Snapping a value can change layout; choose the value deliberately.
13
26
  - Values of one pixel or less (hairlines) and percentages are allowed and are not findings.
14
27
  - Tailwind arbitrary spacing values such as `p-[13px]` are findings too. The finding names the two utility classes to choose from (`p-3` or `p-4`); write one of those, not another arbitrary value.
@@ -1,9 +1,15 @@
1
+ ---
2
+ applyTo: "**/*.css,**/*.scss,**/*.jsx,**/*.tsx,**/*.vue,**/*.svelte,**/*.astro,**/*.html"
3
+ ---
4
+
1
5
  ## Spacing scale
2
6
 
3
7
  This project enforces its spacing scale with stylelint-plugin-rhythmguard.
4
8
 
5
- - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding.
9
+ - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --scale auto --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding. Without `--scale auto` the audit checks a built-in scale, not this project's.
10
+ - In a project with ESLint or Oxlint and no Stylelint, the audit reads class strings only and lists the stylesheets it skipped; run `npx eslint .` (or `npx oxlint`) as well, and do not install Stylelint unless the task asks for it.
6
11
  - A finding names the value and the two nearest on-scale values. Prefer the design token for that value when one exists; otherwise use the nearest on-scale value. Never invent a new spacing value.
12
+ - Never invent a token name. Use a token only if the project defines it: the audit lists them under `contracts.tokens.definedTokens`, and any `var()` it cannot find under `contracts.tokens.missingTokens`. A `var()` that points at nothing renders no spacing at all.
7
13
  - Do not use `--fix` on spacing findings unless the task says so. Snapping a value can change layout; choose the value deliberately.
8
14
  - Values of one pixel or less (hairlines) and percentages are allowed and are not findings.
9
15
  - Tailwind arbitrary spacing values such as `p-[13px]` are findings too. The finding names the two utility classes to choose from (`p-3` or `p-4`); write one of those, not another arbitrary value.
@@ -1,15 +1,17 @@
1
1
  ---
2
2
  description: Spacing scale rules enforced by stylelint-plugin-rhythmguard
3
- globs: ["**/*.css", "**/*.scss", "**/*.tsx", "**/*.jsx", "**/*.vue", "**/*.svelte", "**/*.astro", "**/*.html"]
4
- alwaysApply: true
3
+ globs: **/*.css, **/*.scss, **/*.jsx, **/*.tsx, **/*.vue, **/*.svelte, **/*.astro, **/*.html
4
+ alwaysApply: false
5
5
  ---
6
6
 
7
7
  ## Spacing scale
8
8
 
9
9
  This project enforces its spacing scale with stylelint-plugin-rhythmguard.
10
10
 
11
- - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding.
11
+ - Before finishing any change to CSS or to Tailwind class strings, run `npx rhythmguard audit . --scale auto --format json` (or `npx stylelint "**/*.css"` if a config exists) and fix every `off-scale` finding. Without `--scale auto` the audit checks a built-in scale, not this project's.
12
+ - In a project with ESLint or Oxlint and no Stylelint, the audit reads class strings only and lists the stylesheets it skipped; run `npx eslint .` (or `npx oxlint`) as well, and do not install Stylelint unless the task asks for it.
12
13
  - A finding names the value and the two nearest on-scale values. Prefer the design token for that value when one exists; otherwise use the nearest on-scale value. Never invent a new spacing value.
14
+ - Never invent a token name. Use a token only if the project defines it: the audit lists them under `contracts.tokens.definedTokens`, and any `var()` it cannot find under `contracts.tokens.missingTokens`. A `var()` that points at nothing renders no spacing at all.
13
15
  - Do not use `--fix` on spacing findings unless the task says so. Snapping a value can change layout; choose the value deliberately.
14
16
  - Values of one pixel or less (hairlines) and percentages are allowed and are not findings.
15
17
  - Tailwind arbitrary spacing values such as `p-[13px]` are findings too. The finding names the two utility classes to choose from (`p-3` or `p-4`); write one of those, not another arbitrary value.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stylelint-plugin-rhythmguard",
3
- "version": "3.18.0",
3
+ "version": "3.19.0",
4
4
  "description": "Nobody chose 13px. Catches off-scale spacing in CSS and Tailwind class strings and snaps it to your scale or tokens. Stylelint rules, an ESLint companion, and an audit CLI.",
5
5
  "bin": {
6
6
  "rhythmguard": "src/cli/index.js"
@@ -194,7 +194,7 @@
194
194
  "stylelint": "^17.0.0",
195
195
  "stylelint-config-tailwindcss": "^1.0.1",
196
196
  "stylelint-plugin-logical-css": "^2.0.2",
197
- "stylelint-scales": "^5.0.0",
197
+ "stylelint-scales": "^6.0.0",
198
198
  "typescript": "^7.0.0"
199
199
  },
200
200
  "engines": {
@@ -297,6 +297,14 @@ function createLegacyFindingKey(finding) {
297
297
 
298
298
  function getAuditFailures(report, parsed) {
299
299
  const failures = [];
300
+ const gated = parsed.maxFindings !== null || parsed.minCleanliness !== null || parsed.failOnNewDrift;
301
+ const missing = (report.scanned && report.scanned.stylelintMissing) || 0;
302
+
303
+ // Without Stylelint the stylesheets were not audited, so no gate can pass on
304
+ // what was read: say so and fail, rather than pass on class strings alone.
305
+ if (gated && missing > 0) {
306
+ failures.push(`${missing} stylesheet(s) were not audited because Stylelint is not installed (npm install --save-dev stylelint), so the gate cannot pass`);
307
+ }
300
308
 
301
309
  if (parsed.maxFindings !== null && report.totalWarnings > parsed.maxFindings) {
302
310
  failures.push(`total findings ${report.totalWarnings} exceeds --max-findings ${parsed.maxFindings}`);
@@ -242,6 +242,7 @@ function buildReport({
242
242
  scssFiles = 0,
243
243
  scssSkipped = 0,
244
244
  stylelintIgnored = 0,
245
+ stylelintMissing = 0,
245
246
  templateFiles,
246
247
  tailwindFindings,
247
248
  tokenCandidateMinCount,
@@ -273,9 +274,10 @@ function buildReport({
273
274
  ...tailwindFindings.map((finding) => finding.file),
274
275
  ])).slice(0, 10);
275
276
 
276
- // A stylesheet skipped for want of postcss-scss, or excluded by the project's
277
- // .stylelintignore, was not audited: it is neither scanned nor clean.
278
- const cssFilesScanned = Math.max(0, cssFiles.length - scssSkipped - stylelintIgnored);
277
+ // A stylesheet skipped for want of postcss-scss or of Stylelint itself, or
278
+ // excluded by the project's .stylelintignore, was not audited: it is neither
279
+ // scanned nor clean.
280
+ const cssFilesScanned = Math.max(0, cssFiles.length - scssSkipped - stylelintIgnored - stylelintMissing);
279
281
  const totalFiles = cssFilesScanned + templateFiles.length;
280
282
  const totalWarnings = cssFindings.length + motionFindings.length + tailwindFindings.length;
281
283
  const filesWithIssues = issueFiles.size;
@@ -323,6 +325,8 @@ function buildReport({
323
325
  scssFiles,
324
326
  scssSkipped,
325
327
  stylelintIgnored,
328
+ // Stylesheets found in a project without Stylelint: class strings were audited, these were not.
329
+ stylelintMissing,
326
330
  // Vendored, minified or built stylesheets left out of the audit (#161).
327
331
  nonAuthoredSkipped: nonAuthoredFiles.length,
328
332
  nonAuthoredFiles,
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The commands the quickstart, `init` and the audit's text footer print next,
5
+ * built from what the run scanned rather than written as literals, so each one
6
+ * works when pasted: the install line names every package the pasted config
7
+ * needs, the lint glob matches the stylesheets that were found, and the audit
8
+ * command repeats the run's own scale flags (dx-01, dx-05, dx-10, dx-11).
9
+ */
10
+ const path = require('node:path');
11
+
12
+ const { peerDependencies } = require('../../package.json');
13
+
14
+ const SAFE_DIRECTORY = /^[\w.@+-]+$/;
15
+
16
+ function shellQuote(value) {
17
+ return /^[\w./@%+=:,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
18
+ }
19
+
20
+ /** `npm install` for the Stylelint path: Stylelint at the plugin's peer range, plus what the pasted config extends or parses with. */
21
+ function stylelintInstallLine({ scss = false, tailwindConfig = false } = {}) {
22
+ return [
23
+ 'npm install --save-dev',
24
+ // Double quotes: the range holds spaces and ||, and cmd.exe does not take single quotes.
25
+ `"stylelint@${peerDependencies.stylelint}"`,
26
+ 'stylelint-plugin-rhythmguard',
27
+ ...(tailwindConfig ? ['stylelint-config-tailwindcss'] : []),
28
+ ...(scss ? ['postcss-scss'] : []),
29
+ ].join(' ');
30
+ }
31
+
32
+ /** `npm install` for the class-string path, with the TypeScript parser when the snippet uses it. */
33
+ function eslintInstallLine({ typescript = false } = {}) {
34
+ return ['npm install --save-dev eslint eslint-plugin-rhythmguard', ...(typescript ? ['typescript-eslint'] : [])].join(' ');
35
+ }
36
+
37
+ /**
38
+ * The Stylelint glob for the stylesheets a run found: under their one top-level
39
+ * directory when they share it (`src/**\/*.css`), else from the root, with the
40
+ * extensions that occur (`*.{css,scss}`).
41
+ */
42
+ function lintGlob(cwd, cssFiles) {
43
+ const relative = cssFiles.map((file) => path.relative(cwd, file)).filter((file) => file && !file.startsWith('..'));
44
+ const extensions = [...new Set(relative.map((file) => path.extname(file).slice(1)).filter(Boolean))].sort();
45
+ const pattern = extensions.length > 1 ? `*.{${extensions.join(',')}}` : `*.${extensions[0] || 'css'}`;
46
+ const tops = new Set(relative.map((file) => (file.includes(path.sep) ? file.split(path.sep)[0] : '')));
47
+ const top = tops.size === 1 ? [...tops][0] : '';
48
+ // The glob is printed inside double quotes for pasting, where $(...) and
49
+ // backticks still expand, so a directory name goes in only when it is plain.
50
+ return top && SAFE_DIRECTORY.test(top) ? `${top}/**/${pattern}` : `**/${pattern}`;
51
+ }
52
+
53
+ /** `npx rhythmguard audit <dir>` with the scale flags of the run it describes. */
54
+ function auditCommand({ dir = '.', scale = null, tokenSources = [] } = {}) {
55
+ const scaleArg = Array.isArray(scale) ? scale.join(',') : scale;
56
+ return [
57
+ 'npx rhythmguard audit',
58
+ shellQuote(dir),
59
+ ...(scaleArg ? [`--scale ${shellQuote(String(scaleArg))}`] : []),
60
+ ...tokenSources.map((file) => `--token-source ${shellQuote(file)}`),
61
+ ].join(' ');
62
+ }
63
+
64
+ /**
65
+ * The audit command a CLI run should be repeated with: only the flags the user
66
+ * passed, since anything from .rhythmguardrc.json is read again anyway.
67
+ */
68
+ function auditCommandFromArgs(parsed) {
69
+ const passed = parsed.cliOptions || new Set();
70
+ return auditCommand({
71
+ dir: parsed.dir || '.',
72
+ scale: passed.has('scale') ? parsed.scale : null,
73
+ tokenSources: passed.has('tokenSources') ? parsed.tokenSources.map((entry) => (typeof entry === 'string' ? entry : entry.path)) : [],
74
+ });
75
+ }
76
+
77
+ module.exports = {
78
+ auditCommand,
79
+ auditCommandFromArgs,
80
+ eslintInstallLine,
81
+ lintGlob,
82
+ shellQuote,
83
+ stylelintInstallLine,
84
+ };
@@ -2,25 +2,56 @@
2
2
 
3
3
  const { getAllFindings } = require('./baseline');
4
4
 
5
+ /**
6
+ * GitHub shows at most 10 error and 10 warning annotations per step and drops
7
+ * the rest without a word, so the one line a pull request added was annotation
8
+ * 4,695 of 5,987 (ci-03). The summary comes first; with a baseline only the
9
+ * new findings are annotated, as errors; each type stops at the cap with a
10
+ * notice that says how many were left out. Arrays are walked, not spread:
11
+ * spreading 150,000 findings into push() overflowed the stack (cq-04).
12
+ */
13
+ const ANNOTATIONS_PER_TYPE = 10;
14
+
15
+ function annotation(level, finding, text) {
16
+ return `::${level} file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'rhythmguard')}::${escapeGithubData(text)}`;
17
+ }
18
+
5
19
  function renderGithub(report) {
6
20
  const findings = getAllFindings(report);
7
- const lines = report.baseline
8
- ? [`::notice title=Rhythmguard audit::Since baseline: ${report.baseline.resolvedFindingsCount} resolved, ${report.baseline.newFindingsCount} new`]
9
- : [];
10
- // A stylesheet that failed to parse was not audited: an error on its line.
11
- lines.push(...((report.findings && report.findings.parseErrors) || []).map((finding) =>
12
- `::error file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'CssSyntaxError')}::${escapeGithubData(`Not audited: ${finding.text || ''}`)}`,
13
- ));
14
- lines.push(...findings.map((finding) =>
15
- `::warning file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'rhythmguard')}::${escapeGithubData(finding.text || '')}`,
16
- ));
21
+ const parseErrors = (report.findings && report.findings.parseErrors) || [];
22
+ const baseline = report.baseline || null;
17
23
  const findingWord = findings.length === 1 ? 'finding' : 'findings';
18
24
  const fileWord = report.filesWithIssues === 1 ? 'file' : 'files';
19
- lines.push(
20
- `::notice title=Rhythmguard audit::${escapeGithubData(
25
+ const lines = [
26
+ `::notice title=Rhythmguard audit::${escapeGithubData([
27
+ ...(baseline ? [`Since baseline: ${baseline.resolvedFindingsCount} resolved, ${baseline.newFindingsCount} new.`] : []),
21
28
  `${findings.length} ${findingWord} across ${report.filesWithIssues} ${fileWord}, ${report.scaleCleanliness}% scale cleanliness`,
22
- )}`,
23
- );
29
+ ].join(' '))}`,
30
+ ];
31
+
32
+ // Errors: stylesheets that could not be parsed, then (with a baseline) new findings.
33
+ const errors = [];
34
+ for (const finding of parseErrors) {
35
+ errors.push(annotation('error', { ...finding, rule: finding.rule || 'CssSyntaxError' }, `Not audited: ${finding.text || ''}`));
36
+ }
37
+ const annotated = baseline ? baseline.newFindings || [] : findings;
38
+ const level = baseline ? 'error' : 'warning';
39
+ const rest = [];
40
+ for (const finding of annotated) {
41
+ rest.push(annotation(level, finding, `${baseline ? 'New since the baseline: ' : ''}${finding.text || ''}`));
42
+ }
43
+ const errorLines = level === 'error' ? [...errors, ...rest] : errors;
44
+ const warningLines = level === 'warning' ? rest : [];
45
+
46
+ for (const group of [errorLines, warningLines]) {
47
+ for (const line of group.slice(0, ANNOTATIONS_PER_TYPE)) {
48
+ lines.push(line);
49
+ }
50
+ }
51
+ const left = Math.max(0, errorLines.length - ANNOTATIONS_PER_TYPE) + Math.max(0, warningLines.length - ANNOTATIONS_PER_TYPE);
52
+ if (left > 0) {
53
+ lines.push(`::notice title=Rhythmguard audit::${escapeGithubData(`${left} more not annotated: GitHub shows ${ANNOTATIONS_PER_TYPE} per type. The full list is in --format markdown or --format json.`)}`);
54
+ }
24
55
  return `${lines.join('\n')}\n`;
25
56
  }
26
57
 
@@ -40,6 +71,7 @@ function escapeGithubProperty(value) {
40
71
  }
41
72
 
42
73
  module.exports = {
74
+ ANNOTATIONS_PER_TYPE,
43
75
  escapeGithubData,
44
76
  escapeGithubProperty,
45
77
  renderGithub,
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const { sortCountMap } = require('./contract');
4
+ const { auditCommand } = require('./next-steps');
5
+ const { nothingAudited, nothingAuditedReasons } = require('./render-text');
4
6
  const { escapeMarkdown, markdownCode, tableCode } = require('./render-utils');
5
7
 
6
8
  function describeScaleSource(scale) {
@@ -12,13 +14,25 @@ function describeScaleSource(scale) {
12
14
  : scale.source;
13
15
  }
14
16
 
15
- function renderMarkdown(report) {
17
+ /**
18
+ * The report a pull request comment carries. GitHub rejects a comment over
19
+ * 65,536 characters, and on 300 stylesheets this reached 64,473 with the new
20
+ * finding at line 129 (ci-03): new findings now come first, and file lists are
21
+ * cut to five names.
22
+ */
23
+ function renderMarkdown(report, options = {}) {
16
24
  const lines = [
17
25
  '# Rhythmguard Design-System Audit',
18
26
  '',
19
27
  ...(report.baseline ? [`**Since baseline:** ${report.baseline.resolvedFindingsCount} resolved, ${report.baseline.newFindingsCount} new.`, ''] : []),
20
28
  `Directory: ${markdownCode(report.directory)}`,
21
29
  '',
30
+ ];
31
+ if (nothingAudited(report)) {
32
+ lines.push(`**Nothing was audited:** ${escapeMarkdown(nothingAuditedReasons(report).join('; '))}.`, '');
33
+ }
34
+ appendNewFindingsMarkdown(lines, report);
35
+ lines.push(
22
36
  '## Summary',
23
37
  '',
24
38
  '| Metric | Value |',
@@ -27,6 +41,7 @@ function renderMarkdown(report) {
27
41
  `| Template files scanned | ${report.templateFilesScanned} |`,
28
42
  ...(report.scanned && report.scanned.scssFiles > 0 ? [`| SCSS files scanned | ${report.scanned.scssFiles - report.scanned.scssSkipped} |`] : []),
29
43
  ...(report.scanned && report.scanned.scssSkipped > 0 ? [`| SCSS files skipped (install postcss-scss) | ${report.scanned.scssSkipped} |`] : []),
44
+ ...(report.scanned && report.scanned.stylelintMissing > 0 ? [`| Stylesheets not audited (Stylelint is not installed: \`npm install --save-dev stylelint\`) | ${report.scanned.stylelintMissing} |`] : []),
30
45
  ...(report.scanned && report.scanned.stylelintIgnored > 0 ? [`| Stylesheets ignored by .stylelintignore (not audited) | ${report.scanned.stylelintIgnored} |`] : []),
31
46
  ...(report.scanned && report.scanned.nonAuthoredSkipped > 0 ? [`| Non-authored stylesheets skipped (vendored, minified or built; --include-non-authored audits them) | ${report.scanned.nonAuthoredSkipped} |`] : []),
32
47
  ...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [`| Symbolic links not followed (they point outside the scanned directory) | ${report.scanned.linksOutsideRoot} |`] : []),
@@ -34,7 +49,7 @@ function renderMarkdown(report) {
34
49
  `| Files with issues | ${report.filesWithIssues} |`,
35
50
  `| Total findings | ${report.totalWarnings} |`,
36
51
  `| Scale cleanliness | ${report.scaleCleanliness}% |`,
37
- ];
52
+ );
38
53
 
39
54
  if (report.scale) {
40
55
  lines.push(`| Scale | ${report.scale.values.join(', ')} |`);
@@ -92,7 +107,8 @@ function renderMarkdown(report) {
92
107
  if (report.totalWarnings === 0) {
93
108
  lines.push('- Keep Rhythmguard in CI to prevent new drift.');
94
109
  } else {
95
- lines.push('- Run deterministic autofix for CSS declarations where appropriate.');
110
+ const command = options.auditCommand || auditCommand({ dir: report.directory });
111
+ lines.push(`- Propose one decision per off-scale value with ${markdownCode(`${command} --plan`)}, then rewrite each decided value with ${markdownCode('npx rhythmguard fix <dir> --value <px> --to <step or token>')}. Snapping every value at once can move layout.`);
96
112
  lines.push('- Review Tailwind arbitrary spacing values with UX/design-system owners.');
97
113
  lines.push('- Convert repeated raw on-scale values into existing design tokens.');
98
114
  }
@@ -117,7 +133,7 @@ function appendParseErrorsMarkdown(lines, report) {
117
133
  lines.push('| File | Error |');
118
134
  lines.push('| --- | --- |');
119
135
  for (const finding of errors) {
120
- lines.push(`| ${tableCode(`${finding.file}:${finding.line}:${finding.column}`)} | ${escapeMarkdown(finding.text)} |`);
136
+ lines.push(`| ${tableCode(`${finding.file}:${finding.line}:${finding.column}`)} | ${tableCode(finding.text || '')} |`);
121
137
  }
122
138
  lines.push('');
123
139
  }
@@ -221,7 +237,7 @@ function appendTokenContractMarkdown(lines, tokenContract) {
221
237
  lines.push('| Token | Files |');
222
238
  lines.push('| --- | --- |');
223
239
  for (const entry of missingTokens.slice(0, 10)) {
224
- lines.push(`| ${tableCode(entry.token)} | ${tableCode(entry.files.join(', '))} |`);
240
+ lines.push(`| ${tableCode(entry.token)} | ${tableCode(fileList(entry.files))} |`);
225
241
  }
226
242
  lines.push('');
227
243
  }
@@ -243,7 +259,7 @@ function appendTokenContractMarkdown(lines, tokenContract) {
243
259
  lines.push('| Value | Count | Files |');
244
260
  lines.push('| --- | ---: | --- |');
245
261
  for (const entry of rawValueCandidates.slice(0, 10)) {
246
- lines.push(`| ${tableCode(entry.value)} | ${entry.count} | ${tableCode(entry.files.join(', '))} |`);
262
+ lines.push(`| ${tableCode(entry.value)} | ${entry.count} | ${tableCode(fileList(entry.files))} |`);
247
263
  }
248
264
  lines.push('');
249
265
  }
@@ -271,6 +287,34 @@ function appendTokenContractMarkdown(lines, tokenContract) {
271
287
  }
272
288
  }
273
289
 
290
+ const NEW_FINDINGS_SHOWN = 25;
291
+ const FILES_SHOWN = 5;
292
+
293
+ /** Five names and a count: a value repeated in 300 files made one table row of 6,900 characters. */
294
+ function fileList(files) {
295
+ const shown = files.slice(0, FILES_SHOWN).join(', ');
296
+ return files.length > FILES_SHOWN ? `${shown}, +${files.length - FILES_SHOWN} more` : shown;
297
+ }
298
+
299
+ function appendNewFindingsMarkdown(lines, report) {
300
+ const fresh = (report.baseline && report.baseline.newFindings) || [];
301
+ if (fresh.length === 0) {
302
+ return;
303
+ }
304
+ lines.push('## New Since the Baseline');
305
+ lines.push('');
306
+ lines.push('| Location | Finding |');
307
+ lines.push('| --- | --- |');
308
+ for (const finding of fresh.slice(0, NEW_FINDINGS_SHOWN)) {
309
+ // A code span: finding text can carry values from the project's source, and this goes into a PR comment.
310
+ lines.push(`| ${tableCode(`${finding.file}:${finding.line}`)} | ${tableCode(finding.text || '')} |`);
311
+ }
312
+ if (fresh.length > NEW_FINDINGS_SHOWN) {
313
+ lines.push(`| ${fresh.length - NEW_FINDINGS_SHOWN} more | see \`--format json\` |`);
314
+ }
315
+ lines.push('');
316
+ }
317
+
274
318
  function appendBaselineMarkdown(lines, report) {
275
319
  if (!report.baseline && !report.baselineWritten) {
276
320
  return;
@@ -288,15 +332,6 @@ function appendBaselineMarkdown(lines, report) {
288
332
  lines.push('');
289
333
  }
290
334
 
291
- if (report.baseline && report.baseline.newFindings.length > 0) {
292
- lines.push('| New finding | Location |');
293
- lines.push('| --- | --- |');
294
- for (const finding of report.baseline.newFindings.slice(0, 10)) {
295
- lines.push(`| ${tableCode(finding.text)} | ${tableCode(`${finding.file}:${finding.line}`)} |`);
296
- }
297
- lines.push('');
298
- }
299
-
300
335
  if (report.baselineWritten) {
301
336
  lines.push(`Baseline written: ${markdownCode(report.baselineWritten.file)}`);
302
337
  lines.push('');
@@ -4,13 +4,18 @@ const {
4
4
  sortCountMap,
5
5
  sumCounts,
6
6
  } = require('./contract');
7
+ const { auditCommand, shellQuote } = require('./next-steps');
7
8
  const {
8
9
  histBar,
9
10
  scoreBar,
10
11
  truncate,
11
12
  } = require('./render-utils');
12
13
 
13
- function renderText(report) {
14
+ /**
15
+ * `options.auditCommand` is the command that reproduces this run (its directory
16
+ * and scale flags); the footer builds on it so the next step uses the same scale.
17
+ */
18
+ function renderText(report, options = {}) {
14
19
  const lines = [
15
20
  '',
16
21
  ' ┌─ RHYTHMGUARD DESIGN-SYSTEM AUDIT ─────────────────────────┐',
@@ -21,6 +26,7 @@ function renderText(report) {
21
26
  ` Template files scanned ${String(report.templateFilesScanned).padStart(4)}`,
22
27
  ...(report.scanned && report.scanned.scssFiles > 0 ? [` SCSS files scanned ${String(report.scanned.scssFiles - report.scanned.scssSkipped).padStart(4)}`] : []),
23
28
  ...(report.scanned && report.scanned.scssSkipped > 0 ? [` SCSS files skipped ${String(report.scanned.scssSkipped).padStart(4)} (install postcss-scss to audit them)`] : []),
29
+ ...(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
30
  ...(report.scanned && report.scanned.stylelintIgnored > 0 ? [` Ignored by .stylelintignore ${String(report.scanned.stylelintIgnored).padStart(4)} (not audited)`] : []),
25
31
  ...(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
32
  ...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [` Links not followed ${String(report.scanned.linksOutsideRoot).padStart(4)} (they point outside the scanned directory)`] : []),
@@ -72,19 +78,42 @@ function renderText(report) {
72
78
  lines.push('');
73
79
  }
74
80
 
75
- if (report.totalWarnings === 0 && parseErrors(report).length > 0) {
81
+ if (nothingAudited(report)) {
82
+ lines.push(` ! Nothing was audited: ${nothingAuditedReasons(report).join('; ')}. The cleanliness above counts no files.`);
83
+ } else if (report.totalWarnings === 0 && parseErrors(report).length > 0) {
76
84
  lines.push(` ! No findings in the stylesheets that parsed; ${parseErrors(report).length} could not be parsed and were not audited.`);
77
85
  } else if (report.totalWarnings === 0) {
78
86
  lines.push(' ✓ No issues found. Your design-system rhythm is clean.');
79
87
  } 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.');
88
+ // Snapping a value can move layout, so the footer offers the reviewable
89
+ // path: one decision per value, then a rewrite of each decided value.
90
+ const command = options.auditCommand || auditCommand({ dir: report.directory });
91
+ lines.push(` → Propose one decision per off-scale value: ${command} --plan`);
92
+ lines.push(` → Then rewrite each value you decided on: npx rhythmguard fix ${shellQuote(report.directory)} --value <px> --to <step or token>`);
93
+ lines.push(` → PR or design review: ${command} --format markdown`);
82
94
  }
83
95
  lines.push('');
84
96
 
85
97
  return `${lines.join('\n')}\n`;
86
98
  }
87
99
 
100
+ /** No stylesheet and no template file was read, though the run may have found some (dx-09). */
101
+ function nothingAudited(report) {
102
+ return (report.cssFilesScanned || 0) === 0 && (report.templateFilesScanned || 0) === 0;
103
+ }
104
+
105
+ function nothingAuditedReasons(report) {
106
+ const scanned = report.scanned || {};
107
+ const reasons = [
108
+ ...(scanned.stylelintMissing > 0 ? [`${scanned.stylelintMissing} stylesheets need Stylelint, which is not installed`] : []),
109
+ ...(scanned.scssSkipped > 0 ? [`${scanned.scssSkipped} SCSS files need postcss-scss, which is not installed`] : []),
110
+ ...(scanned.stylelintIgnored > 0 ? [`${scanned.stylelintIgnored} stylesheets are in .stylelintignore`] : []),
111
+ ...(scanned.nonAuthoredSkipped > 0 ? [`${scanned.nonAuthoredSkipped} stylesheets look vendored, minified or built`] : []),
112
+ ...(parseErrors(report).length > 0 ? [`${parseErrors(report).length} stylesheets could not be parsed`] : []),
113
+ ];
114
+ return reasons.length > 0 ? reasons : [`no .css, .scss or template files under ${report.directory}`];
115
+ }
116
+
88
117
  function parseErrors(report) {
89
118
  return (report.findings && report.findings.parseErrors) || [];
90
119
  }
@@ -208,6 +237,8 @@ function appendHistogram(lines, title, counts = {}) {
208
237
  }
209
238
 
210
239
  module.exports = {
240
+ nothingAudited,
241
+ nothingAuditedReasons,
211
242
  appendBaselineText,
212
243
  appendHistogram,
213
244
  appendParseErrorsText,
@@ -126,6 +126,7 @@ async function createAuditReport(options) {
126
126
  scssFiles: cssResults.scssFiles || 0,
127
127
  scssSkipped: cssResults.scssSkipped || 0,
128
128
  stylelintIgnored: cssResults.stylelintIgnored || 0,
129
+ stylelintMissing: cssResults.stylelintMissing || 0,
129
130
  tailwindFindings: decided.tailwindFindings,
130
131
  templateFiles,
131
132
  tokenCandidateMinCount: parsed.tokenCandidateMinCount,
@@ -134,6 +135,10 @@ async function createAuditReport(options) {
134
135
  tokenSourceWarnings: tokenSourceResult.warnings,
135
136
  });
136
137
 
138
+ // The files this run scanned, for the CLI's next-step commands (lint globs,
139
+ // parsers). Not enumerable, so no JSON output carries the lists.
140
+ Object.defineProperty(report, 'files', { enumerable: false, value: { cssFiles: [...cssFiles], templateFiles: [...templateFiles] } });
141
+
137
142
  const declarations = collectDeclarations({
138
143
  cssFiles,
139
144
  externalDefinitions: tokenSourceResult.definitions,
@@ -35,18 +35,15 @@ function resolveScssSyntax() {
35
35
  /**
36
36
  * Stylelint is an optional peer, so an ESLint-only project can reach this
37
37
  * without it. The `rhythmguard` package depends on it; this package's own
38
- * command says what to install instead of failing on a module path.
38
+ * command then audits class strings only and counts the stylesheets as not
39
+ * audited (null here), instead of failing on a module path.
39
40
  */
40
41
  async function loadStylelint() {
41
42
  try {
42
43
  return (await import('stylelint')).default;
43
44
  } catch (error) {
44
45
  if (error && error.code === 'ERR_MODULE_NOT_FOUND' && /'stylelint'/.test(error.message)) {
45
- throw new Error(
46
- 'Auditing stylesheets needs Stylelint, which this project does not have. '
47
- + 'Install it with: npm install --save-dev stylelint',
48
- { cause: error },
49
- );
46
+ return null;
50
47
  }
51
48
  throw error;
52
49
  }
@@ -58,11 +55,22 @@ async function runStylelintAudit(cssFiles, options) {
58
55
  empty.scssFiles = 0;
59
56
  empty.scssSkipped = 0;
60
57
  empty.stylelintIgnored = 0;
58
+ empty.stylelintMissing = 0;
61
59
  empty.unauditedFiles = [];
62
60
  return empty;
63
61
  }
64
62
 
65
63
  const stylelint = await loadStylelint();
64
+ if (!stylelint) {
65
+ // Found but not audited, like SCSS without postcss-scss: neither scanned nor clean.
66
+ const missing = [];
67
+ missing.scssFiles = 0;
68
+ missing.scssSkipped = 0;
69
+ missing.stylelintIgnored = 0;
70
+ missing.stylelintMissing = cssFiles.length;
71
+ missing.unauditedFiles = [...cssFiles];
72
+ return missing;
73
+ }
66
74
  const rules = {
67
75
  'rhythmguard/use-scale': [
68
76
  true,
@@ -133,6 +141,7 @@ async function runStylelintAudit(cssFiles, options) {
133
141
  results.scssFiles = scssFiles.length;
134
142
  results.scssSkipped = skippedScssFiles.length;
135
143
  results.stylelintIgnored = ignoredFiles.length;
144
+ results.stylelintMissing = 0;
136
145
  // Neither kind was audited: they count as neither scanned nor clean.
137
146
  results.unauditedFiles = [...skippedScssFiles, ...ignoredFiles];
138
147
  return results;
package/src/cli/audit.js CHANGED
@@ -16,6 +16,7 @@ const { renderGithub } = require('../audit/render-github');
16
16
  const { renderBadge } = require('../audit/render-badge');
17
17
  const { renderHtml } = require('../audit/render-html');
18
18
  const { renderMarkdown } = require('../audit/render-markdown');
19
+ const { auditCommandFromArgs } = require('../audit/next-steps');
19
20
  const { renderText } = require('../audit/render-text');
20
21
  const { createAuditReport, normalizeCreateAuditOptions } = require('../audit/report');
21
22
 
@@ -61,42 +62,42 @@ async function run() {
61
62
 
62
63
  if (parsed.format === 'json') {
63
64
  writeOutput(`${JSON.stringify(toAuditContractReport(report), null, 2)}\n`, parsed.outputPath);
64
- finish(auditFailures);
65
+ finish(auditFailures, report);
65
66
  return;
66
67
  }
67
68
 
68
69
  if (parsed.format === 'json-v1') {
69
70
  writeOutput(`${JSON.stringify(report, null, 2)}\n`, parsed.outputPath);
70
- finish(auditFailures);
71
+ finish(auditFailures, report);
71
72
  return;
72
73
  }
73
74
 
74
75
  if (parsed.format === 'markdown') {
75
- writeOutput(renderMarkdown(report), parsed.outputPath);
76
- finish(auditFailures);
76
+ writeOutput(renderMarkdown(report, { auditCommand: auditCommandFromArgs(parsed) }), parsed.outputPath);
77
+ finish(auditFailures, report);
77
78
  return;
78
79
  }
79
80
 
80
81
  if (parsed.format === 'html') {
81
82
  writeOutput(renderHtml(report), parsed.outputPath);
82
- finish(auditFailures);
83
+ finish(auditFailures, report);
83
84
  return;
84
85
  }
85
86
 
86
87
  if (parsed.format === 'badge') {
87
88
  writeOutput(renderBadge(report, { metric: parsed.badgeMetric }), parsed.outputPath);
88
- finish(auditFailures);
89
+ finish(auditFailures, report);
89
90
  return;
90
91
  }
91
92
 
92
93
  if (parsed.format === 'github') {
93
94
  writeOutput(renderGithub(report), parsed.outputPath);
94
- finish(auditFailures);
95
+ finish(auditFailures, report);
95
96
  return;
96
97
  }
97
98
 
98
- writeOutput(renderText(report), parsed.outputPath);
99
- finish(auditFailures);
99
+ writeOutput(renderText(report, { auditCommand: auditCommandFromArgs(parsed) }), parsed.outputPath);
100
+ finish(auditFailures, report);
100
101
  }
101
102
 
102
103
  function writeOutput(output, outputPath) {
@@ -110,13 +111,21 @@ function writeOutput(output, outputPath) {
110
111
  fs.writeFileSync(resolvedPath, output);
111
112
  }
112
113
 
113
- function finish(auditFailures) {
114
+ function finish(auditFailures, report) {
115
+ // A configured token source that does not exist made the run audit against
116
+ // another scale and pass (ci-02): that is a configuration error, exit 2.
117
+ const missing = ((report && report.tokenSourceWarnings) || []).filter((warning) => warning.startsWith('Token source not found:'));
118
+ if (missing.length > 0) {
119
+ process.stderr.write(`${missing.join('\n')}\nAudit failed: a 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`);
120
+ process.exitCode = 2;
121
+ }
122
+
114
123
  if (auditFailures.length === 0) {
115
124
  return;
116
125
  }
117
126
 
118
127
  process.stderr.write(`Audit failed: ${auditFailures.join('; ')}\n`);
119
- process.exitCode = 1;
128
+ process.exitCode = process.exitCode || 1;
120
129
  }
121
130
 
122
131
  module.exports = {
package/src/cli/init.js CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
+
6
+ const { lintGlob, stylelintInstallLine } = require('../audit/next-steps');
7
+ const { getScanFiles } = require('../audit/scan/files');
5
8
  const readline = require('node:readline');
6
9
 
7
10
  function createPrompter() {
@@ -195,7 +198,7 @@ function selectProfile(stack) {
195
198
  const AGENT_TARGETS = {
196
199
  claude: { source: 'claude-code/SKILL.md', target: path.join('.claude', 'skills', 'rhythmguard', 'SKILL.md'), mode: 'write' },
197
200
  cursor: { source: 'cursor/rhythmguard.mdc', target: path.join('.cursor', 'rules', 'rhythmguard.mdc'), mode: 'write' },
198
- copilot: { source: 'copilot/copilot-instructions.md', target: path.join('.github', 'copilot-instructions.md'), mode: 'append' },
201
+ copilot: { source: 'copilot/rhythmguard.instructions.md', target: path.join('.github', 'instructions', 'rhythmguard.instructions.md'), mode: 'write' },
199
202
  };
200
203
  const AGENT_BLOCK_START = '<!-- rhythmguard:agents:start -->';
201
204
  const AGENT_BLOCK_END = '<!-- rhythmguard:agents:end -->';
@@ -238,11 +241,31 @@ function parseInitArgs(argv) {
238
241
  return parsed;
239
242
  }
240
243
 
244
+ /**
245
+ * Up to 3.18 the Copilot pack was appended to .github/copilot-instructions.md
246
+ * between markers. It now has its own path-specific file, so the old block,
247
+ * which this command wrote and owns, is taken out to leave one copy.
248
+ */
249
+ function removeLegacyCopilotBlock(cwd) {
250
+ const legacy = path.join('.github', 'copilot-instructions.md');
251
+ const legacyPath = path.join(cwd, legacy);
252
+ if (!fs.existsSync(legacyPath)) return null;
253
+ const existing = fs.readFileSync(legacyPath, 'utf8');
254
+ const start = existing.indexOf(AGENT_BLOCK_START);
255
+ const end = existing.indexOf(AGENT_BLOCK_END);
256
+ if (start === -1 || end === -1 || end < start) return null;
257
+ const next = `${existing.slice(0, start).trimEnd()}\n${existing.slice(end + AGENT_BLOCK_END.length).replace(/^\n+/, '\n')}`.replace(/^\n+/, '');
258
+ if (next.trim() === '') {
259
+ fs.rmSync(legacyPath);
260
+ } else {
261
+ fs.writeFileSync(legacyPath, next.endsWith('\n') ? next : `${next}\n`);
262
+ }
263
+ return legacy;
264
+ }
265
+
241
266
  /**
242
267
  * Copies the generated packs under <package>/agents into the locations each
243
- * agent reads. Claude Code and Cursor files are owned by Rhythmguard and
244
- * overwritten; copilot-instructions.md is shared, so the block is appended
245
- * between markers and replaced in place on later runs.
268
+ * agent reads. Every target is a file Rhythmguard owns, overwritten on rerun.
246
269
  */
247
270
  function installAgents(selection, cwd = process.cwd()) {
248
271
  const names = selection === 'all' ? Object.keys(AGENT_TARGETS) : [selection];
@@ -254,24 +277,17 @@ function installAgents(selection, cwd = process.cwd()) {
254
277
  const packsDir = path.join(__dirname, '..', '..', 'agents');
255
278
  const written = [];
256
279
  for (const name of names) {
257
- const { mode, source, target } = AGENT_TARGETS[name];
280
+ const { source, target } = AGENT_TARGETS[name];
258
281
  const content = fs.readFileSync(path.join(packsDir, source), 'utf8');
259
282
  const targetPath = path.join(cwd, target);
260
283
  fs.mkdirSync(path.dirname(targetPath), { recursive: true });
261
284
 
262
- if (mode === 'append' && fs.existsSync(targetPath)) {
263
- const existing = fs.readFileSync(targetPath, 'utf8');
264
- const block = `${AGENT_BLOCK_START}\n${content.trimEnd()}\n${AGENT_BLOCK_END}\n`;
265
- const start = existing.indexOf(AGENT_BLOCK_START);
266
- const end = existing.indexOf(AGENT_BLOCK_END);
267
- const next = start !== -1 && end !== -1
268
- ? `${existing.slice(0, start)}${block}${existing.slice(end + AGENT_BLOCK_END.length).replace(/^\n/, '')}`
269
- : `${existing.trimEnd()}\n\n${block}`;
270
- fs.writeFileSync(targetPath, next);
271
- } else {
272
- fs.writeFileSync(targetPath, content);
273
- }
285
+ fs.writeFileSync(targetPath, content);
274
286
  written.push(target);
287
+ if (name === 'copilot') {
288
+ const moved = removeLegacyCopilotBlock(cwd);
289
+ if (moved) written.push(`${moved} (the block an older version appended there was removed)`);
290
+ }
275
291
  }
276
292
  return written;
277
293
  }
@@ -324,8 +340,12 @@ async function run() {
324
340
  }
325
341
 
326
342
  const profile = selectProfile(stack);
343
+ // The stylesheets here decide the glob, and whether SCSS needs its syntax (dx-05, dx-10).
344
+ const stylesheets = getScanFiles(process.cwd(), [], {}).cssFiles;
345
+ const scss = stylesheets.some((file) => file.endsWith('.scss'));
327
346
  const config = {
328
347
  extends: [`stylelint-plugin-rhythmguard/configs/${profile}`],
348
+ ...(scss ? { customSyntax: 'postcss-scss' } : {}),
329
349
  // Next.js build output is generated CSS; never lint it.
330
350
  ...(stack.nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
331
351
  };
@@ -372,7 +392,8 @@ async function run() {
372
392
 
373
393
  process.stdout.write(`\n✓ Wrote ${configPath}\n`);
374
394
  process.stdout.write(`\nNext steps:\n`);
375
- process.stdout.write(` npx stylelint "src/**/*.css"\n\n`);
395
+ process.stdout.write(` ${stylelintInstallLine({ scss, tailwindConfig: profile === 'tailwind' })}\n`);
396
+ process.stdout.write(` npx stylelint "${lintGlob(process.cwd(), stylesheets)}"\n\n`);
376
397
  } finally {
377
398
  prompter.close();
378
399
  }
@@ -12,6 +12,7 @@
12
12
  const fs = require('node:fs');
13
13
  const path = require('node:path');
14
14
 
15
+ const { auditCommand, eslintInstallLine, lintGlob, stylelintInstallLine } = require('../audit/next-steps');
15
16
  const { createAuditReport } = require('../audit/report');
16
17
  const { detect } = require('./init');
17
18
  const { discoverTokenPackages } = require('../core/scale-inference');
@@ -94,13 +95,15 @@ function topEntries(counts, limit = MAX_LISTED) {
94
95
  * `scale: "auto"` would fall back to the `rhythmic-4` preset instead, which is
95
96
  * a longer scale, and the pasted config would not reproduce this report (#246).
96
97
  */
97
- function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profile, tokenFiles }) {
98
+ function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profile, scss = false, tokenFiles }) {
98
99
  const ruleOptions = Array.isArray(fallbackScale) ? { scale: [...fallbackScale] } : { scale: 'auto' };
99
100
  if (!fallbackScale && tokenFiles.length > 0) {
100
101
  ruleOptions.scaleSources = tokenFiles.map(toPosix);
101
102
  }
102
103
  return {
103
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' } : {}),
104
107
  ...(nextjs ? { ignoreFiles: ['.next/**', 'out/**', 'node_modules/**'] } : {}),
105
108
  rules: {
106
109
  'rhythmguard/use-scale': [true, ruleOptions],
@@ -108,17 +111,28 @@ function suggestedStylelintConfig({ fallbackScale = null, nextjs = false, profil
108
111
  };
109
112
  }
110
113
 
111
- function eslintSnippet(scaleValues) {
114
+ /**
115
+ * The eslint.config.js block. It imports the package the printed install line
116
+ * installs. With TypeScript files it lints .ts and .tsx through typescript-eslint's
117
+ * parser: the default parser reads no TSX, so a JS-only block linted nothing (dx-04).
118
+ */
119
+ // Written this way so the snippet's import lines are not read as imports of this file.
120
+ const quoted = (name) => `'${name}'`;
121
+
122
+ function eslintSnippet(scaleValues, { typescript = false } = {}) {
112
123
  const scale = scaleValues.filter((value) => typeof value === 'number').join(', ');
113
124
  return [
114
125
  "// eslint.config.js",
115
- "import rhythmguard from 'stylelint-plugin-rhythmguard/eslint';",
126
+ `import rhythmguard from ${quoted('eslint-plugin-rhythmguard')};`,
127
+ ...(typescript ? [`import tseslint from ${quoted('typescript-eslint')};`] : []),
116
128
  '',
117
129
  'export default [',
118
130
  ' {',
119
131
  // Without `files` and JSX parsing, a flat config lints no .jsx at all (#243).
120
- " files: ['**/*.{js,jsx,mjs,cjs}'],",
121
- ' languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },',
132
+ typescript ? " files: ['**/*.{js,jsx,mjs,cjs,ts,tsx}']," : " files: ['**/*.{js,jsx,mjs,cjs}'],",
133
+ typescript
134
+ ? ' languageOptions: { parser: tseslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },'
135
+ : ' languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } },',
122
136
  " plugins: { 'rhythmguard-tailwind': rhythmguard },",
123
137
  ` rules: { 'rhythmguard-tailwind/tailwind-class-use-scale': ['warn', { scale: [${scale}] }] },`,
124
138
  ' },',
@@ -126,20 +140,19 @@ function eslintSnippet(scaleValues) {
126
140
  ].join('\n');
127
141
  }
128
142
 
129
- function shellQuote(value) {
130
- return /^[\w./@%+=:,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
131
- }
132
-
133
143
  /**
134
144
  * The commands to run next. The audit commands pass what quickstart passed,
135
145
  * `--scale auto` and the token files it read, so they report the same scale
136
146
  * and the same findings; `audit .` alone would use the default scale (#287).
137
147
  */
138
- function nextCommands(tokenSources) {
139
- const audit = ['npx rhythmguard audit .', '--scale auto', ...tokenSources.map((file) => `--token-source ${shellQuote(toPosix(file))}`)].join(' ');
148
+ function nextCommands(tokenSources, { eslint = false, glob = '**/*.css', stylelint = true } = {}) {
149
+ const audit = auditCommand({ dir: '.', scale: 'auto', tokenSources: tokenSources.map(toPosix) });
140
150
  // Each note on its own line above its command, so a long command copies whole.
141
151
  return [
142
- ['Lint with the config above:', 'npx stylelint "**/*.css"'],
152
+ ...(stylelint ? [['Lint stylesheets with the config above:', `npx stylelint "${glob}"`]] : []),
153
+ ...(eslint ? [['Lint class strings with the ESLint config above:', 'npx eslint .']] : []),
154
+ // Snapping a value can move layout: decide per value, then rewrite (dx-11).
155
+ ['Propose one decision per off-scale value, before changing any:', `${audit} --plan`],
143
156
  ['PR-ready report:', `${audit} --format markdown`],
144
157
  ['Then gate only new drift in CI, with the same flags:', `${audit} --write-baseline`],
145
158
  ['Check the setup:', 'npx rhythmguard doctor'],
@@ -201,10 +214,12 @@ async function run() {
201
214
  }
202
215
 
203
216
  const scanned = report.scanned || {};
204
- const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0);
217
+ const skippedStylesheets = (scanned.scssSkipped || 0) + (scanned.stylelintIgnored || 0) + (scanned.nonAuthoredSkipped || 0) + (scanned.stylelintMissing || 0);
218
+ // An ESLint-only project: class strings were audited, stylesheets were not.
219
+ const withoutStylelint = (scanned.stylelintMissing || 0) > 0;
205
220
  if (report.cssFilesScanned === 0 && report.templateFilesScanned === 0 && skippedStylesheets === 0) {
206
221
  out.push(' No CSS files found here. Run from your project root, or audit a directory directly:');
207
- out.push(' npx rhythmguard audit ./src', '');
222
+ out.push(' npx rhythmguard audit <directory>', '');
208
223
  process.stdout.write(`${out.join('\n')}\n`);
209
224
  return;
210
225
  }
@@ -228,6 +243,7 @@ async function run() {
228
243
  out.push(` Template files ${report.templateFilesScanned}`);
229
244
  if (skippedStylesheets > 0) {
230
245
  const reasons = [
246
+ ...(withoutStylelint ? [`${scanned.stylelintMissing} because Stylelint is not installed`] : []),
231
247
  ...(scanned.scssSkipped > 0 ? [`${scanned.scssSkipped} SCSS without postcss-scss`] : []),
232
248
  ...(scanned.stylelintIgnored > 0 ? [`${scanned.stylelintIgnored} in .stylelintignore`] : []),
233
249
  ...(scanned.nonAuthoredSkipped > 0 ? [`${scanned.nonAuthoredSkipped} vendored, minified or built`] : []),
@@ -256,21 +272,45 @@ async function run() {
256
272
  out.push('');
257
273
 
258
274
  const profile = stack.tailwind ? 'tailwind' : 'recommended';
259
- out.push(` Paste this into .stylelintrc.json${stack.hasExistingConfig ? ' (merge with your existing config)' : ''}:`, '');
260
- const fallbackScale = scale.source === 'fallback' ? scale.values : null;
261
- out.push(JSON.stringify(suggestedStylelintConfig({ fallbackScale, nextjs: stack.nextjs, profile, tokenFiles }), null, 2).replace(/^/gm, ' '));
262
- out.push('');
263
-
264
- if (stack.tailwind) {
265
- out.push(' Tailwind class strings need the ESLint companion. Paste this into eslint.config.js:', '');
266
- out.push(eslintSnippet(scale.values).replace(/^/gm, ' '));
267
- out.push('', ' TypeScript, Vue, Svelte and Astro files need their parser in a block of their own; see the');
268
- out.push(' eslint-plugin-rhythmguard README, "Other file types".');
275
+ const files = report.files || { cssFiles: [], templateFiles: [] };
276
+ const scss = files.cssFiles.some((file) => file.endsWith('.scss'));
277
+ const templateExtensions = new Set(files.templateFiles.map((file) => path.extname(file)));
278
+ const typescript = templateExtensions.has('.ts') || templateExtensions.has('.tsx');
279
+ const otherTemplates = ['.vue', '.svelte', '.astro'].filter((extension) => templateExtensions.has(extension));
280
+ const glob = lintGlob(cwd, files.cssFiles);
281
+ const printStylelint = () => {
282
+ out.push(withoutStylelint ? ' To audit your stylesheets too, install Stylelint and the plugin:' : ' Install:', '');
283
+ out.push(` ${stylelintInstallLine({ scss, tailwindConfig: profile === 'tailwind' })}`, '');
284
+ out.push(` ${withoutStylelint ? 'then paste' : 'Then paste'} this into .stylelintrc.json${stack.hasExistingConfig ? ' (merge with your existing config)' : ''}:`, '');
285
+ const fallbackScale = scale.source === 'fallback' ? scale.values : null;
286
+ out.push(JSON.stringify(suggestedStylelintConfig({ fallbackScale, nextjs: stack.nextjs, profile, scss, tokenFiles }), null, 2).replace(/^/gm, ' '));
269
287
  out.push('');
288
+ };
289
+ const printEslint = () => {
290
+ out.push(' Tailwind class strings need the ESLint companion. Install:', '');
291
+ out.push(` ${eslintInstallLine({ typescript })}`, '');
292
+ out.push(' Then paste this into eslint.config.js:', '');
293
+ out.push(eslintSnippet(scale.values, { typescript }).replace(/^/gm, ' '));
294
+ if (otherTemplates.length > 0) {
295
+ out.push('', ` ${otherTemplates.join(', ')} files need their parser in a block of their own; see the`);
296
+ out.push(' eslint-plugin-rhythmguard README, "Other file types".');
297
+ }
298
+ out.push('');
299
+ };
300
+
301
+ // Without Stylelint the class strings are what was audited, so their config comes first.
302
+ if (stack.tailwind && withoutStylelint) {
303
+ printEslint();
304
+ printStylelint();
305
+ } else {
306
+ printStylelint();
307
+ if (stack.tailwind) {
308
+ printEslint();
309
+ }
270
310
  }
271
311
 
272
312
  out.push(' Next');
273
- out.push(...nextCommands(auditTokenSources).map((line) => ` ${line}`));
313
+ out.push(...nextCommands(auditTokenSources, { eslint: stack.tailwind, glob, stylelint: !withoutStylelint }).map((line) => ` ${line}`));
274
314
  out.push('');
275
315
 
276
316
  process.stdout.write(`${out.join('\n')}\n`);
@@ -3,7 +3,6 @@
3
3
  const { readJsonFile } = require('./json');
4
4
  const { parseTokenValueLength } = require('./token-sources');
5
5
 
6
- const { spawnSync } = require('node:child_process');
7
6
  const fs = require('node:fs');
8
7
  const path = require('node:path');
9
8
  const {
@@ -288,70 +287,15 @@ function loadTailwindSpacingFromRequire(resolvedPath) {
288
287
  }
289
288
  }
290
289
 
291
- function loadTailwindSpacingFromDynamicImport(resolvedPath) {
292
- const script = [
293
- 'const { pathToFileURL } = require("node:url");',
294
- '(async () => {',
295
- ' try {',
296
- ' const configPath = process.argv[1];',
297
- ' const loaded = await import(pathToFileURL(configPath).href);',
298
- ' const config = loaded && typeof loaded.default === "object" ? loaded.default : loaded;',
299
- ' if (!config || typeof config !== "object" || Array.isArray(config)) {',
300
- ' process.stdout.write("{}");',
301
- ' return;',
302
- ' }',
303
- ' const theme = config.theme && typeof config.theme === "object" && !Array.isArray(config.theme)',
304
- ' ? config.theme',
305
- ' : null;',
306
- ' if (!theme) {',
307
- ' process.stdout.write("{}");',
308
- ' return;',
309
- ' }',
310
- ' const spacing = theme.spacing && typeof theme.spacing === "object" && !Array.isArray(theme.spacing)',
311
- ' ? theme.spacing',
312
- ' : {};',
313
- ' const extendSpacing = theme.extend && typeof theme.extend === "object" && !Array.isArray(theme.extend) &&',
314
- ' theme.extend.spacing && typeof theme.extend.spacing === "object" && !Array.isArray(theme.extend.spacing)',
315
- ' ? theme.extend.spacing',
316
- ' : {};',
317
- ' process.stdout.write(JSON.stringify({ ...spacing, ...extendSpacing }));',
318
- ' } catch {',
319
- ' process.exit(1);',
320
- ' }',
321
- '})();',
322
- ].join('\n');
323
-
324
- const child = spawnSync(process.execPath, ['-e', script, resolvedPath], {
325
- encoding: 'utf8',
326
- timeout: 5000,
327
- });
328
-
329
- if (child.error || child.status !== 0) {
330
- return null;
331
- }
332
-
333
- if (typeof child.stdout !== 'string' || child.stdout.trim() === '') {
334
- return null;
335
- }
336
-
337
- try {
338
- const parsed = JSON.parse(child.stdout);
339
- return isPlainObject(parsed)
340
- ? parsed
341
- : null;
342
- } catch {
343
- return null;
344
- }
345
- }
346
-
347
290
  function loadTailwindSpacing(resolvedPath) {
348
291
  if (tailwindSpacingCache.has(resolvedPath)) {
349
292
  return tailwindSpacingCache.get(resolvedPath);
350
293
  }
351
294
 
352
- const spacing =
353
- loadTailwindSpacingFromRequire(resolvedPath) ||
354
- loadTailwindSpacingFromDynamicImport(resolvedPath);
295
+ // require() loads CommonJS and ES module configs alike on every supported Node
296
+ // (require(esm) is on from 20.19). A config that uses top-level await cannot be
297
+ // required and is not read; point scaleSources at the built CSS instead.
298
+ const spacing = loadTailwindSpacingFromRequire(resolvedPath);
355
299
 
356
300
  tailwindSpacingCache.set(resolvedPath, spacing);
357
301
  return spacing;
package/types/audit.d.ts CHANGED
@@ -114,6 +114,8 @@ export interface AuditScanned {
114
114
  scssSkipped?: number;
115
115
  /** Stylesheets Stylelint skipped because the project's own .stylelintignore excludes them. */
116
116
  stylelintIgnored?: number;
117
+ /** Stylesheets found but not audited because Stylelint is not installed. */
118
+ stylelintMissing?: number;
117
119
  /** Stylesheets not audited because they look vendored, generated, test-only, minified or built. 0 with `includeNonAuthored`. */
118
120
  nonAuthoredSkipped?: number;
119
121
  /** The stylesheets counted in `nonAuthoredSkipped`, with why each was skipped. */