Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion CHANGELOG.md
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,5 +1,46 @@
# Changelog

# v2.2.0

## Bugs

- [x] minifier: the universal selector was removed before a combinator: `.foo *+.x` became `.foo +.x`, `.a * .b` became `.a .b`, `*|*` became `|*`
- [x] minifier: the selectors factored with `:is()` lost the descendant combinator: `.foo .a,.foo .b` became `.foo:is(.a,.b)` instead of `.foo :is(.a,.b)`
- [x] minifier: the declarations of a rule were moved across an `@apply` rule, an empty contents block was removed: `@apply --mixin {}`
- [x] minifier: the unit of the `initial-value` of `@property` was removed: `initial-value: 0deg` became `initial-value: 0`, which is not a valid `<angle>`
- [x] minifier: there is no early return in a `@function`: the `result` that precedes the conditional rules is moved after them. `result: 16px; @media (...) { result: 20px }` -> `@media (...) { result: 20px } result: 16px`
- [x] minifier: the conditional rules of a `@function` were removed when they were placed before the last `result`: they are never removed
- [x] minifier: the `result` descriptors of a `@function` were only deduplicated with `{validation: true}`: `@function --mypi() { result: 3; result: 3.14; }` -> `@function --mypi(){result:3.14}`
- [x] an empty `@function` or `@mixin` was removed with `removeEmpty`, and a `@function` with an empty result (`result: ;`) was dropped: they are valid definitions
- [x] a declaration that is not `!important` no longer overrides a previous `!important` declaration of the same property: `.a{color:red !important;color:blue}` -> `.a{color:red!important}`
- [x] minifier: the merge of two rules is kept only when the output is smaller (or has the same size and removes a rule). the merge of a rule into a rule that keeps some declarations repeated the selector of that rule: `html{margin:0}body,div,...{margin:0;font:inherit}` became `html,body,div,...{margin:0}body,div,...{font:inherit}`. the minified output
- [x] minifier: `text-emphasis` declarations threw `Cannot read properties of undefined (reading 'includes')` (`text-emphasis-color` has no keyword)
- [x] `parse()`, `parseSync()`, `transform()`, `transformSync()` and `render()` no longer modify the options object of the caller: a reused options object kept the source and the code units of the first input, and its validation (sync api) traversed them at every call. the sync api options check only traverses the plain objects and the arrays of `blueprint.css` was larger than the output of the fast mode (`minify: false`)

## Feature
- [x] experimental: evaluate css mixins with `{evaluateMixins: true}`: the `@apply` rules are replaced by the mixin body, the private variables (`@private`, mixin arguments, custom properties of the rule) are substituted https://drafts.csswg.org/css-mixins-1/#mixin-rule
- [x] minification: `@apply --mixin()` is minified to `@apply --mixin`
- [x] the evaluated mixins and the mixins that are not referenced are replaced with a comment, they are kept with `{keepMixins: true}`
- [x] a mixin can be defined in a cascade layer or a conditional group rule that is not nested in a style rule
- [x] custom functions: a call that is not evaluated makes the declaration, the custom function and the mixin that contain it fail, they are not evaluated
- [x] custom functions that contain conditional rules (`@media`, `@supports`, `@container`, `@when`, `@else`) are not evaluated
- [x] mixins and custom functions: a definition located in a rule or an at-rule is only visible inside of it, it hides the definitions with the same name of the outer scopes. a reference that does not see a definition is not evaluated
- [x] mixins: `@contents` is replaced with a copy of the contents block of the `@apply` rule, or with its default contents. `@result` is supported
- [x] mixins: the value of a typed argument is computed on the element the mixin is applied to, using a registered custom property (`@property`) when a descendant references it
- [x] evaluate the custom functions with `{evaluateMixins: true}`: the custom function calls (`--fn(1px)`) are replaced by the result of the function
- [x] the rules that apply a mixin are not merged
- [x] mixins and custom functions: a value that is not valid is left as is. a mixin that is not valid is ignored and left as is
- [x] custom functions: a `@function` rule whose parameters contain the same name more than once is invalid, it is dropped when `{evaluateMixins: true}`. the custom functions see the custom properties of the call site. the css-wide keywords of the local variables: `initial` is the value of the parameter, `inherit` and `unset` the value of the calling context. the invalid declarations are not evaluated
- [x] shorthand properties `padding-inline`, `padding-block`, `margin-inline` and `margin-block`: `.a{margin-inline-start:auto;margin-inline-end:auto}` -> `.a{margin-inline:auto}`
- [x] `RenderResult` and `TransformResult` are classes. the generated css is accumulated as UTF-8 bytes in `result.write` (`Uint8Array`), `result.code` is a getter that decodes the bytes once, when it is first read.

