@projectwallace/css-parser
v0.20.0
Published
High-performance CSS lexer and parser, optimized for CSS inspection and analysis
Maintainers
Readme
CSS Parser
[!WARNING] This is a very experimental CSS parser. Expect several bugs and inconveniences!
High-performance CSS parser built for static analysis and tooling
Parses large CSS files in microseconds with a fixed-size memory arena — no garbage collection pressure, no per-node allocations, no surprises. If you're building a formatter, linter, or analysis tool and need raw speed with precise source locations, this is built for that.
Heavily influenced by CSSTree. Some parsing mechanics are shared, but the memory model, architecture, and API are fundamentally different — not a fork.
Features
- Full modern CSS — CSS Nesting,
:is(),:where(),:has(),@layer,@container - Error-tolerant — keeps parsing through malformed input; one bad rule won't kill the file
- Precise source locations — line, column, offset, and length on every node
- Tiny footprint — tree-shakeable subparsers; as small as 278 bytes gzipped, < 16 kB worst case
Installation
npm install @projectwallace/css-parserUsage
import { parse, STYLE_RULE, DECLARATION } from '@projectwallace/css-parser'
const ast = parse(`
body {
color: red;
margin: 0;
}
@media (min-width: 768px) {
.container {
max-width: 1200px;
}
}
`)
// Iterate over top-level rules
for (const rule of ast) {
if (rule.type === STYLE_RULE) {
const selector = rule.first_child
console.log(`Selector: ${selector.text}`)
// Iterate over declarations
for (const node of rule) {
if (node.type === DECLARATION) {
console.log(` ${node.property}: ${node.value}`)
}
}
}
}Performance
- Zero allocations during parsing — memory is reserved upfront using real-world heuristics; the GC never runs mid-parse
- Cache-friendly layout — all nodes live in a single contiguous arena, making sequential access fast
- Location tracking with no penalty — full line, column, and offset data without slowing the parser down
- No syntax validation — skipping spec checks and MDN data means nothing gets in the way of speed
API
Everything is exported from the package root. Each part is also available from its own entry point, so you can import only what you need. Node properties and return types ship as TypeScript types.
Entry points
@projectwallace/css-parser— everything below, except theLexerandParserclasses/parse—parse,Parser,ParserOptions/parse-selector—parse_selector,parse_selector_list/parse-atrule-prelude—parse_atrule_prelude/parse-declaration—parse_declaration/parse-value—parse_value/parse-anplusb—parse_anplusb/parse-dimension—parse_dimension/tokenizer—tokenize,Lexer/walker—walk,traverse,walk_declarations,walk_selectors,walk_values,SKIP,BREAK/nodes— node type constants (STYLE_RULE,DECLARATION, …),NODE_TYPES/node-types— type guards (is_declaration,is_rule, …) and node types (CSSNode,Rule, …)/string-utils—is_custom,is_vendor_prefixed,strip_vendor_prefix,strip_value_hack,property_basename,str_equals,str_starts_with,str_index_of/token-types— token type constants (TOKEN_*)
parse(source, options?)
Returns the root StyleSheet node. Nodes are iterable and expose first_child, next_sibling, children, text, line, column, start, end and length.
const ast = parse('body { color: red; }')
const rule = ast.first_child
rule.block.first_child.property // "color"
rule.block.first_child.value.text // "red"Options:
parse_values(defaulttrue) — parse declaration values into nodesparse_selectors(defaulttrue) — parse selectors into nodesparse_atrule_preludes(defaulttrue) — parse at-rule preludes into nodeson_comment— called for every comment ({ start, end, length, line, column }); comments are never part of the tree
Sub-parsers
parse_selector('a.b > c').children.map((part) => part.text) // ["a", ".b", ">", "c"]
parse_selector_list('h1, h2').children.map((s) => s.text) // ["h1", "h2"]
const decl = parse_declaration('color: red !important')
decl.property // "color"
decl.is_important // true
for (const node of parse_value('10px 20px')) {
node.type_name // "Dimension"
}
const [query] = parse_atrule_prelude('media', '(min-width: 768px)') // name without the `@`
query.type_name // "MediaQuery"
parse_dimension('1.5e3s') // { value: 1500, unit: "s" } (no validation; no leading number gives `value: 0`)walk(node, callback) and traverse(node, { enter, leave })
Both walk the tree depth-first. Return SKIP to skip the children of a node and BREAK to stop entirely. walk also passes a depth that counts rule and at-rule nesting. traverse calls enter before and leave after the children, both with the same depth (leave still runs after SKIP, but not after BREAK).
walk(ast, (node) => {
if (node.type === DECLARATION) return BREAK
})
traverse(ast, {
enter(node) {
if (node.type === AT_RULE) return SKIP
},
leave(node) {},
})walk_declarations, walk_selectors and walk_values
Typed walkers that only visit what you ask for and never enter irrelevant subtrees, so they are faster than filtering inside walk. BREAK stops the walk.
// every declaration, including nested rules and at-rules (values and selectors are not entered)
walk_declarations(ast, (decl) => {
decl.property
})
// skip whole at-rules by lowercase name (vendor prefixes ignored), also supported by `walk_selectors`
walk_declarations(ast, (decl) => {}, { skip_atrules: new Set(['font-face', 'keyframes']) })
// every complex selector: `a` and `b > c` in `a, b > c {}`
walk_selectors(ast, (selector) => {})
// also selectors nested in pseudo-classes: `b` in `a:is(b)`. Return SKIP to skip a selector's nested selectors
walk_selectors(ast, (selector) => {}, { recursive: true })
// skip selectors in at-rule preludes (`@scope (.a) to (.b)`, `selector()`) and whole at-rules
walk_selectors(ast, (selector) => {}, {
skip_atrule_preludes: true,
skip_atrules: new Set(['keyframes']),
})
// nodes in a declaration's value. Return SKIP to skip function arguments
walk_values(decl, (node) => {
if (node.type === FUNCTION) return SKIP
})node.parent and node.closest(match)
parent is the parent node (null for the root); closest(match) is the nearest ancestor that is of a node type (AT_RULE) or satisfies a predicate or type guard (is_atrule), not counting the node itself; it returns null when there is none. Passing a type constant climbs without creating wrapper objects, so prefer it over a predicate. Nothing is stored while parsing: the first call on a tree builds a lookup table in one pass (4 bytes per node), so you only pay for it if you use it.
walk(ast, (node) => {
if (node.type === DECLARATION) {
node.closest(AT_RULE)?.name // "media" for a declaration inside @media
node.closest((n) => is_atrule(n) && n.name === 'media') // by predicate
}
})tokenize(source, on_token)
Calls on_token(type, start, end, line, column) for every token. Whitespace and comments are emitted as tokens (TOKEN_WHITESPACE, TOKEN_COMMENT).
tokenize('a { color: red }', (type, start, end, line, column) => {
console.log(type, start, end)
})Node types, type guards and clone()
Type guards such as is_declaration() narrow a node to its specific type. node.clone({ deep?, locations? }) returns a mutable plain-object copy of a node.
const decl = parse('a { color: red }').first_child.block.first_child
is_declaration(decl) // true
decl.type_name // "Declaration"String helpers
Allocation-free helpers, handy when working with node names. The lowercase argument is always the first one.
is_custom('--primary') // true
is_vendor_prefixed('-webkit-transform') // true
strip_vendor_prefix('-webkit-transform') // "transform"
str_equals('media', 'MEDIA') // true
str_starts_with('webkit', 'WEBKIT-transform') // true
str_index_of('color', 'background-COLOR') // 11Non-goals
- No syntax validation — CSS structure is your responsibility; the parser accepts anything valid or not
- No preprocessor syntax — Sass, Less, and Stylus are out of scope; this parser targets plain CSS only
- Tree operations - Manipulating the AST is not within scope of this library
License
MIT
