A tool set for CSS: fast detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations
npx @tessl/cli install tessl/npm-css-tree@3.1.0CSS Tree is a comprehensive tool set for CSS providing a fast, detailed parser that converts CSS to Abstract Syntax Trees (AST), along with complementary tools for AST traversal (walker), CSS generation from AST (generator), and syntax validation (lexer). Built with performance and W3C specification compliance in mind, it supports various levels of parsing detail, graceful error recovery, and is designed for CSS analysis and source-to-source transformation tasks.
npm install css-treeimport * as csstree from 'css-tree';For CommonJS:
const csstree = require('css-tree');Modular imports for tree-shaking and performance:
import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as generator from 'css-tree/generator';
import * as lexer from 'css-tree/lexer';
import * as utils from 'css-tree/utils';import * as csstree from 'css-tree';
// Parse CSS to AST
const ast = csstree.parse('.example { color: red; }');
// Traverse AST and modify it
csstree.walk(ast, (node) => {
if (node.type === 'ClassSelector' && node.name === 'example') {
node.name = 'hello';
}
});
// Generate CSS from AST
console.log(csstree.generate(ast));
// Output: .hello{color:red}
// Syntax validation
const valueAst = csstree.parse('red 1px solid', { context: 'value' });
const matchResult = csstree.lexer.matchProperty('border', valueAst);
console.log(matchResult.isType(valueAst.children.first, 'color')); // trueCSS Tree is built around several key components:
Core CSS parsing functionality that converts CSS source code into detailed Abstract Syntax Trees with configurable parsing levels and error recovery.
function parse(css: string, options?: ParseOptions): CssNode;
interface ParseOptions {
context?: 'stylesheet' | 'atrule' | 'atrulePrelude' | 'mediaQueryList' | 'mediaQuery' | 'rule' | 'selectorList' | 'selector' | 'block' | 'declarationList' | 'declaration' | 'value';
atrule?: string;
property?: string;
positions?: boolean;
filename?: string;
offset?: number;
line?: number;
column?: number;
parseAtrulePrelude?: boolean;
parseRulePrelude?: boolean;
parseValue?: boolean;
parseCustomProperty?: boolean;
}Converts Abstract Syntax Trees back into CSS source code with configurable formatting and source map generation.
function generate(ast: CssNode, options?: GenerateOptions): string;
interface GenerateOptions {
sourceMap?: boolean;
file?: string;
decorateNode?: (handlers: object) => void;
}Low-level CSS tokenization following W3C CSS Syntax specification for breaking CSS source into tokens.
function tokenize(source: string, onToken: (type: number, start: number, end: number) => void): void;
const tokenTypes: {
EOF: 0;
Ident: 1;
Function: 2;
AtKeyword: 3;
Hash: 4;
String: 5;
Number: 10;
Dimension: 12;
// ... additional token types
};Comprehensive AST traversal utilities for walking, searching, and manipulating CSS Abstract Syntax Trees.
function walk(ast: CssNode, visitor: WalkVisitor): void;
function find(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode | null;
function findLast(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode | null;
function findAll(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode[];
type WalkVisitor = (node: CssNode, item: ListItem<CssNode>, list: List<CssNode>) => void;Advanced CSS syntax validation and matching against W3C specifications with support for properties, at-rules, and value types.
const lexer: Lexer;
class Lexer {
checkStructure(ast: CssNode): void;
matchProperty(propertyName: string, value: CssNode): MatchResult;
matchType(typeName: string, value: CssNode): MatchResult;
match(syntax: string, value: CssNode): MatchResult;
}
interface MatchResult {
matched: CssNode | null;
error: Error | null;
isType(node: CssNode, type: string): boolean;
getTrace(node: CssNode): TraceNode[];
}Collection of utility functions for CSS identifier, string, and URL encoding/decoding, plus AST manipulation helpers.
// Identifier utilities
namespace ident {
function encode(str: string): string;
function decode(str: string): string;
}
// String utilities
namespace string {
function encode(str: string, apostrophe?: boolean): string;
function decode(str: string): string;
}
// URL utilities
namespace url {
function encode(str: string): string;
function decode(str: string): string;
}
// AST utilities
function clone(node: CssNode): CssNode;
function toPlainObject(ast: CssNode): object;
function fromPlainObject(ast: object): CssNode;Specialized data structures including the List class for efficient AST node manipulation and various stream classes for tokenization.
class List<T> {
constructor();
readonly size: number;
readonly isEmpty: boolean;
readonly first: T;
readonly last: T;
forEach(fn: (item: T, index: number) => void): void;
map<U>(fn: (item: T, index: number) => U): List<U>;
filter(fn: (item: T, index: number) => boolean): List<T>;
toArray(): T[];
fromArray(array: T[]): this;
}interface CssNode {
type: string;
loc?: SourceLocation;
children?: List<CssNode>;
}
interface SourceLocation {
source?: string;
start: Position;
end: Position;
}
interface Position {
offset: number;
line: number;
column: number;
}
interface ListItem<T> {
prev: ListItem<T> | null;
next: ListItem<T> | null;
data: T;
}