## Performance
- [x] avoid temporary strings allocation
- [x] faster css transform minification

## Validation
- [x] rewrite validation to reduce execution time

# v2.1.0

## Bugs
Expand All @@ -11,7 +52,7 @@
## Feature

- [x] now accepting arraybuffer as input data: transformSync(arraybuffer);
- [x] renamed 'word-wrap' to 'overflow-wrap', 'grid-gap' to 'gap', 'grid-row-gap' to 'row-gap', 'grid-column-gap' to 'column-gap', 'font-stretch' to 'font-width'.
- [ ] renamed 'word-wrap' to 'overflow-wrap', 'grid-gap' to 'gap', 'grid-row-gap' to 'row-gap', 'grid-column-gap' to 'column-gap', 'font-stretch' to 'font-width'.

## Validation
- [x] switching syntax definitions source from mdn-data to webref/css
Expand Down
21 changes: 14 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A zero-allocation, high-performance CSS processing engine for Node.js and the br
Every stylesheet is fully parsed into a structured AST, with token values represented as typed data. This provides a reliable semantic foundation for custom transformations, plugin development, and advanced stylesheet analysis without relying on raw string manipulation.

> [!NOTE]
> Version 2.0 has been rewritten to use arena memory for AST nodes and tokens, improving memory usage and performance. On the Tailwind CSS parsing and validation workload, runtime is 42% faster than v1.8.2 while using 60% less memory.<br>
> Version 2.2.0 has been rewritten to use arena memory for AST nodes and tokens, improving memory usage and performance. On the Tailwind CSS parsing and validation workload, runtime is **59% faster than v1.8.2** while using less memory.<br>
This major release also introduces breaking changes and removes deprecated features. See the [migration guide](https://tbela99.github.io/css-parser/docs/documents/Guide.Migration.html) for details.

## Installation
Expand All @@ -30,7 +30,7 @@ $ deno add @tbela99/css-parser

* **Zero dependencies** — lightweight and easy to integrate into any project.
* **All-in-one CSS parsing solution** covering parsing, validation, transformation, minification, and AST manipulation.
* **Standards-based CSS validation** powered by MDN data.
* **Standards-based CSS validation** powered by the W3C specification definitions ([@webref/css](https://github.com/w3c/webref/tree/main/packages/css)).
* **Full CSS Modules support** for modern component-based workflows.
* **Fault-tolerant parsing** that follows the CSS Syntax Module Level 3 specification and always produces a complete, structured parse result.
* **Typed tokens and AST** — parsed CSS is exposed as strongly typed tokens and nodes so plugins and transforms can operate on semantic structures.
Expand All @@ -45,7 +45,9 @@ $ deno add @tbela99/css-parser
* **CSS variable inlining** where values can be safely resolved.
* **Duplicate declaration removal** to eliminate redundant rules.
* **`@import` flattening** to produce self-contained stylesheets.
* **Vendor prefix cleanup** to modernize generated CSS.
* **Binary input** — the css can be a string, an `ArrayBuffer` or an `ArrayBufferView` (utf-8 bytes, `Uint8Array`, `Buffer`): an ASCII buffer is tokenized without copy.
* **Experimental**: evaluate @mixin and @function
* **51.5kb** once minified and gzipped.

## Vendor prefix removal
Expand All @@ -55,6 +57,7 @@ $ deno add @tbela99/css-parser
CSS-Parser can transform these modern CSS features into lower-level CSS syntax:
* **Nested CSS transpilation** to legacy-compatible syntax.
* **`if()` function transpilation** for broader browser compatibility.
* **CSS mixins and custom functions evaluation** the `@apply` rules are replaced by the mixin body, the custom function calls are replaced by their result.
* **`color-mix()` function conversion** convert new color-mix() syntax to any of the supported colors.

## Benchmark
Expand All @@ -67,9 +70,9 @@ A sample result:

| File | ligthningcss | CSS Parser |
| ------------------------------ | ------------- | ------------- |
| tailwind.css - 2380419 bytes | 1864728 bytes | 1633188 bytes |
| bootstrap-4.css - 200078 bytes | 153616 bytes | 144571 bytes |
| bootstrap-5.css - 205481 bytes | 159987 bytes | 150852 bytes |
| tailwind.css - 2380419 bytes | 1864728 bytes | 1624148 bytes |
| bootstrap-4.css - 200078 bytes | 153616 bytes | 144391 bytes |
| bootstrap-5.css - 205481 bytes | 159987 bytes | 150764 bytes |

On the [complete benchmark suite](https://tbela99.github.io/css-parser/benchmark/index.html), css-parser generated a total output size of 2,158,698 bytes, compared to 2,494,113 bytes for Lightning CSS and larger outputs for all other tested minifiers.
While some tools prioritize raw execution speed, css-parser focuses on maximizing compression while preserving stylesheet semantics, resulting in consistently smaller production bundles.
Expand Down Expand Up @@ -114,8 +117,8 @@ Performance vs execution speed comparison
| File: tailwind.css | Speed optimization | Minification optimization |
| --------------------- | ------------------ | ------------------------- |
| Size: 2,380,419 bytes | 1,890,835 bytes | 1,633,188 bytes |
| Time | 116.61 ms | 224.18 ms |
| Size reduction | -20.6% | -31.4% |
| Time | 109.07 ms | 191.85 ms |
| Size reduction | -20.7% | -31.8% |

## Playground

Expand Down Expand Up @@ -321,11 +324,15 @@ See [Ast Manipulation](https://tbela99.github.io/css-parser/docs/documents/Guide
- [x] inset
- [x] list-style
- [x] margin
- [x] margin-block
- [x] margin-inline
- [ ] mask
- [ ] offset
- [x] outline
- [x] overflow
- [x] padding
- [x] padding-block
- [x] padding-inline
- [ ] place-content
- [ ] place-items
- [ ] place-self
Expand Down
Binary file modified architecture.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions benchmark/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"all": "npm run sizes && npm run bench; npm run report"
},
"dependencies": {
"@stacksjs/ts-css": "^0.3.26",
"@tbela99/css-parser": "github:tbela99/css-parser#v2.0.1",
"@tbela99/css-parser2": "github:tbela99/css-parser#d237344",
"clean-css": "^5.3.3",
Expand Down
106 changes: 45 additions & 61 deletions benchmark/src/minifiers.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as csso from "csso";
import * as csstree from "css-tree";
import * as esbuild from "esbuild";
import { transform } from "lightningcss";
import { minify} from '@stacksjs/ts-css';
import { transform as yukuTransform} from "yuku-css";
import { transformSync as tbelaTransform } from "@tbela99/css-parser";
import { transformSync as tbelaDevTransform } from "@tbela99/css-parser2";
Expand Down Expand Up @@ -67,6 +68,7 @@ const versions = {
esbuild: pkgVersion("esbuild", "esbuild/package.json"),
lightningcss: pkgVersion("lightningcss", "lightningcss/package.json"),
'yuku-css': pkgVersion("yuku-css", "yuku-css/package.json"),
'stacksjs-ts-css': pkgVersion("stacksjs-ts-css", "@stacksjs/ts-css/package.json"),
"css-parser": pkgVersion("css-parser", "@tbela99/css-parser/package.json"),
"css-parser-dev": pkgVersion("css-parser-dev", "@tbela99/css-parser2/package.json"),
};
Expand All @@ -80,39 +82,12 @@ const cssnanoProcessor = postcss([cssnano]);
* official table's "name - version" formatting.
*/
export const minifiers = [
// {
// id: "clean-css",
// url: versions["clean-css"].url,
// label: `clean-css - ${versions["clean-css"].version}`,
// minify: (css) => cleanCssInstance.minify(css).styles,
// },
// {
// id: "cssnano",
// url: versions.cssnano.url,
// label: `cssnano - ${versions.cssnano.version}`,
// minify: async (css) => (await cssnanoProcessor.process(css, { from: undefined })).css,
// },
// {
// id: "csso",
// url: versions.csso.url,
// label: `csso - ${versions.csso.version}`,
// minify: (css) => csso.minify(css).css,
// },
// infinite loop bug
{
id: "css-tree",
url: versions["css-tree"].url,
label: `css-tree - ${versions["css-tree"].version}`,
// css-tree has no dedicated minifier API; parse+generate already
// drops whitespace/comments, which is how the official benchmark
// treats it too (no property-level optimization, just compact output).
minify: (css) => csstree.generate(csstree.parse(css)),
},
{
id: "esbuild",
url: versions.esbuild.url,
label: `esbuild - ${versions.esbuild.version}`,
minify: async (css) => (await esbuild.transform(css, { loader: "css", minify: true })).code,
id: "yuku-css",
url: versions["yuku-css"].url,
label: `yuku-css - ${versions["yuku-css"].version}`,
minify: (css) => yukuTransform(css).code,
},
{
id: "lightningcss",
Expand All @@ -121,33 +96,40 @@ export const minifiers = [
minify: (css) => transform({ filename: "style.css", code: Buffer.from(css), minify: true }).code.toString(),
},
{
id: "yuku-css",
url: versions["yuku-css"].url,
label: `yuku-css - ${versions["yuku-css"].version}`,
minify: (css) => yukuTransform(css).code,
id: "esbuild",
url: versions.esbuild.url,
label: `esbuild - ${versions.esbuild.version}`,
minify: async (css) => (await esbuild.transform(css, { loader: "css", minify: true })).code,
},
{
id: "css-parser-default",
url: versions["css-parser"].url,
label: `@tbela99/css-parser - ${versions["css-parser"].version}`,
minify: async (css) =>
tbelaTransform({
input: css,
}).code,
id: "css-tree",
url: versions["css-tree"].url,
label: `css-tree - ${versions["css-tree"].version}`,
// css-tree has no dedicated minifier API; parse+generate already
// drops whitespace/comments, which is how the official benchmark
// treats it too (no property-level optimization, just compact output).
minify: (css) => csstree.generate(csstree.parse(css)),
},
{
id: "css-parser-speed",
url: versions["css-parser"].url,
label: `@tbela99/css-parser (fast) - ${versions["css-parser"].version}`,
id: "stacksjs-ts-css",
url: versions["stacksjs-ts-css"].url,
label: `@stacksjs/ts-css - ${versions["stacksjs-ts-css"].version}`,
minify: (css) => minify(css).css,
},
{
id: "css-parser-dev-speed",
url: versions["css-parser-dev"].url,
label: `@tbela99/css-parser-dev (fast) - ${versions["css-parser-dev"].version}`,
title: `settings: { minify: false, beautify: false, removeEmpty: true, removeComments: true, convertColor: true }`,
minify: async (css) =>
tbelaTransform({
input: css,
tbelaDevTransform({
input: Buffer.from(css),
minify: false,
beautify: false,
removeEmpty: true,
removeComments: true,
convertColor: true,
validate: false,
// minifyValues: true,
}).code,
},
Expand All @@ -158,19 +140,21 @@ export const minifiers = [
minify: async (css) => tbelaDevTransform({ input: Buffer.from(css) }).code,
},
{
id: "css-parser-dev-speed",
url: versions["css-parser-dev"].url,
label: `@tbela99/css-parser-dev (fast) - ${versions["css-parser-dev"].version}`,
title: `settings: { minify: false, beautify: false, removeEmpty: true, removeComments: true, convertColor: true }`,
minify: async (css) =>
tbelaDevTransform({
input: Buffer.from(css),
minify: false,
beautify: false,
removeEmpty: true,
removeComments: true,
convertColor: true,
// minifyValues: true,
}).code,
id: "csso",
url: versions.csso.url,
label: `csso - ${versions.csso.version}`,
minify: (css) => csso.minify(css).css,
},
{
id: "clean-css",
url: versions["clean-css"].url,
label: `clean-css - ${versions["clean-css"].version}`,
minify: (css) => cleanCssInstance.minify(css).styles,
},
{
id: "cssnano",
url: versions.cssnano.url,
label: `cssnano - ${versions.cssnano.version}`,
minify: async (css) => (await cssnanoProcessor.process(css, { from: undefined })).css,
},
];
Loading
Loading