@tenphi/tasty 0.0.0-snapshot.d9aaeb7 → 0.0.0-snapshot.d9fa8e8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +440 -372
  2. package/dist/babel-types-Dc5zghyE.d.ts +18 -0
  3. package/dist/chunks/async-storage-f9j9JRtq.js +37 -0
  4. package/dist/chunks/async-storage-f9j9JRtq.js.map +1 -0
  5. package/dist/chunks/build-config-D9Iq8QQm.js +60 -0
  6. package/dist/chunks/build-config-D9Iq8QQm.js.map +1 -0
  7. package/dist/{collector-WUJKpM4q.js → chunks/collector-Cb8ah2JF.js} +79 -99
  8. package/dist/chunks/collector-Cb8ah2JF.js.map +1 -0
  9. package/dist/chunks/config-engine-CMYFZYQh.js +272 -0
  10. package/dist/chunks/config-engine-CMYFZYQh.js.map +1 -0
  11. package/dist/chunks/config-file-DlZXJMj8.js +25 -0
  12. package/dist/chunks/config-file-DlZXJMj8.js.map +1 -0
  13. package/dist/chunks/css-definitions-B4aWBkH3.js +910 -0
  14. package/dist/chunks/css-definitions-B4aWBkH3.js.map +1 -0
  15. package/dist/chunks/css-resources-P7IBUUZs.js +142 -0
  16. package/dist/chunks/css-resources-P7IBUUZs.js.map +1 -0
  17. package/dist/chunks/debug-D2Pu7Xhy.js +502 -0
  18. package/dist/chunks/debug-D2Pu7Xhy.js.map +1 -0
  19. package/dist/chunks/dsl-CsFl9LGn.js +1458 -0
  20. package/dist/chunks/dsl-CsFl9LGn.js.map +1 -0
  21. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  22. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  23. package/dist/chunks/react-runtime-DHiopXCu.js +691 -0
  24. package/dist/chunks/react-runtime-DHiopXCu.js.map +1 -0
  25. package/dist/chunks/runtime-engine-NGCofNXy.js +2435 -0
  26. package/dist/chunks/runtime-engine-NGCofNXy.js.map +1 -0
  27. package/dist/chunks/runtime-state-lZjMbvwV.js +152 -0
  28. package/dist/chunks/runtime-state-lZjMbvwV.js.map +1 -0
  29. package/dist/{merge-styles-B57eQpFZ.js → chunks/shared-utils-y-HjvPN4.js} +60 -55
  30. package/dist/chunks/shared-utils-y-HjvPN4.js.map +1 -0
  31. package/dist/chunks/style-engine-DnkV_4Jg.js +5602 -0
  32. package/dist/chunks/style-engine-DnkV_4Jg.js.map +1 -0
  33. package/dist/{css-writer-BaR8ywQm.js → chunks/zero-engine-DcwaCvFs.js} +104 -123
  34. package/dist/chunks/zero-engine-DcwaCvFs.js.map +1 -0
  35. package/dist/collector-D2OT6I2G.d.ts +164 -0
  36. package/dist/config-C4ftFxgI.d.ts +1367 -0
  37. package/dist/core/index.d.ts +5 -5
  38. package/dist/core/index.js +9 -6
  39. package/dist/hydrate-CRyjjAyl.d.ts +22 -0
  40. package/dist/index-DxQNRj50.d.ts +1964 -0
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +11 -732
  43. package/dist/{merge-styles-CtDJMhpJ.d.ts → merge-styles-D39qBtox.d.ts} +2 -3
  44. package/dist/ssr/astro-client.d.ts +1 -1
  45. package/dist/ssr/astro-client.js +1 -14
  46. package/dist/ssr/astro-client.js.map +1 -1
  47. package/dist/ssr/astro-middleware-extract-static.d.ts +10 -0
  48. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  49. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  50. package/dist/ssr/astro-middleware-extract.d.ts +10 -0
  51. package/dist/ssr/astro-middleware-extract.js +9 -0
  52. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  53. package/dist/ssr/astro-middleware-static.d.ts +17 -0
  54. package/dist/ssr/astro-middleware-static.js +7 -0
  55. package/dist/ssr/astro-middleware-static.js.map +1 -0
  56. package/dist/ssr/astro-middleware.d.ts +11 -8
  57. package/dist/ssr/astro-middleware.js +2 -14
  58. package/dist/ssr/astro-middleware.js.map +1 -1
  59. package/dist/ssr/astro.d.ts +40 -10
  60. package/dist/ssr/astro.js +163 -91
  61. package/dist/ssr/astro.js.map +1 -1
  62. package/dist/ssr/client.d.ts +2 -0
  63. package/dist/ssr/client.js +2 -0
  64. package/dist/ssr/index.d.ts +5 -32
  65. package/dist/ssr/index.js +6 -6
  66. package/dist/ssr/index.js.map +1 -1
  67. package/dist/ssr/next-config.d.ts +64 -0
  68. package/dist/ssr/next-config.js +123 -0
  69. package/dist/ssr/next-config.js.map +1 -0
  70. package/dist/ssr/next.d.ts +9 -9
  71. package/dist/ssr/next.js +29 -44
  72. package/dist/ssr/next.js.map +1 -1
  73. package/dist/static/index.d.ts +8 -9
  74. package/dist/static/index.js +4 -22
  75. package/dist/static/index.js.map +1 -1
  76. package/dist/static/inject.d.ts +1 -2
  77. package/dist/static/inject.js.map +1 -1
  78. package/dist/{index-dUtwpOux.d.ts → types-CYQIhUg1.d.ts} +691 -388
  79. package/dist/zero/babel.d.ts +12 -20
  80. package/dist/zero/babel.js +101 -152
  81. package/dist/zero/babel.js.map +1 -1
  82. package/dist/zero/index.d.ts +76 -7
  83. package/dist/zero/index.js +25 -2
  84. package/dist/zero/index.js.map +1 -0
  85. package/dist/zero/next.d.ts +4 -5
  86. package/dist/zero/next.js +3 -38
  87. package/dist/zero/next.js.map +1 -1
  88. package/docs/README.md +20 -9
  89. package/docs/adoption.md +69 -36
  90. package/docs/ai-agents.md +259 -0
  91. package/docs/comparison.md +77 -47
  92. package/docs/configuration.md +648 -85
  93. package/docs/debug.md +28 -15
  94. package/docs/design-system.md +154 -33
  95. package/docs/dsl.md +715 -194
  96. package/docs/getting-started.md +130 -50
  97. package/docs/injector.md +160 -69
  98. package/docs/methodology.md +106 -49
  99. package/docs/migration-v3.md +285 -0
  100. package/docs/pipeline.md +141 -46
  101. package/docs/plugins.md +333 -0
  102. package/docs/react-api.md +236 -47
  103. package/docs/runtime-benchmarks.md +388 -0
  104. package/docs/ssr.md +310 -116
  105. package/docs/styles.md +234 -49
  106. package/docs/tasty-static.md +298 -130
  107. package/package.json +146 -41
  108. package/tasty.config.ts +5 -0
  109. package/dist/async-storage-B7_o6FKt.js +0 -44
  110. package/dist/async-storage-B7_o6FKt.js.map +0 -1
  111. package/dist/collector-LuU1vZ68.d.ts +0 -98
  112. package/dist/collector-WUJKpM4q.js.map +0 -1
  113. package/dist/config-raGoEeGs.js +0 -10227
  114. package/dist/config-raGoEeGs.js.map +0 -1
  115. package/dist/config-vuCRkBWX.d.ts +0 -884
  116. package/dist/context-CkSg-kDT.js +0 -24
  117. package/dist/context-CkSg-kDT.js.map +0 -1
  118. package/dist/core-CrPLif0D.js +0 -1592
  119. package/dist/core-CrPLif0D.js.map +0 -1
  120. package/dist/css-writer-BaR8ywQm.js.map +0 -1
  121. package/dist/format-global-rules-Dbc_1tc3.js +0 -22
  122. package/dist/format-global-rules-Dbc_1tc3.js.map +0 -1
  123. package/dist/format-rules-B_Cuw1ZS.js +0 -143
  124. package/dist/format-rules-B_Cuw1ZS.js.map +0 -1
  125. package/dist/hydrate-DmVyww8Y.js +0 -45
  126. package/dist/hydrate-DmVyww8Y.js.map +0 -1
  127. package/dist/index-ZRxZWzlj.d.ts +0 -1602
  128. package/dist/index.js.map +0 -1
  129. package/dist/keyframes-C9OD_9bX.js +0 -588
  130. package/dist/keyframes-C9OD_9bX.js.map +0 -1
  131. package/dist/merge-styles-B57eQpFZ.js.map +0 -1
  132. package/dist/resolve-recipes-J9mdpVSZ.js +0 -144
  133. package/dist/resolve-recipes-J9mdpVSZ.js.map +0 -1
