css-edit: replace postcss in build-tool-css with an in-house CST over @csstools/css-tokenizer #
Status: in progress. This document is the durable record for the migration; update it after each landmark (decision, commit, verification result).
Task #
User request:
migrate package/build-tool/css off postcss.
Original phrasing named css-tree as the target;
a grilling session (2026-07-22) replaced that target after empirical probes.
Requirements (confirmed with user) #
- Cure four named postcss pains:
unguarded
process.envreach-in (forcesprocess-shim.ts), stringly-typed at-rule params, mutable OO AST feel, and dependency hygiene. - Preserve current
@mixin/@applysemantics and monorepo-aware@importinlining. - Keep the pipeline pure JS and browser-compatible
(
applyMixins()runs in-browser inpackage/webapp-productivity/done-postcss/src/client/css.ts). - Full sibling rigor:
css-edit.fuzz,css-edit.bench, andcss-edit.conformancepackages, mirroring thejsonc-editfamily.
Decision: hybrid CST layer, not an off-the-shelf parser #
New package package/module/css-edit (@monochromatic-dev/module-css-edit)
implements the stylesheet-structure layer (CSS Syntax section 5 consume-block-contents)
over @csstools/css-tokenizer (4.0.0,
zero deps,
TS-native,
MIT,
csstools team).
build-tool-css then consumes css-edit and drops postcss.
Candidate survey evidence (probes run 2026-07-22, scratch dir ~/temp/agent/css-tree-probe-2026-07-22) #
All candidates were probed with the same corpus:
comment,
@mixin body containing declarations plus relaxed nesting plus & nesting plus @apply,
@media range syntax,
braces and semicolons inside strings and url(),
escaped selectors,
custom-property block values.
css-tree3.2.1 (original migration target): rejected. Corrupts relaxed nesting (nestedbutton:disabled {}without&becomes Raw plus parse error); this syntax exists today inpackage/webapp-productivity/done-postcss/src/client/mixins.css(@mixin --shadow-dom-globals). Unknown at-rule blocks parse in rule-list mode, mangling@mixinbodies, fixable only viafork()with a customatruleparser config (verified working). Drops all comments (itsBlock.jsskips comment tokens), generate() is minified-only, and@types/css-tree(2.3.11) lags css-tree by a major version.@adobe/css-tools4.5.0: runner-up. Passed the full corpus including relaxed nesting and comment preservation; zero deps, TS-native types, noprocessreferences. Rejected because custom-property block values (--raw: { nested: token };) throw, its scanner is regex-era (two patched ReDoS CVEs in 2023), and string preludes keep the stringly-params pain.@projectwallace/css-parser0.18.1: disqualified. Arena-based analyzer with no generate/stringify export; cannot emit CSS.@stacksjs/ts-css0.1.1: disqualified. Silently deleted a nested rule from a@mixinbody and ejected@applyto top level; week-old 0.x, Bun-first (conflicts with cross-runtime rule XRT).@csstools/css-parser-algorithms4.0.0: component-value level only, no stylesheet or rule parser; not usable alone, informs the hybrid design.@csstools/css-tokenizer4.0.0: chosen foundation. Byte-perfect lossless round-trip on the full corpus including every adversarial case, zero parse errors, comments preserved as tokens,stringifyre-emits tokens exactly.- Keeping postcss:
viable null option,
cures none of the four pains.
postcss remains in the repo regardless (stylelint config plus catalog override in
pnpm-workspace.yaml), so this migration only removes it frombuild-tool-css.
Design decisions #
- API follows the
jsonc-editfamily convention (verified inpackage/module/jsonc-edit/src/edit-state.ts): immutable state handle, every edit returns fresh state, structural sharing,kind-discriminated readonly plain-object nodes. - Node kinds: stylesheet, at-rule (name, prelude token slice, optional block), rule (prelude token slice, block), raw declaration runs; whitespace and comments preserved in place as token slices. No selector or value parsing: preludes and declaration values stay token arrays.
- Strict parsing: positioned custom error on tokenizer parse errors.
- Stringify is token re-emission: byte-identical output for untouched regions.
build-tool-cssmixin redesign: the fixed-point ten-pass loop with string comparison inmixin-registry.tsis replaced by visited-set recursive expansion; circular references report the exact cycle. The module-level mutablemixinsMap becomes a registry value threaded through functions. Public API changes are fine (unpublished package, design change per HON).process-shim.tsis deleted along with itssideEffectsentry and export (existed solely for postcss; verify no importer remains, includingpackage-paused/).- Output behavior change: author formatting and comments survive byte-exactly outside spliced regions; spliced mixin bodies keep definition-site indentation.
Rejected ideas #
- Pure in-house tokenizer: re-implements what csstools maintains; only buys zero deps.
- css-tree plus authoring convention (
&-only nesting): pays fork config, comment loss, minified output, and stale types to cure two pains.
Open questions #
- None blocking. Deferred: none (conformance sibling was added back by user).
- Conformance data source: tabatkins css-parsing-tests (used by tinycss2).
Plan and progress #
Performance findings (2026-07-22, mitata) #
- Raw parse+stringify, 94 KB sheet: postcss 1.13x faster than css-edit. Decomposition: the spec tokenizer alone (2.86 ms) exceeds postcss's whole parse (2.59 ms) on 66 KB; css-edit's own structure layer adds ~1 ms, stringify 0.81 ms after the flat-accumulator rewrite. Future optimization target: the upstream tokenizer's per-token tuple plus data-object allocation, or index-range nodes instead of token slices.
- Mixin pipeline:
expandCssMixins1.72x faster than the retired postcss clone-and-fixed-point design, ~40 percent less allocation.
Implementation notes discovered while building #
- Repo lint regime shaped the parser:
scan cursors live in named IIFEs
(
no-function-root-let), absence models as discriminated unions or empty arrays (no-nullish-union), and the@csstools/css-tokenizerguards are catalogued as audited pure reads inpackage/oxlint-plugin/prefer-readonly-parameter-type/src/prefer-readonly-parameter-types/csstools-css-tokenizer-package-effect-catalog.ts(shipped dist sha256 recorded there; unit test beside the other catalog tests). - Visitor removal semantics:
empty-array result removes;
with
pruneTriviaBeforeRemovedthe preceding trivia run keeps comments and loses only whitespace after the last comment, matching postcss removal behavior. - CDO/CDC are single tokens;
prose between
<!--and-->is NOT a comment and tokenizes as idents (caught by an initially wrong test corpus). - When postcss leaves
build-tool-css, check whetherpostcss-package-effect-catalog.tsstill has consumers before retiring it.
Commits #
d18af81a1docs: this handover.feat(module-css-edit): CST implementation.805e84287fix/feat: lint remediation + tokenizer effect catalog.test(module-css-edit): unit suites; catalog test passing.