Skip to content

v10: full rewrite; collector-based API; single-pass, multiplexed visitor - #647

Open
bartveneman wants to merge 138 commits into
mainfrom
claude/sleepy-tesla-tu72wq
Open

bartveneman wants to merge 138 commits into
mainfrom
claude/sleepy-tesla-tu72wq

Conversation

@bartveneman

@bartveneman bartveneman commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

A rewrite of the analyzer around collectors: small units that subscribe to the CSS nodes they need, run in one shared walk, and own their own results.

import { analyze } from '@projectwallace/css-analyzer'
import { colors, font_sizes, z_indexes } from '@projectwallace/css-analyzer/collectors'

const result = analyze(css, { colors: colors(), font_sizes: font_sizes(), z: z_indexes() })
result.colors.unique.get('red') // { count: 3 }

What's new

  • Collectors (/collectors): one module each. The result type is inferred from the object you pass. The parser only parses what the collectors need (selectors, values, at-rule preludes).
  • One counting shape everywhere: { total, total_unique, unique: Map<string, { count, locations? }> }. useLocations is gone; locations are opt-in per collector. sequence: true keeps numeric series in source order (for charts).
  • stylesheet() reports size, lines, source_lines_of_code, complexity (equal to 9.x), comments and embedded content (in the standard count shape).
  • Statistics are derived from counted values with summarize_numbers, summarize_specificity and summarize.
  • Public collector contract: define_collector() plus the counters, so you can write collectors with the same API the built-ins use.
  • Presets (/presets): analyze_all (every collector, flat) and analyze_design_tokens.
  • Utilities (/selectors, /values, /atrules, /properties, /stylesheet) take text or a parsed node and return plain data: no callbacks, no parser nodes in results. New ones: analyze_transition(), get_animation_names(), get_declared_container_names(), is_gradient_function() (vendor prefix aware) and get_container_query_name(). DefinedUsed and KeywordSet live in /utils/collections.
  • Layering is enforced by lint (no-restricted-imports): utilities and utils/ never import engine/, collectors/ or presets/. See "Where does code go?" in CONTRIBUTING.md.
  • The engine and collectors use @projectwallace/css-parser directly (no adapter layer: simplicity over flexibility).

Breaking changes

See MIGRATION.md. Highlights:

  • analyze() now takes collectors.
  • Node >= 22.18 and .ts import specifiers in the source.
  • unique and by_context are Maps (Object.fromEntries() gives a plain object).
  • snake_case for all functions, options and result keys; const and function declarations are enforced by lint.
  • Utilities renamed and reshaped (for example getSpecificity -> get_specificity, callbacks -> returned arrays).
  • Selectors inside at-rule preludes (@scope (.a) to (.b), @supports selector(...)) are no longer counted by selectors(), specificity() and stylesheet() (source_lines_of_code, complexity). 9.x counted them.
  • A few behaviour fixes are listed in MIGRATION.md (var() use tracking in every property, consistent lowercasing, per-property counts use the normalized property by default, animation-name: red is no longer a color).

closes #362
prepares for #330
prepares for #335
closes #513
closes #602
closes #603
closes #605
closes #606
closes #607
refs #646

@pkg-pr-new

pkg-pr-new Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@projectwallace/css-analyzer@7a5ca6e

commit: 7a5ca6e

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Package Size Increase

📦 Package 📏 Base Size 📏 Source Size 📈 Size Change
@projectwallace/css-analyzer 22.6 kB 37.1 kB +14.5 kB

@bartveneman bartveneman left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some preliminary feedback, plz process first