package/docs/pipeline.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  This document describes the style rendering pipeline that transforms style objects into CSS rules. The pipeline ensures that each style value is applied to exactly one condition through exclusive condition building, boolean simplification, and intelligent CSS generation.
4
4
 
5
- **Implementation:** [`src/pipeline/`](../src/pipeline/) — TypeScript file names below are relative to that directory.
5
+ **Implementation:** [`src/pipeline/`](https://github.com/tenphi/tasty/tree/main/src/pipeline) — TypeScript file names below are relative to that directory.
6
6
 
7
7
  ## Overview
8
8
 
9
- The pipeline takes a `Styles` object and produces an array of `CSSRule` objects ready for injection into the DOM. Entry points include `renderStylesPipeline` (full pipeline + optional class-name prefixing) and `renderStyles` (direct selector/class mode). The per-handler flow is:
9
+ The pipeline takes a `Styles` object and produces an array of `CSSRule` objects ready for injection into the DOM. The entry point is `renderStyles`, which has two overloads: called with a selector or class (`renderStyles(styles, '.t1')`) it returns the rules directly; called without one (`renderStyles(styles)`) it returns `{ rules }` for a caller that will allocate the class name itself. The per-handler flow is:
10
10
 
11
11
  ```
12
12
  Input: Styles Object
@@ -76,7 +76,7 @@ Output: CSSRule[]
76
76
 
77
77
  **Simplification** (`simplifyCondition` in `simplify.ts`) is not a separate numbered stage. It runs inside OR expansion, exclusive building, `expandExclusiveOrs` branch cleanup, combination ANDs, merge-by-value ORs, and materialization. Every call is cached by condition unique-id, so the repetition is cheap.
78
78
 
79
- **Post-pass:** After `processStyles` collects rules from every handler, `runPipeline` (`index.ts:188`) filters duplicates using a key of `selector|declarations|atRules|rootPrefix|startingStyle` and then reorders rules so every `@starting-style` rule is emitted **after** all normal rules. This ordering is cascade-critical: `@starting-style` rules share specificity with their normal counterparts, and source order decides which value wins.
79
+ **Post-pass:** After `processStyles` collects rules from every handler, `runPipeline` (`index.ts`) filters duplicates using a key of `selector|declarations|atRules|rootPrefix|startingStyle`, then **stable-sorts rules by their cascade `order` hint (ascending source priority)** so lower-priority rules come first and higher-priority rules win, and finally emits every `@starting-style` rule **after** all normal rules. Each Stage 4 snapshot takes the highest source priority among its entries as its `order` hint; when Stage 6 merges same-output rules, the merged rule keeps the lowest `order` of its group, so a rule carrying the `_` floor's value keeps the floor's early position (threaded `ComputedRule → CSSRule`). This ordering is cascade-critical because Stage 7 equalizes specificity with `:where()`: once every state selector carries zero specificity, source order alone decides which of two overlapping rules wins — most importantly the `_` fallback floor (low order, emitted first) versus the states layered over it, and `@starting-style` versus its normal counterpart. Mutually-exclusive rules are unaffected by ordering (they never both match), so reordering them is safe.
80
80
 
81
81
  ---
82
82
 
@@ -86,18 +86,22 @@ Output: CSSRule[]
86
86
 
87
87
  ### What It Does
88
88
 
89
- Runs on each style's value map **before** any parsing. If a compound AND state key shares a value with the "atom absent" variant, the atom is a don't-care and every key is simplified by dropping it. Duplicate keys collapse.
89
+ Runs on each style's value map **before** any parsing, when the map has at least three keys and one of them uses `&`. An atom is a **don't-care** when flipping it never changes which value the map resolves to; every key that mentions a don't-care atom is dropped.
90
90
 
91
91
  ### How It Works
92
92
 
93
- 1. Gather the unique set of top-level AND atoms across all keys.
94
- 2. An atom is **redundant** when every entry that contains it has a same-value partner with the atom absent and the rest of the atoms identical.
95
- 3. Keys containing `|`, `^`, or `,` at top level are treated as opaque single atoms (they don't participate in atom-level extraction).
96
- 4. Drop redundant atoms from every key; collapse duplicates.
93
+ 1. Split each key into its top-level `&` atoms. Keys containing `|`, `^`, or `,` at top level are a single opaque atom. The `_` floor (and a misused `_` key) is kept verbatim and left out of the analysis.
94
+ 2. Treat the map as the cascade it is: the last authored key whose atoms all hold wins, and `''` is always the lowest priority.
95
+ 3. An atom is a don't-care when, in every state, the cascade resolves to the same value with the atom present as with it absent. Only the states `(K₁ minus the atom) ∪ K₀`, for every key `K₁` that contains the atom and every key `K₀` that does not (or none), can tell the two apart, so the check is quadratic in the number of keys rather than exponential in atoms.
96
+ 4. Drop every key that contains a don't-care atom. With the atom forced absent those keys never match, and by definition the result is unchanged.
97
+
98
+ The check is over the cascade, not over pairs of keys. In `{ '': A, checked: B, 'invalid & checked': C, disabled: A }`, `disabled` has the default's value, but it outranks `checked`: a checked, disabled element gets `A`, so `disabled` is not a don't-care. (An earlier pairwise rule — "every key with the atom has a same-value partner without it" — folded `disabled` into `''` here and lost that priority.)
99
+
100
+ Atoms are compared as strings and treated as independent. Real atoms can be related (`theme=dark` vs `theme=light`, nested media ranges); that only rules states out, so a don't-care over independent atoms is one for every real state too. Two guards keep the rewrite safe: a map with more than 32 distinct atoms is left unreduced, and a reduction that would leave the `_` floor alone with `''` (which means "use the floor", see Stage 1) is skipped.
97
101
 
98
102
  ### Why
99
103
 
100
- Removing don't-care dimensions before parsing prevents combinatorial blowup in later stages. `mergeEntriesByValue`, `buildExclusiveConditions`, and materialization all see fewer entries and fewer spurious conditions. Implemented as part of the Apr 2026 fix for overlapping CSS rules (commit 7cd9dbe).
104
+ Removing don't-care dimensions before parsing prevents combinatorial blowup in later stages. `mergeEntriesByValue`, `buildExclusiveConditions`, and materialization all see fewer entries and fewer spurious conditions.
101
105
 
102
106
  ### Example
103
107
 
@@ -120,6 +124,8 @@ Removing don't-care dimensions before parsing prevents combinatorial blowup in l
120
124
 
121
125
  Converts each state key in a style value map (like `'hovered & !disabled'`, `'@media(w < 768px)'`) into `ConditionNode` trees. `parseStyleEntries` walks the object keys in source order and assigns priorities; `parseStateKey` parses a single key string.
122
126
 
127
+ `parseStyleEntries` also handles the bare `''` default and the standalone `_` fallback floor before the priority order is finalized. The bare `''` default only behaves correctly as the lowest-priority state, so a misplaced one is moved to the front (`MISPLACED_DEFAULT_STATE` warning). The `_` key is pulled out as a separate floor entry (`floor: true`, `TrueCondition`) and always assigned the lowest priority. If a map defines only `_` and a bare `''` (no other states), the `''` default is redundant — it is dropped in favor of the `_` value (`REDUNDANT_DEFAULT_STATE` warning). A `_` combined with state logic (`_ & hovered`, `_ | x`) is ignored (`INVALID_FALLBACK_KEY` warning).
128
+
123
129
  ### How It Works
124
130
 
125
131
  1. **Tokenization**: The state key is split into tokens using a regex pattern that recognizes:
@@ -179,38 +185,68 @@ The condition tree representation enables:
179
185
 
180
186
  ### What It Does
181
187
 
182
- Collapses parsed entries that share the same value. Only **non-default** entries are merged — an entry with the default state (`''` → `TrueCondition`) is never merged with a non-default entry.
188
+ Collapses parsed entries that share the same value when doing so provably preserves the authored cascade. Only **non-default** entries are merged — an entry with the default state (`''` → `TrueCondition`) is never merged with a non-default entry.
183
189
 
184
190
  ### How It Works
185
191
 
186
- 1. Group entries by serialized value.
187
- 2. Within each group, split out default (TRUE) entries.
188
- 3. Keep default entries as-is; they must retain TRUE so they participate correctly in exclusive building.
189
- 4. Combine non-default entries into a single entry with condition `OR(e1.condition, e2.condition, …)`, simplified via `simplifyCondition`. The merged entry keeps the **highest** priority in the group.
190
- 5. Re-sort by priority (highest first).
192
+ Entries arrive sorted highest-priority-first. For each entry the pass walks already-emitted entries from most-recent backward, looking for the nearest same-value entry where merging is safe. If found, the two entries collapse into one (priority becomes the maximum of the pair, condition becomes the simplified `OR`). Default entries are emitted as singletons and never participate in a merge.
193
+
194
+ ### The Safety Condition
195
+
196
+ Merging two same-value entries with conditions `C_h` (higher priority) and `C_l` (lower priority) lifts the lower one up to `p_h` and changes the higher-priority "blocker" for every intermediate-priority entry from `!C_h` to `!(C_h | C_l) = !C_h & !C_l`. The added `!C_l` constraint can incorrectly block an intermediate entry that should have won.
197
+
198
+ The merge is safe iff for every entry `e_m` strictly between them in priority with a different value,
199
+
200
+ ```
201
+ simplify(C_m & C_l & !C_h) = FALSE
202
+ ```
203
+
204
+ i.e. there is no scenario where the intermediate state could have matched, the lower same-value entry would also have matched, and the higher one would not. This is the only way the merge could leak through and shadow the intermediate state.
205
+
206
+ An intermediate whose condition always holds (a tautological key, or same-value keys that already merged into one, like `beta | !beta`) is checked like any other. Only the `''` default and the `_` floor are exempt from the check, and they are always the lowest priorities, so they are never intermediates.
191
207
 
192
208
  ### Why
193
209
 
194
- Without this, a value map like `{ '@dark': 'red', '@dark & @hc': 'red' }` would create two separate entries that later produce two CSS rules with identical output. Merging before exclusive building keeps the exclusive condition algebra small and avoids duplicate CSS.
210
+ Without this pass a value map like `{ '@dark': 'red', '@dark & @hc': 'red' }` would create two separate entries that later produce two CSS rules with identical output. Merging before exclusive building keeps the exclusive condition algebra small and avoids duplicate CSS. The safety check ensures we never break the cascade in service of this optimization.
195
211
 
196
- **Why defaults are kept separate:** merging `TRUE | X` collapses to `TRUE`, destroying X's participation in the exclusive cascade. Intermediate-priority states would then lose their `:not(X)` negation, producing overlapping CSS rules. See `exclusive.ts:140-160` for the rationale.
212
+ **Why defaults are kept separate:** merging `TRUE | X` collapses to `TRUE`, destroying X's participation in the exclusive cascade. Intermediate-priority states would then lose their `:not(X)` negation, producing overlapping CSS rules.
197
213
 
198
- ### Example
214
+ ### Example — Safe merge (still collapses)
199
215
 
200
216
  ```typescript
201
- // Input entries (highest priority first)
217
+ // { '@dark & @hc': 'red', '@dark': 'red' }
218
+ // Input entries (highest priority first), no intermediate different-value entry
202
219
  [
203
- { stateKey: '@dark & @hc', value: 'red', condition: dark & hc },
204
- { stateKey: '@dark', value: 'red', condition: dark },
220
+ { stateKey: '@dark & @hc', value: 'red', condition: dark & hc, priority: 1 },
221
+ { stateKey: '@dark', value: 'red', condition: dark, priority: 0 },
205
222
  ]
206
223
 
207
- // Output: one merged entry
224
+ // Safe: no intermediates. Output: one merged entry
208
225
  [
209
226
  { stateKey: '@dark & @hc | @dark', value: 'red',
210
- condition: simplify((dark & hc) | dark) = dark }
227
+ condition: simplify((dark & hc) | dark) = dark, priority: 1 }
211
228
  ]
