🌜
🌞
css-tree

css-tree

v2.1.0

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

npm install css-tree

README

CSSTree logo

CSSTree

NPM version Build Status Coverage Status NPM Downloads Twitter

CSSTree is 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. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.

Features

  • Detailed parsing with an adjustable level of detail

    By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see AST format for all possible node types). The parsing detail level can be changed through parser options, for example, you can disable parsing of selectors or declaration values for component parts.

  • Tolerant to errors by design

    Parser behaves as spec says: "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (Raw) that allows processing it later.

  • Fast and efficient

    CSSTree is created with focus on performance and effective memory consumption. Therefore it's one of the fastest CSS parsers at the moment.

  • Syntax validation

    The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses mdn/data as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.

Projects using CSSTree

  • Svelte – Cybernetically enhanced web apps
  • SVGO – Node.js tool for optimizing SVG files
  • CSSO – CSS minifier with structural optimizations
  • NativeScript – NativeScript empowers you to access native APIs from JavaScript directly
  • react-native-svg – SVG library for React Native, React Native Web, and plain React web projects
  • penthouse – Critical Path CSS Generator
  • Bit – Bit is the platform for collaborating on components
  • and more...

Documentation

Tools

Usage

Install with npm:

npm install css-tree

Basic usage:

import * as csstree from 'css-tree';

// parse CSS to AST
const ast = csstree.parse('.example { world: "!" }');

// 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));
// .hello{world:"!"}

Syntax matching:

// parse CSS to AST as a declaration value
const ast = csstree.parse('red 1px solid', { context: 'value' });

// match to syntax of `border` property
const matchResult = csstree.lexer.matchProperty('border', ast);

// check first value node is a <color>
console.log(matchResult.isType(ast.children.first(), 'color'));
// true

// get a type list matched to a node
console.log(matchResult.getTrace(ast.children.first()));
// [ { type: 'Property', name: 'border' },
//   { type: 'Type', name: 'color' },
//   { type: 'Type', name: 'named-color' },
//   { type: 'Keyword', name: 'red' } ]

Exports

Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations.

import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as lexer from 'css-tree/lexer';
import * as definitionSyntax from 'css-tree/definition-syntax';
import * as data from 'css-tree/definition-syntax-data';
import * as dataPatch from 'css-tree/definition-syntax-data-patch';
import * as utils from 'css-tree/utils';

Using in a browser

Bundles are available for use in a browser:

  • dist/csstree.js – minified IIFE with csstree as global

    <script src="node_modules/css-tree/dist/csstree.js"></script>
    <script>
    csstree.parse('.example { color: green }');
    </script>
    
  • dist/csstree.esm.js – minified ES module

    <script type="module">
    import { parse } from 'node_modules/css-tree/dist/csstree.esm.js'
    parse('.example { color: green }');
    </script>
    

One of CDN services like unpkg or jsDelivr can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified:

<!-- ESM -->
<script type="module">
  import * as csstree from 'https://cdn.jsdelivr.net/npm/css-tree';
  import * as csstree from 'https://unpkg.com/css-tree';
</script>

<!-- IIFE with an export to global -->
<script src="https://cdn.jsdelivr.net/npm/css-tree/dist/csstree.js"></script>
<script src="https://unpkg.com/css-tree/dist/csstree.js"></script>

Top level API

API map

License

MIT

Release Notes