Comment thread .oxlintrc.json Resolved
Comment thread src/test-utils.ts Resolved
Comment thread tsdown.config.ts Resolved
@bartveneman
bartveneman force-pushed the claude/sleepy-tesla-tu72wq branch from 4e61df1 to 278ef6f Compare November 7, 2026 18:49
Comment thread src/collectors/atrules.ts Resolved
Comment thread src/collectors/atrules.ts Resolved
Comment thread src/collectors/atrules.ts Resolved
Comment thread CONTRIBUTING.md Resolved
Comment thread src/collectors/atrules.ts Resolved
Comment thread src/collectors/line-heights.ts Resolved
Comment thread src/collectors/all-collectors.test.ts Resolved
Comment thread src/test-utils.ts Resolved
Comment thread src/input.ts Resolved
Comment thread src/engine/counter.ts Resolved
Comment thread src/engine/counter.ts Resolved
@bartveneman bartveneman changed the title v10: collector-based API v10: full rewrite; collector-based API; single-pass, multiplexed visitor Nov 8, 2026
claude added 16 commits November 8, 2026 22:50
Adds the new engine next to the legacy analyze(), exposed as the
temporary `./next` subpath until the old code is removed:

- adapter/css-parser: the only module that talks to the parser
- define_collector, create_analyzer, analyze and merge
- one count shape (create_counter, merge_counts, summarize) with
  opt-in locations
- declarative dispatch table: parse options follow subscriptions,
  one shared value walk, lazy memoized declaration facts
- incremental add() with per-file `source` on locations
- oxlint overrides (prefer-const, function declarations, adapter-only
  parser imports) for the new code, plus a pkg.pr.new preview workflow

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Reworks the public utils on the /selectors, /values and /atrules
subpaths to one contract: input is `string | node`, output is plain
data. No callbacks, no parser nodes in results.

- get_specificity, compare_specificity, get_complexity (number[]),
  get_vendor_prefixes, get_accessibility_selectors, get_combinators
- analyze_animation, destructure_font_shorthand, is_value_reset,
  get_prefixed_values, get_value_browserhacks
- get_supports_browserhacks, get_media_browserhacks
- colour keyword sets renamed to snake_case
- remove deprecated is_ie9_hack

The legacy analyze() is adapted to the new utils and its output is
unchanged. Adds contract tests (text vs node parity) for each util.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Ports the nine collectors css-design-tokens reads onto the new engine:
colors (+ formats, per-property counts), font_sizes, font_families,
line_heights, gradients, box_shadows, border_radiuses, durations and
timing_functions, exposed on the new ./collectors subpath. The
./presets subpath adds analyze_design_tokens and design_tokens_collectors.

Engine additions the collectors needed:
- value handlers receive the node kind
- lazy, shared ctx facts: clean_value_text and font_shorthand
- context counters track contexts only with `contexts: true`

Output matches the 9.x analyzer on a fixture covering all nine
(parity test). Deliberate differences: contexts are keyed by the
normalized property, and values are lowercased consistently.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Covers the stylelint use cases next to colors: max-unique-z-indexes,
max-unique-colors and max-average-selector-specificity.

- z_indexes counts z-index values
- specificity counts every selector as "a,b,c"; summarize_specificity
  derives min, max, sum, mean and mode and matches the 9.x analyzer
- summarize_numbers/summarize_frequencies derive min, max, range, sum,
  mean, mode and median from counted values, so averages stay mergeable
  across files and runs
- the engine no longer descends into selectors nested in :is()/:not(),
  so each selector is dispatched once

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds the collectors for every other group of the 9.x report, so the
full report can now be built from collectors:

- stylesheet (size, lines, comments, embedded content)
- atrules (all at-rules incl. font-face, import, media, supports,
  keyframes, container, layer, property, function, scope)
- rules, selectors, declarations, properties
- text_shadows, displays, units, keywords, resets, value_prefixes,
  value_browserhacks, value_complexity, animation_names

Names that are defined and used (keyframes, containers, layers,
custom properties, anchor names) are tracked per collector and merge
across files. Numeric series are stored as counted values so min, max,
mean, mode and median stay derivable and mergeable.

Every group has a parity test against the 9.x analyzer on one fixture.
The engine now skips @supports conditions, so they are no longer
mistaken for declarations.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- analyze_all: every collector in one call, flat snake_case result
  (one key per collector), mergeable with merge()