212
229
  ```
213
230
 
231
+ The compound dark/HC dedup pattern `{ '': light, '@dark': dark, '@hc': hc, '@dark & @hc': dark }` also collapses cleanly because `@hc & @dark & !(@dark & @hc)` simplifies to FALSE — the intermediate `@hc` is structurally blocked by the contradiction.
232
+
233
+ ### Example — Unsafe merge (must NOT collapse)
234
+
235
+ ```typescript
236
+ // { hovered: 'red', pressed: 'blue', disabled: 'red' }
237
+ // Authored cascade: disabled > pressed > hovered.
238
+ // Merging hovered (priority 0) with disabled (priority 2) would lift
239
+ // hovered to priority 2 and rewrite `pressed`'s exclusive from
240
+ // `pressed & !disabled` to `pressed & !disabled & !hovered`, making
241
+ // `pressed + hovered` resolve to red instead of blue.
242
+
243
+ // `simplify(pressed & hovered & !disabled)` is not FALSE — three
244
+ // independent modifiers can all be active — so the entries are kept
245
+ // separate. Stage 6 `mergeByValue` will later combine the two red
246
+ // CSS rules into one selector group, but only after the cascade is
247
+ // correctly resolved.
248
+ ```
249
+
214
250
  ---
215
251
 
216
252
  ## Stage 2a: Expand User OR Branches
@@ -265,7 +301,35 @@ B: B & !A (applies only when A doesn't)
265
301
  C: C & !A & !B (applies only when neither A nor B)
266
302
  ```
