ReviewOS

also looking at this

stacks/ts-css

Merge @stacksjs/ts-css into this repo as packages/toolkit

#27
Merged glennmichael123 wants to merge merge/ts-css-toolkit into main
128 files +9797 -201
packages/toolkit/README.mdadded+213-0
Changes to packages/toolkit/README.md
@@ -0,0 +1,213 @@
1# @stacksjs/ts-css
2
3> Pure-TypeScript CSS toolkit for Bun & Node. Zero runtime dependencies.
4
5`ts-css` is a CSS toolkit for build tools, linters, design-system pipelines,
6SSR templating, runtime style transforms — anything that needs to read,
7walk, query, transform, or minify CSS in a JS/TS environment. Written from
8scratch in TypeScript with strict types and the CSS Syntax Module Level 3
9tokenizer.
10
11It bundles every common CSS pipeline primitive — tokenizer, AST parser,
12visitor walker, generator, selector parser, selector matcher, and minifier —
13into a single zero-dep package. The shape of each sub-API mirrors the
14de-facto community standard for that capability (`css-tree`-style AST and
15walker, `css-what`-style selector tokens, the `css-select` adapter contract,
16`csso`-style minify result), so adopting `ts-css` rarely requires call-site
17changes — but the project stands on its own and isn't pitched as "the
18replacement for X."
19
20## Highlights
21
22- **Zero runtime deps.** Only ts-css's own code. Ships ~4.5k lines of TS.
23- **One install for the whole CSS pipeline.** Tokenizer, parser, walker,
24 generator, selector parser/matcher, and minifier — all behind sub-module
25 imports at `@stacksjs/ts-css/parse`, `/what`, `/select`, `/optimize`.
26- **Familiar API shapes.** Visitor/walker callbacks, AST node types, and
27 the `css-select` adapter contract follow the conventions established by
28 the popular community libraries, so most existing call sites work
29 unchanged.
30- **Bun-first.** Built and tested on Bun, works on Node ≥18.
31- **Strict TypeScript.** Strict mode, isolatedDeclarations, verbatimModuleSyntax.
32
33## Install
34
35```bash
36bun add @stacksjs/ts-css
37# or
38npm i @stacksjs/ts-css
39```
40
41## Quick start
42
43### Parse, walk, generate
44
45```ts
46import { generate, parse, walk } from '@stacksjs/ts-css'
47
48const ast = parse(`
49 .foo, .bar > .baz {
50 color: red;
51 background: url("/x.png") no-repeat;
52 }
53`)
54
55walk(ast, {
56 visit: 'Declaration',
57 enter(decl) {
58 console.log(decl.property, '→', generate(decl.value))
59 },
60})
61// color → red
62// background → url("/x.png") no-repeat
63
64console.log(generate(ast))
65// .foo,.bar>.baz{color:red;background:url("/x.png") no-repeat}
66```
67
68### Match selectors against any tree
69
70```ts
71import { selectAll } from '@stacksjs/ts-css'
72
73const adapter = {
74 isTag: (n) => n?.type === 'el',
75 getName: (e) => e.name,
76 getAttributeValue: (e, n) => e.attrs[n],
77 // …other adapter methods (see docs/api/select.md)
78}
79
80selectAll('p > span.foo:not(.disabled)', root, { adapter, xmlMode: true })
81```
82
83The matcher is decoupled from any DOM implementation: pass an `Adapter`
84describing your tree (HTML, XML, an SVG AST, your design-system component
85graph, anything with `parent`/`children`/`name`/`attrs`-like access) and
86ts-css will match standard CSS selectors against it.
87
88### Minify CSS
89
90```ts
91import { minify } from '@stacksjs/ts-css'
92
93minify(`
94 .a {
95 margin: 0px 0.5em 10.000px;
96 color: #aabbcc;
97 color: blue; /* later wins */
98 }
99`).css
100// → ".a{margin:0 .5em 10px;color:blue}"
101```
102
103### Compute selector specificity
104
105```ts
106import { parse, syntax } from '@stacksjs/ts-css'
107
108const sel = parse('#a.b div', { context: 'selector' })
109syntax.specificity(sel) // [1, 1, 1]
110```
111
112## API surface
113
114`ts-css` exposes a complete CSS pipeline. The named exports below cover the
115endpoints most build/lint/transform tools reach for:
116
117| Capability | Export |
118| -------------------------------- | ---------------------------- |
119| Parse a stylesheet to an AST (`stylesheet`/`rule`/`declaration`/`selectorList`/etc. contexts) | `parse(source, opts?)` |
120| Walk the AST with `enter`/`leave` callbacks, `visit` filtering, and a `walk.skip` sentinel | `walk(ast, fn \| visitor)` |
121| Stringify any AST node back to CSS source | `generate(node)` |
122| Deep-clone an AST subtree | `clone(node)` |
123| Doubly-linked children container with cursor-safe `forEach(data, item, list)` mid-walk mutation | `List` / `ListItem` |
124| Tokenize a selector string into segments | `cssWhat.parse(selector)` |
125| Detect combinator/traversal segments | `cssWhat.isTraversal(seg)` |
126| Match a selector against an arbitrary tree via the `Adapter` contract | `selectAll`, `selectOne`, `is`, `compile` |
127| Minify with declaration/value compression and whitespace collapse | `minify`, `minifyBlock` |
128| Compute selector specificity tuple | `syntax.specificity(node)` |
129
130A namespace export (`csstree`, `cssWhat`, `cssSelect`, `csso`) is also
131available so existing code that imports from those packages can typically
132switch by just changing the import path.
133
134## CLI
135
136```bash
137ts-css minify input.css > output.css
138ts-css parse input.css # AST as JSON on stdout
139ts-css format input.css # round-trip through parser/generator
140```
141
142## What's not (yet) in scope
143
144This is a pragmatic toolkit — full surface area where it's load-bearing,
145trimmed where edge cases would force in spec data or rarely-used passes:
146
147- ❌ **No CSS-spec-aware value lexer.** Validating that `red` is a valid
148 `<color>`, or that `1px` is the right syntax for a given property, is
149 thousands of lines of spec grammar that most pipelines don't need. The
150 AST preserves enough information to layer that on top if you do.
151- ❌ **No cross-rule restructuring pass.** Reordering rules across the
152 whole stylesheet to fold compatible declarations is complex and gives
153 marginal gains beyond gzip. Declaration-level minification (numbers,
154 colors, dedup, longhand collapse) ships fully.
155
156Everything else round-trips byte-equivalent.
157
158## Project layout
159
160```
161src/
162 parse/ # tokenizer, parser, AST types, walker, generator, clone, List
163 what/ # selector parser/stringifier
164 select/ # selectAll/selectOne/is engine + pseudo-class compilers
165 optimize/ # minifier, value compressors, specificity
166```
167
168Each sub-module is exported as a separate entry point so you can import
169just what you need:
170
171```ts
172import { parse, walk } from '@stacksjs/ts-css/parse'
173import { selectAll } from '@stacksjs/ts-css/select'
174import { minify } from '@stacksjs/ts-css/optimize'
175```
176
177## Performance
178
179End-to-end (parse → minify → generate) on a 6 KB representative fixture
180(Apple M3 Pro, Bun 1.3):
181
182| Pipeline | Time/iter |
183| --------------------------- | --------- |
184| `ts-css.minify(source)` | **~270 µs** |
185| `csso.minify(source)` | ~890 µs |
186
187→ **~3.3× faster end-to-end** with zero runtime deps. Per-API breakdown
188in [`docs/benchmarks.md`](./docs/benchmarks.md). Run them yourself with
189`bun run bench`.
190
191## Documentation
192
193Full docs: see [`./docs`](./docs) or run `bun run dev:docs` to start the
194local docs site.
195
196- [Getting started](./docs/intro.md)
197- [Parser API](./docs/api/parse.md)
198- [Selector parser API](./docs/api/what.md)
199- [Selector matcher API](./docs/api/select.md)
200- [Optimizer API](./docs/api/optimize.md)
201- [Migration guide](./docs/migration.md)
202- [Benchmarks](./docs/benchmarks.md)
203
204## License
205
206MIT — see [`LICENSE.md`](./LICENSE.md).
207
208`ts-css` is an independent implementation. The visitor / linked-list shape
209in `src/parse`, the selector tokenizer model in `src/what`, the adapter
210pattern in `src/select`, and the minification plan in `src/optimize` all
211follow conventions established by the long-standing community libraries in
212each area, so call sites that already use those conventions tend to drop in
213without changes. All such projects are MIT-licensed.