- analyze_compat: the 9.x report (nested, camelCase, same numbers),
  built from the collectors; `useLocations` and `__meta__` are gone
- opt-in `sequence: true` on the counting collectors keeps numeric
  series in source order (9.x `items`, used for charts); compat turns
  it on
- context collectors take `property: 'as_written'` for 9.x-style
  per-property keys; compat uses it
- `pnpm test:compat` runs the existing 9.x topic tests against
  analyze_compat (tests about useLocations are skipped); CI runs it
- shared fixtures, preset tests and a knip config that treats every
  test file as an entry

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…alyzer

The new API now lives at `.`: analyze, create_analyzer, merge,
define_collector, the counters and summaries. The 9.x analyze() is
gone; `analyze_compat` from `/presets` returns the same report.

- delete the monolithic analyze(), useLocations, Collection,
  ContextCollection and AggregateCollection, plus deprecated exports
  (hasVendorPrefix, isIe9Hack)
- freeze the 9.9.6 output as golden JSON; analyze_compat must match it
- run the 9.x topic tests against analyze_compat; port the
  useLocations tests to collectors
- apply prefer-const and function declarations to all of src, rename
  the remaining camelCase helpers
- drop the temporary `./next` subpath and the compat test config
- rewrite the readme for pnpm and the collector API; add MIGRATION.md

BREAKING CHANGE: see MIGRATION.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… selectors); rename remaining camelCase locals to snake_case

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The 9.x topic tests ran the whole analyzer for every case. They are now
unit tests that live next to the code they test:

- one test file per collector in src/collectors, each running only that
  collector (src/test-utils.ts has plain() and series() to compare
  results)
- direct tests for the utilities (specificity, complexity, font
  shorthand, browserhacks, prefixes, resets, property helpers) and for
  the adapter, using test.each tables
- the only integration test left is the compat preset against the
  golden 9.x output
- add CONTRIBUTING.md with the style and test conventions

Also rename all remaining camelCase locals, parameters and helpers to
snake_case, and fix walk_value reporting the value node itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
pkg.pr.new publishes previews to its own registry, not npm, so the
trusted publishing audit does not apply.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Remove our own preview workflow; main now has pkg-pr-new.yml.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The adapter layer was 435 lines of mostly thin wrappers for a parser
swap that is not planned. Simplicity wins over flexibility:

- the engine parses and walks with css-parser directly; collector
  handlers get typed nodes (Declaration, Rule, Atrule, Selector)
- helpers that only one collector needs now live in that collector;
  the small shared ones are in collectors/shared.ts
- text-or-node input handling for the utilities moves to src/input.ts
- remove the lint rule that restricted parser imports

No behaviour change: the full suite, golden 9.x output included, still
passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The 9.x compatibility layer (analyze_compat, compat_collectors, the
golden 9.x output and the tests that use them) moves to its own pull
request so the package stays smaller and it can be revisited later.

The core keeps what compat needed from the collectors: `sequence`,
`property: 'as_written'`, and the collectors themselves. The tests that
ran through analyze_compat now run the collectors directly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…u72wq

Keeps the v10 src/index.ts and analyze_animation (units() already counts the shorthands), and
ports main's new units test table (#672) to the collector.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…u72wq