267
303
 
268
- Each exclusive condition is passed through `simplifyCondition`. Entries that simplify to `FALSE` (impossible) are filtered out. The default state (`''` → `TrueCondition`) is not added to the “prior” list for negation (see `buildExclusiveConditions`).
304
+ Each exclusive condition is passed through `simplifyCondition`. Entries that simplify to `FALSE` (impossible) are filtered out.
305
+
306
+ Every entry is added to the "prior" list, including one whose condition is `TRUE`. That can be a tautological key, or same-value keys that merged into one in Stage 1b (`alpha: X, '!alpha': X` → `TRUE`). Such an entry always applies at its priority, so negating it correctly makes every lower entry `FALSE`. The bare `''` default is `TRUE` too, but it is always the lowest priority, so no entry comes after it.
307
+
308
+ ### `_` fallback floor
309
+
310
+ An entry flagged `floor: true` (from the standalone `_` key) is the one
311
+ exception to the negation cascade above. `buildExclusiveConditions` **pulls the
312
+ floor entries out** before the negation pass, builds the remaining entries with a
313
+ plain unconditional negation loop, then re-appends each floor with its own
314
+ (`TRUE`) condition as the exclusive condition. So the floor **always applies**,
315
+ never receives `!prior`, and never negates lower-priority entries. Because its
316
+ condition is `TRUE`, Stage 1 `mergeEntriesByValue` already leaves it untouched
317
+ (same guard as the bare `''` default), so no floor-specific merge handling is
318
+ needed.
319
+
320
+ This exists to fix the *unknown-query hole*: CSS three-valued logic makes
321
+ `not(unknown) = unknown`, so a negated `@supports(...)` / container-query default
322
+ branch silently never applies. A `_` floor sidesteps negation entirely and lets
323
+ the positive override layer on top via the cascade (see Stage 7's `:where()`
324
+ equalization and the ascending-priority post-pass).
325
+
326
+ Because the floor is **additive** (always emitted, never negated) rather than
327
+ mutually exclusive, it differs observably from the `''` default in two ways
328
+ beyond the unknown-query fix: an "empty" higher-priority state (one that emits no
329
+ declarations) cannot unset the property — the floor still applies — and when
330
+ states emit different declaration sets, the floor's declarations bleed through
331
+ wherever a winning state does not override the same property. The `''` default,
332
+ being negated, swaps out cleanly. See the DSL guide's "`_` vs the `''` default".
269
333
 
270
334
  ### Why
271
335
 
@@ -300,29 +364,36 @@ This is the companion to **Stage 2a** (user-OR expansion). The split exists beca
300
364
 
301
365
  | Stage | Runs on | Sees ORs from | Sorts branches? |
302
366
  |---|---|---|---|
303
- | 2a `expandOrConditions` | `ParsedStyleEntry.condition` | User-authored `|` in state keys | No — user order is stable |
367
+ | 2a `expandOrConditions` | `ParsedStyleEntry.condition` | User-authored `\|` in state keys | No — user order is stable |
304
368
  | 3 `expandExclusiveOrs` | `ExclusiveStyleEntry.exclusiveCondition` | De Morgan negation inside `buildExclusiveConditions` | Yes — at-rule branches first |
305
369
 
306
370
  ### How It Works
307
371
 
308
372
  1. Collect top-level OR branches of `exclusiveCondition`.
309
373
  2. If there is no OR (single branch), the entry is unchanged. Pure selector ORs with no at-rule context are also left alone (materialization handles them via `:is()` / variant merging).
310
- 3. Otherwise `sortOrBranchesForExpansion` reorders branches so at-rule-heavy branches come first. This is load-bearing for correctness (see below).
374
+ 3. Otherwise `sortOrBranchesForExpansion` reorders branches by a three-tier rank — `@supports` branches first, then other at-rule branches (media / container / starting), then pure-selector branches. This is load-bearing for correctness (see below).
311
375
  4. Each branch is made exclusive against prior branches: `branch & !prior[0] & !prior[1] & ...`, then simplified.
312
376
  5. Impossible branches are dropped; expanded entries get a synthetic `stateKey` suffix like `[or:0]`.
313
377
 
314
378
  ### Why the sort matters
315
379
 
316
- Consider `!A | !B` where A is an at-rule (e.g. `@supports(grid)`) and B is a modifier (e.g. `:has(foo)`):
380
+ **At-rules before selectors.** Consider `!A | !B` where A is an at-rule (e.g. `@supports(grid)`) and B is a modifier (e.g. `:has(foo)`):
317
381
 
318
382
  - **With at-rule-first sort** (`!A`, then `!B & A`): the first branch emits "outside `@supports`", the second emits "inside `@supports` with `:not(:has(foo))`". Full coverage.
319
383
  - **Without the sort** (`!B`, then `!A & B`): the first branch emits `:not(:has(foo))` as a bare selector with no at-rule context — leaking the rule outside `@supports`. The second is incomplete.
320
384
 
385
+ **`@supports` before other at-rules (Kleene logic).** A `@supports` feature query is special: anything ANDed with it can become *unknown* — not simply false — when the feature is unsupported. The canonical case is a feature guard over a dependent query, e.g. `@supports(container-type: scroll-state) & @(scroll-state(scrolled: block-end))` (`S & C`). The default's exclusive is `!(S & C) = !S | !C`, which `simplify` sorts alphabetically into `[!C, !S]`.
386
+
387
+ - **Expanding `!C` first** emits a bare `@container (not scroll-state(...))` rule. In a browser without `scroll-state` support that query is unknown (not false), so it matches nothing and the default `inset` is never applied — a coverage hole.
388
+ - **Expanding `!S` first** yields `!S | (S & !C)`: a bare `@supports (not (container-type: scroll-state))` fallback carrying the default, plus the dependent negation nested inside the supported scope. Full coverage, and the unsupported path never references the guarded query.
389
+
390
+ Because `!S | (S & !R) ≡ !S | !R` in two-valued logic, this reordering is a no-op for cases without an `@supports` guard. The same supports-first ordering is also applied in `makeOrBranchesExclusive` (`materialize.ts`) for ORs that survive nested inside an AND (e.g. `compact & (!S | !C)`).
391
+
321
392
  The pre-build Stage 2a pass doesn't need this because user-authored ORs aren't produced by negation and their branches are expected to apply in each branch's own scope.
322
393
 
323
394
  ### Example (conceptual)
324
395
 
325
- See the comment block in `exclusive.ts:500-523`: a default value whose higher-priority sibling is `@supports(...) & :has(...)` gets an exclusive of `!@supports | !:has`. Expansion yields one branch under `@supports (not ...)` and another under `@supports (...) { :not(:has()) }` instead of a bare `:not(:has())` rule.
396
+ See the comment block on `expandExclusiveOrs` in `exclusive.ts`: a default value whose higher-priority sibling is `@supports(...) & :has(...)` gets an exclusive of `!@supports | !:has`. Expansion yields one branch under `@supports (not ...)` and another under `@supports (...) { :not(:has()) }` instead of a bare `:not(:has())` rule.
326
397
 
327
398
  ---
328
399
 
@@ -334,6 +405,8 @@ See the comment block in `exclusive.ts:500-523`: a default value whose higher-pr
334
405
 
335
406
  Computes the Cartesian product of all style entries for a handler, creating snapshots of which value each style has for each possible state combination.
336
407
 
408
+ When every input is a direct value rather than a state map, the pipeline skips stages 0–4 and passes one unconditional snapshot directly to the handler. This avoids building exclusive entries and a Cartesian product for ordinary state-free styles.
409
+
337
410
  ### How It Works
338
411
 
339
412
  1. Collect exclusive entries for each style the handler uses
@@ -393,6 +466,7 @@ Style handlers encapsulate the logic for translating design tokens (like `'2x'`)
393
466
  ### What It Does
394
467
 
395
468
  Combines rules that have identical CSS output into a single rule with an OR condition.
469
+ Zero- and one-rule inputs return unchanged because no merge is possible.
396
470
 
397
471
  ### How It Works
398
472
 
@@ -444,7 +518,15 @@ Converts condition trees into actual CSS selectors and at-rules.
444
518
 
445
519
  3. **Contradiction detection**: During variant merging, impossible combinations are dropped (e.g. conflicting media, root, or modifier negations).
446
520
 
447
- 4. **`materializeComputedRule`**: Groups variants by sorted at-rules plus root-prefix key; within each group, `mergeVariantsIntoSelectorGroups` merges variants that differ only in flat modifier/pseudo parts; builds selector strings and emits one or more `CSSRule` objects.
521
+ 4. **`materializeComputedRule`**: Groups variants by sorted at-rules plus root-prefix key; within each group, `mergeVariantsIntoSelectorGroups` merges variants that differ only in flat modifier/pseudo parts; builds selector strings and emits one or more `CSSRule` objects. The rule's `order` hint (cascade priority) is propagated here for the post-pass sort.
522
+
523
+ 5. **`:where()` specificity equalization**: Every stateful part of the selector is wrapped in `:where(...)` so it contributes **zero specificity**:
524
+ - the flat root modifiers + pseudos and the root element's `:is()`/`:not()` groups are combined into one `:where(...)` (`buildSelectorFromVariant`);
525
+ - the sub-element (`@own`) groups are wrapped in a **separate** `:where(...)` so the sub-element's structural `[data-element="X"]` specificity is preserved while its states are zeroed. When the suffix ends in a pseudo-element, these are the pseudo-element's own states and stay after it (`a::before:where(:hover)`). States a pseudo-element can't have (attributes, modifiers, classes, tree-structural pseudo-classes) are dropped with a `PSEUDO_ELEMENT_STATE_IGNORED` warning before Stage 0, using the CSS language alone, never per-browser support (`pseudo-element-states.ts`). A direct selector that ends in a pseudo-element (`.card::before`) is rendered separately: its root states are checked the same way and go after the pseudo-element, its `@parent` segments before it, at the `pseudoElementAt` each `CSSRule` records;
526
+ - `@parent` ancestors (`parentGroupsToCSS`) become `:where(... *)` / `:where(:not(... *))`;
527
+ - the `@root` context prefix (`rootStateToPrefix`) becomes `:where(:root...)` (zeroing the `:root` pseudo too). When a direct selector can only match the root itself (`:root`, `html`, `:where(:root)`), the state segment joins it instead — `:root:where([data-schema="dark"])` — since an ancestor prefix would ask for a `:root` inside the root.
528
+
529
+ The only specificity anchors that remain are the doubled component class (`.tXX.tXX`, added by the injector) and sub-element `[data-element]` attributes. Because Stage 2b already makes ordinary rules mutually exclusive, zeroing specificity never changes *which* rule matches — it only makes additive layering (`_` fallback floor, `@starting-style`) resolve deterministically by source order (see the post-pass). Canonical sorting/dedup/subsumption still run first; `:where()` is only the final wrapper, and both output paths (injector and direct-selector / SSR) consume the same wrapped fragments.
448
530
 
449
531
  ### Why
450
532
 
@@ -465,10 +547,13 @@ interface CSSRule {
465
547
  declarations: string; // CSS declarations (e.g. 'color: red;')
466
548
  atRules?: string[]; // Wrapping at-rules
467
549
  rootPrefix?: string; // Root state prefix
550
+ rootState?: string; // Root-state segment without its :root anchor; lets a root selector take states directly
551
+ startingStyle?: boolean; // Wrap declarations in @starting-style
552
+ order?: number; // Internal cascade order hint (ascending source priority); stripped before injection
468
553
  }
469
554
  ```
470
555
 
471
- When `renderStylesPipeline` runs **without** a class name, returned rules include `needsClassName: true` (compatibility field for the injector); that flag is not part of `CSSRule` inside `materialize.ts`.
556
+ When `renderStyles` runs **without** a selector, returned rules include `needsClassName: true` (compatibility field for the injector); that flag is not part of `CSSRule` (defined in `materialize-types.ts`).
472
557
 
473
558
  ---
474
559
 
@@ -536,7 +621,7 @@ Applies boolean algebra rules to reduce condition complexity and detect impossib
536
621
  - `A & (A | B) = A`
537
622
  - `A | (A & B) = A`
538
623
 
539
- 7. **Range intersection**: For **media and container** dimension queries, impossible ranges simplify to `FALSE` (e.g. `@media(w > 400px) & @media(w < 300px)`). Ranges with compatible bounds are also merged in place (`w >= 400 & w <= 800` → a single bounded range).
624
+ 7. **Range intersection**: For **media and container** dimension queries, impossible ranges simplify to `FALSE` (e.g. `@media(w > 400px) & @media(w < 300px)`). Ranges with compatible bounds are also merged in place (`w >= 400 & w <= 800` → a single bounded range). Only bounds in the same unit are compared: `600px` and `40em` are never merged or found contradictory, because a query `em` follows the user's default font size. A bound with no numeric value (`calc(…)`) and a range whose two bounds use different units are left as they are.
540
625
 
541
626
  8. **Container style queries**: Conflicting or redundant `@container` style conditions on the same property can be reduced (see `simplify.ts` around the container-style conflict pass).
542
627
 
@@ -560,7 +645,7 @@ LRU and small auxiliary caches:
560
645
  | Cache | Size | Key | Purpose |
561
646
  |-------|------|-----|---------|
562
647
  | `pipelineCache` | 5000 | `pipelineCacheKey \|\| stringifyStyles(styles)` | Skip full pipeline for identical styles |
563
- | `parseCache` | 5000 | `trimmedStateKey + '\\0' + isSubElement + '\\0' + JSON.stringify(localPredefinedStates)` | Skip re-parsing identical state keys in context |
648
+ | `parseCache` | 5000 | `trimmedStateKey + '\0' + (isSubElement ? '1' : '0') + '\0' + (localPredefinedStates non-empty ? JSON.stringify(localPredefinedStates) : '')` | Skip re-parsing identical state keys in context |
564
649
  | `simplifyCache` | 5000 | `getConditionUniqueId(node)` | Skip re-simplifying identical conditions |
565
650
  | `conditionCache` | 3000 | `getConditionUniqueId(node)` in `conditionToCSS` | Skip re-materializing identical conditions |
566
651
  | `variantKeyCache` | — | `WeakMap<SelectorVariant, string>` | Stable string keys for variants during materialization |
@@ -612,7 +697,7 @@ The default entry's exclusive is `!hovered & !@media(dark)` — no top-level OR,
612
697
 
613
698
  ### Stages 4–5: Compute combinations and call handler
614
699
 
615
- Single style, three snapshots; the `color` handler emits `color` plus `--current-color*` variables.
700
+ Single style, three snapshots; the `color` handler emits `color` plus a `--current-color` variable.
616
701
 
617
702
  ### Stage 6: Merge by value
618
703
 
@@ -620,27 +705,24 @@ Each snapshot yields distinct declarations; no merge.
620
705
 
621
706
  ### Stage 7: Materialize CSS
622
707
 
623
- Using `renderStyles(styles, '.t1')` (single class prefix; `renderStylesPipeline` doubles the class for specificity when a class name is supplied):
708
+ Using `renderStyles(styles, '.t1', { doubleSelector: true })`. The injector doubles the class the same way (`.t1.t1`) so Tasty owns specificity without `!important`, and every state is wrapped in `:where()` so it adds none. Rules come out in ascending priority:
624
709
 
625
710
  ```css
626
- .t1[data-hovered] {
627
- color: var(--highlight-color);
628
- --current-color: var(--highlight-color);
629
- --current-color-oklch: var(--highlight-color-oklch);
711
+ @media (not (prefers-color-scheme: dark)) {
712
+ .t1.t1:where(:not([data-hovered])) {
713
+ color: var(--white-color);
714
+ --current-color: var(--white-color);
715
+ }
630
716
  }
631
717
  @media (prefers-color-scheme: dark) {
632
- .t1:not([data-hovered]) {
718
+ .t1.t1:where(:not([data-hovered])) {
633
719
  color: var(--dark-color);
634
720
  --current-color: var(--dark-color);
635
- --current-color-oklch: var(--dark-color-oklch);
636
721
  }
637
722
  }
638
- @media (not (prefers-color-scheme: dark)) {
639
- .t1:not([data-hovered]) {
640
- color: var(--white-color);
641
- --current-color: var(--white-color);
642
- --current-color-oklch: var(--white-color-oklch);
643
- }
723
+ .t1.t1:where([data-hovered]) {
724
+ color: var(--highlight-color);
725
+ --current-color: var(--highlight-color);
644
726
  }
645
727
  ```
646
728
 
@@ -671,3 +753,16 @@ Impossible combinations are detected at multiple levels (simplification, variant
671
753
  ### 4. Aggressive Caching
672
754
 
673
755
  Parse, simplify, condition-to-CSS, and full-pipeline results are cached independently, enabling fast re-rendering when only parts of the style object change.
756
+
757
+ Cache keys must respect key order where it carries meaning. A state map resolves by key order, so `{ '': A, checked: B, disabled: C }` and `{ '': A, disabled: C, checked: B }` are different styles and must get different keys (and classes). Only the style keys of a styles object, including a sub-element's, are order-insensitive, so they may be sorted. `stringifyStyles` (pipeline cache) and `generateChunkCacheKey` (class allocation) both follow this rule.
758
+
759
+ ---
760
+
761
+ ## Testing Priority
762
+
763
+ Every stage above is an optimization that must leave one thing unchanged: in any state, the value that applies is the value of the last authored key whose condition holds. `src/test/state-oracle.ts` states that rule directly, with none of the pipeline's machinery, and two suites compare the pipeline against it:
764
+
765
+ - `src/pipeline/exclusive.test.ts` (Node) evaluates the conditions after each of Stages 0–3 on thousands of generated maps, and names the stage that disagrees.
766
+ - `src/pipeline/state-priority.test.ts` (browser) renders hand-written, permuted, and generated maps to CSS, applies every combination of states (modifiers, value modifiers, `:has()`, `@root`, `@parent`, `@own`, media, supports), and compares what the browser computes against the oracle. It also checks that rules stay mutually exclusive, which a correct computed value alone can hide. It runs through the pipeline, the runtime injector, and the SSR collector, with all maps mounted at once so a cache-key collision shows up.
767
+
768
+ A change to any stage should keep both green. When a generated map fails, the message includes the map, the failing states, and the CSS; the map is usually worth adding to the hand-written cases once it is reduced.