2.1.0
By Roman Dvornov • Published on February 27, 2022
  • Bumped mdn-data to 2.0.27
  • Added module field to package.json
  • Fixed minor issues in CommonJS version
  • Fixed css-tree/utils export (#181)
  • Added css-tree/convertor export
  • Added css-tree/selector-parser export (~27kb when bundled, #183)
  • Reduced bundle size:
    • css-tree/parser 50kb -> 41kb
    • css-tree/generator 46kb -> 23kb
  • Renamed syntaxes into types in css-tree/definition-syntax-data-patch
  • Added parsing support for :is(), :-moz-any(), :-webkit-any() and :where() (#182, #184)
2.0.4
By Roman Dvornov • Published on December 17, 2021
  • Extended Node.js support to include ^10
  • Fixed generate() in safe mode to add a whitespace between <dimension-token> and <hash-token>, otherwise some values are broken in IE11, e.g. border properties (#173)
  • Removed allowance for : for an attribute name on AttributeSelector parsing as it does not meet the CSS specs (details)
2.0.3
By Roman Dvornov • Published on December 15, 2021
  • Fixed unintended whitespace on generate() in safe mode between type-selector and id-selector (e.g. a#id). A regression was introduces in 2.0.2 since IE11 fails on values when <hash-token> goes after <ident-token> without a whitespace in the middle, e.g. 1px solid#000. Thus, in one case, a space between the <ident-token> and the <hash-token> is required, and in the other, vice versa. Until a better solution found, a workaround is used on id-selector generation by producing a <delim-token> instead of <hash-token>.
2.0.2
By Roman Dvornov • Published on December 10, 2021
  • Updated width, min-width and max-width syntax definitions
  • Patched counter related syntaxes to match specs until updated in mdn-data
  • Replaced source-map with source-map-js which reduce install size by ~700KB
  • Fixed calc() function consumption on definition syntax matching
  • Fixed generate() auto emitting a whitespace edge cases when next token starts with a dash (minus)
  • Fixed generate() safe mode to cover more cases for IE11
  • Fixed CommonJS bundling by adding browser files dist/data.cjs and dist/version.cjs
  • Added exports:
    • css-tree/definition-syntax-data
    • css-tree/definition-syntax-data-patch
2.0.1
By Roman Dvornov • Published on December 4, 2021
  • Extended Node.js support to include ^12.20.0 and ^14.13.0 versions
2.0.0
By Roman Dvornov • Published on December 3, 2021

ES2020 syntax and support for ESM

The source code was refactored to use ES2020 syntax and ES modules by default. However, Commonjs version of library is still supported, so the package became a dual module. Using ESM allowed to reduce bundle size from 167Kb down to 164Kb despite that mdn-data grew up in size by 11Kb.

In case only a part of CSSTree functionality is used (for instance only for a parsing), it's possible now to use specific exports like css-tree/parser (see the full list of exports) to reduce a bundle size. As new package mechanics are used, the minimal version for Node.js was changed to 14.16+.

No white space nodes on AST anymore

Previously white spaces was preserved on CSS parsing as a WhiteSpace node with a single space. This was mostly needed to avoid combining the CSS tokens into one when generating back into a CSS string. This is no longer necessary, as the generator has been reworked to independently determine when to use spaces in output. This simplify analysis and construction of the AST, and also improves the performance and memory consumption a bit.

Some changes have been made to the AST construction during parsing. First of all, white spaces in selectors are now producing { type: 'Combinator', name: ' ' } nodes when appropriate. Second, white spaces surrounding operators - and + are now replacing with a single space and appending to operators to preserve a behaviour of expressions in calc() functions. Finally, the only case a WhiteSpace node is now created is a custom property declaration with a single whitespace token as the value, since --var: ; and --var:; have different behaviour in terms of CSS.

Improved generator

CSS Syntax Module defines rules for CSS serialization that it must "round-trip" with parsing. Starting with this release the CSSTree's generator follows these rules and determines itself when to output the space to avoid unintended CSS tokens combining.

The spec rules allow to omit whitespaces in most cases. However, some older browsers fail to parse the resulting CSS because they didn't follow the spec. For this reason, the generator supports two modes:

  • safe (by default) which adds an extra space in some edge cases;
  • spec which completely follows the spec.
import { parse, generate } from 'css-tree';

const ast = parse('a { border: calc(1px) solid #ff0000 }');

// safe mode is by default
// the same as console.log(generate(ast, { mode: 'safe' }));
console.log(generate(ast));
// a{border:calc(1px) solid#ff0000}

// spec mode
console.log(generate(ast, { mode: 'spec' }));
// a{border:calc(1px)solid#ff0000}

These changes to the generator bring it closer to the pretty print output that will be implemented in future releases.

Auto encoding and decoding of values

For string and url values an auto encoding and decoding was implemented. This means you no longer need to do any preprocessing on string or url values before analyzing or transforming of it. Most noticeable simplification with Url nodes:

// CSSTree 1.x
csstree.walk(ast, function(node) {
    if (node.type === 'Url') {
        if (node.value.type === 'String') {
            urls.push(node.value.value.substring(1, node.value.value.length - 1));
        } else {
            urls.push(node.value.value);
        }
    }
});

// CSSTree 2.0
csstree.walk(ast, function(node) {
    if (node.type === 'Url') {
        urls.push(node.value);
    }
});

It is worth noting that despite the fact that in many cases the example above will give the same results for both versions, a solution with CSSTree 1.x still lacks decoding of escaped sequences, that is, additional processing of values is needed.

Additionaly, encode and decode functions for string, url and ident values are available as utils:

import { string, url, ident } from 'css-tree';

string.decode('"hello\\9  \\"world\\""') // hello\t "world"
string.decode('\'hello\\9  "world"\'')   // hello\t "world"
string.encode('hello\t "world"')         // "hello\9  \"world\""
string.encode('hello\t "world"', true)   // 'hello\9  "world"'

url.decode('url(file\ \(1\).ext)')  // file (1).ext
url.encode('file (1).ext')          // url(file\ \(1\).ext)

ident.decode('hello\\9 \\ world')   // hello\t world
ident.encode('hello\t world')       // hello\9 \ world

Changes

  • Package
    • Dropped support for Node.js prior 14.16 (following patch versions changed it to ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0)
    • Converted to ES modules. However, CommonJS is supported as well (dual module)
    • Added exports for standalone parts instead of internal paths usage (use as import * as parser from "css-tree/parser" or require("css-tree/parser")):
      • css-tree/tokenizer
      • css-tree/parser
      • css-tree/walker
      • css-tree/generator
      • css-tree/lexer
      • css-tree/definition-syntax
      • css-tree/utils
    • Changed bundle set to provide dist/csstree.js (an IIFE version with csstree as a global name) and dist/csstree.esm.js (as ES module). Both are minified
    • Bumped mdn-data to 2.0.23
  • Tokenizer
    • Changed tokenize() to take a function as second argument, which will be called for every token. No stream instance is creating when second argument is ommited.
    • Changed TokenStream#getRawLength() to take second parameter as a function (rule) that check a char code to stop a scanning
    • Added TokenStream#forEachToken(fn) method
    • Removed TokenStream#skipWS() method
    • Removed TokenStream#getTokenLength() method
  • Parser
    • Moved SyntaxError (custom parser's error class) from root of public API to parser via parse.SyntaxError
    • Removed parseError field in parser's SyntaxError
    • Changed selector parsing to produce { type: 'Combinator', name: ' ' } node instead of WhiteSpace node
    • Removed producing of WhiteSpace nodes with the single exception for a custom property declaration with a single white space token as a value
    • Parser adds a whitespace to + and - operators, when a whitespace is before and/or after an operator
    • Exposed parser's inner configuration as parse.config
    • Added consumeUntilBalanceEnd(), consumeUntilLeftCurlyBracket(), consumeUntilLeftCurlyBracketOrSemicolon(), consumeUntilExclamationMarkOrSemicolon() and consumeUntilSemicolonIncluded() methods to parser's inner API to use with Raw instead of Raw.mode
    • Changed Nth to always consume of clause when presented, so it became more general and moves validation to lexer
    • Changed String node type to store decoded string value, i.e. with no quotes and escape sequences
    • Changed Url node type to store decoded url value as a string instead of String or Raw node, i.e. with no quotes, escape sequences and url() wrapper
  • Generator
    • Generator is now determines itself when a white space required between emitting tokens
    • Changed chunk() handler to token() (output a single token) and tokenize() (split a string into tokens and output each of them)
    • Added mode option for generate() to specify a mode of token separation: spec or safe (by default)
    • Added emit(token, type, auto) handler as implementation specific token processor
    • Changed Nth to serialize +n as n
    • Added auto-encoding for a string and url tokens on serialization
  • Lexer
    • Removed Lexer#matchDeclaration() method
  • Utils
    • Added ident, string and url helpers to decode/encode corresponding values, e.g. url.decode('url("image.jpg")') === 'image.jpg'
    • List
      • Changed List to be iterable (iterates data)
      • Changed List#first, List#last and List#isEmpty to getters
      • Changed List#getSize() method to List#size getter
      • Removed List#each() and List#eachRight() methods, List#forEach() and List#forEachRight() should be used instead
1.1.3
By Roman Dvornov • Published on March 31, 2021
  • Fixed matching on CSS wide keywords for at-rule's prelude and descriptors
  • Added fit-content to width property patch as browsers are supported it as a keyword (nonstandard), but spec defines it as a function
  • Fixed parsing a value contains parentheses or brackets and parseValue option is set to false, in that case !important was included into a value but must not (#155)
1.1.2
By Roman Dvornov • Published on November 26, 2020
  • Rolled back to use spread syntax in object literals since it not supported by nodejs < 8.3 (#145)
1.1.1
By Roman Dvornov • Published on November 18, 2020
  • Fixed edge cases in mismatch location computation for SyntaxMatchError
1.1.0
By Roman Dvornov • Published on November 18, 2020
  • Bumped mdn-data to 2.0.14
  • Extended fork() method to allow append syntax instead of overriding for types, properties and atrules, e.g. csstree.fork({ types: { color: '| foo | bar' } })
  • Extended lexer API for validation
    • Added Lexer#checkAtruleName(atruleName), Lexer#checkAtrulePrelude(atruleName, prelude), Lexer#checkAtruleDescriptorName(atruleName, descriptorName) and Lexer#checkPropertyName(propertyName)
    • Added Lexer#getAtrule(atruleName, fallbackBasename) method
    • Extended Lexer#getAtrulePrelude() and Lexer#getProperty() methods to take fallbackBasename parameter
    • Improved SyntaxMatchError location details
    • Changed error messages

General

License
MIT
Typescript Types
Tree-shakeable
Yes

Popularity

GitHub Stargazers
1,512
Community Interest
1,318
Number of Forks
86

Maintenance

Commits
10/219/22045
Last Commit
Open Issues
31
Closed Issues
127
Open Pull Requests
3
Closed Pull Requests
16

Versions

Versions Released
10/219/2205
Latest Version Released
Feb 27, 2022
Current Tags
latest2.1.0

Contributors

lahmatiy
lahmatiy
Commits: 957
sergejmueller
sergejmueller
Commits: 2
thybzi
thybzi
Commits: 2
acconrad
acconrad
Commits: 1
jbraithwaite
jbraithwaite
Commits: 1
philschatz
philschatz
Commits: 1
life777
life777
Commits: 1
silverwind
silverwind
Commits: 1
xiaoluoboding
xiaoluoboding
Commits: 1
xfq
xfq
Commits: 1
constgen
constgen
Commits: 1
xiaoboost
xiaoboost
Commits: 1
strarsis
strarsis
Commits: 1
smelukov
smelukov
Commits: 1