Takes css-parser ~0.20.0 and the \0 media hack on a dimension unit (#674); keeps the v10
src/index.ts and test files.
…x colors, escaped ID selectors

css-parser 0.20 parses 10px\9 and 0\9 as dimensions with an escaped unit. units() strips the hack from
the unit and ignores a unit that is only a hack, colors() counts the hex without it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…_names, get_container_query_name, is_gradient_function

New pure utilities (text or node in, plain data out) for #603, #605, #606 and #607;
analyze_animation also reports the delays. The collectors use the same helpers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
-webkit-linear-gradient and the old -webkit-gradient() count, like before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Member Author

Proposal: make css-analyzer utils reusable by stylelint-plugin

Based on migrating stylelint-plugin to this preview (projectwallace/stylelint-plugin#285). Line counts are rough, from src/ (non-test).

Problem

v10 utils return plain data (string[], number[]). That is great for analysis, but a lint rule must point at the exact thing it found. Today we have to guess or re-walk the AST:

  • no-value-browserhacks: value.includes(hack) ? hack : value to find where the hack is.
  • max-selector-complexity: parses the selector list itself and zips with get_complexity() by index to get start/end.
  • no-duplicate-container-names: stays on the AST because get_declared_container_names() has no positions.
  • max-unique-font-sizes/line-heights/families: destructure_font_shorthand() returns text only, so we report with a text search.
  • Rules still re-implement what the collectors already know: font shorthand, @font-face/@property contexts, var() fallbacks, color formats, gradients, shadows, units, z-indexes.

get_combinators() already returns { name, loc }; that is the right direction and should become the norm.

Callback vs. locations vs. both

Option Pros Cons
A. Restore callbacks (fn(input, on_match)) no allocation, early exit, node access second API surface; v10 deliberately moved away
B. Return Match[] with locations one API, easy to test, composable small allocation per call
C. Both max flexibility double the surface to document and test

Recommendation: B only. Every util returns Match[] where

type Match = Location & { text: string } // Location = { line, column, offset, length } (already exported)
  • text is the matched text as written (what string[] holds today), so existing callers change from hack to hack.text.
  • Offsets are relative to the text that was parsed. Document this: for a string input, the string; for a node input, the source that node came from. Callers add their own base offset.
  • Structured utils (analyze_animation, destructure_font_shorthand, analyze_transition) return Match[] per part instead of string[], and FontShorthand fields become Match | undefined.
  • get_complexity() returns { complexity: number } & Location per selector.
  • If allocation ever matters, add a generator variant later; do not ship callbacks now.

The unit of reuse: extractors

Collectors are today "extractor + counter" fused together. Export the extractor separately and build the collector from it, so lint rules and the analyzer share one code path and cannot drift apart.

// per declaration; returns [] when the property is not relevant
colors.extract(property: string, value: ValueInput): Match[]   // + format: 'hex' | 'named' | 'rgb' | ...
font_sizes.extract(property, value)   // handles `font` shorthand
font_families.extract(property, value)
line_heights.extract(property, value)
z_indexes.extract(property, value)
gradients.extract(property, value)
box_shadows.extract / text_shadows.extract / border_radiuses.extract
units.extract / durations.extract / timing_functions.extract
// and the matching property filter, so walkDecls can skip early:
colors.properties: KeywordSet

Why per-declaration instead of calling analyze() per rule: stylelint hands us a PostCSS root, so analyze(string) would parse every file again per rule, and for postcss-html / CSS-in-JS syntaxes the offsets would be relative to the whole file rather than the CSS. Extractors work on one declaration value, so they are immune to both problems.

Defined/used names

Rules: no-unused-keyframes, no-unused-container-names, no-unknown-container-names, no-duplicate-*, no-unused-font-faces, no-unused-layers.

  • Make DefinedUsed<T = never> generic with an optional payload per name (we keep a node reference for reporting). Replaces our own 50-line copy.
  • Add name extractors returning Match[]: get_font_families(value) (split, unquoted, incl. shorthand), get_keyframes_name(prelude), get_layer_names(prelude), get_anchor_names(value).
  • Existing get_animation_names, get_declared_container_names, get_container_query_name just gain locations.

Media / container feature bounds

Our media-conditions.ts (337 lines) is the largest piece of custom analysis; three rules (no-unreachable-media-conditions, no-static-media-queries, no-static-container-queries, ~500 lines) sit on top of it.

Proposal: get_feature_bounds(prelude): { feature, direction, value, unit, inclusive } & Location covering min-/max-, equality and range syntax (width > 1px, 50px <= width <= 100px). Contradiction detection stays in the lint package. A "static value" flag per feature would cover the no-static-* rules.

Constants become predicates

  • is_spacing_reset_property(), is_border_radius_property(), is_shorthand_property(): case-insensitive, hack/vendor aware, same shape as is_gradient_function().
  • Bug: spacing_reset_properties is missing margin-inline-start, which is why max-spacing-resets still uses its own regex.
  • All keyword collections should be KeywordSet; today shorthand_properties and spacing_reset_properties are plain Sets that need pre-lowercased input.

Packaging

  • Make @projectwallace/css-parser a peerDependency. The utils accept parsed nodes, so a second parser copy or version mismatch breaks at runtime (we hit for_each is not a function until we bumped to 0.20).
  • Keep sub-exports granular (/values, /atrules, /selectors, /properties); we already import only from those.

Priorities (bang for buck)

# Change Analyzer effort Stylelint-plugin lines removed (est.)
1 Match return type on all existing utils low (nodes already known) ~100: guess logic, re-parsing, AST walks in container/selector/hack rules
2 Per-declaration extractors for the max-unique-* family medium (split collectors) ~350: loops in 14 rules, color and font-family helpers
3 Generic DefinedUsed<T> + name extractors low ~150
4 get_feature_bounds medium ~300
5 Predicates + fix margin-inline-start + KeywordSet trivial ~30

Total: roughly 900 lines, a quarter to a third of the non-test rule code.

Open questions

  1. Should offsets for node inputs be relative to the node's own source or absolute? (We pass parse_value(declaration.value), so relative-to-value is what we need.)
  2. Should Match.text be normalized (lowercased, unquoted) or as written? Rules that count unique values need a normalized form; suggest text as written plus a normalize option on the extractors.
  3. Does extract live on the collector (colors.extract) or as a standalone export (extract_colors)? The latter tree-shakes better.

Generated by Claude Code

claude and others added 22 commits November 15, 2026 18:31
…operty, is_border_radius_property), fix missing margin-inline-start

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
get_vendor_prefixes, get_accessibility_selectors, get_combinators, get_complexity, the browserhack utils, get_prefixed_values, analyze_animation, analyze_transition, get_animation_names, get_declared_container_names, get_container_query_name and destructure_font_shorthand now return Match ({ text, line, column, offset, length }) so tools like linters can point at what was found.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…tch<number>

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…mes_name, get_layer_names, get_font_families, get_anchor_names

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…k, lowercase_unless_var, get_list_items, get_clean_value_text)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…gic with the collectors

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…xtract_border_radiuses

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e package size)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds the pieces the stylelint plugin needs from the analyzer, so the
plugin can stay a thin wrapper:

- `/atrules`: `get_static_features()`, `get_query_bounds()` and
`find_contradiction()` for `@media`/`@container`/`@import` conditions,
and `validate_property_registration()` for `@property`.
- `/values`: `deep` option for `get_font_families()` (reads `var()`
fallbacks), and the unit `KeywordSet`s (`length_units`, `angle_units`,
`time_units`, `flex_units`, `resolution_units`).
- `DefinedUsed`: `defined_size` and `unused_definitions()`.
Replace offset with start_offset and add the exclusive end_offset, so consumers no longer compute offset + length. length stays.
start_offset and end_offset carry the same information.
Values, selectors and at-rule preludes are no longer accepted as text: the consumer parses them. The at-rule name arguments are gone; queries are found by node type. Tests parse with parse_value, parse_selector_list and a parse_prelude test helper.
get_complexity and get_specificity return a single result; get_vendor_prefixes, get_accessibility_selectors and get_combinators take one selector too. A selector list is walked by the consumer. as_selectors is gone.
Its location is the caller's: collectors get it from the counter, tools from the selector node.
hack, name, selector, feature, unit and text carry what a util derives. Whole-value extractors only take the value. get_query_bounds and get_static_features say which queries have not/or instead of hiding them. Location helpers and counters take options.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment