@tenphi/tasty 0.0.0-snapshot.27699f6 → 0.0.0-snapshot.27b6708

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 (91) hide show
  1. package/README.md +171 -107
  2. package/dist/{async-storage-B7_o6FKt.js → async-storage-DKK-wTD4.js} +1 -1
  3. package/dist/{async-storage-B7_o6FKt.js.map → async-storage-DKK-wTD4.js.map} +1 -1
  4. package/dist/babel-BUQGeOXA.d.ts +83 -0
  5. package/dist/{collector-QwpPODsy.js → collector-DTahQUiV.js} +97 -23
  6. package/dist/collector-DTahQUiV.js.map +1 -0
  7. package/dist/{collector-LuU1vZ68.d.ts → collector-DUaHCcTS.d.ts} +54 -7
  8. package/dist/{config-rrijM-U2.js → config-B5kHzuNz.js} +5144 -3012
  9. package/dist/config-B5kHzuNz.js.map +1 -0
  10. package/dist/{config-vuCRkBWX.d.ts → config-YsxGv4tq.d.ts} +412 -33
  11. package/dist/{context-CkSg-kDT.js → context-CA8YKeMn.js} +1 -1
  12. package/dist/{context-CkSg-kDT.js.map → context-CA8YKeMn.js.map} +1 -1
  13. package/dist/core/index.d.ts +5 -5
  14. package/dist/core/index.js +6 -6
  15. package/dist/{core-BvTG0J_M.js → core-Dr4u1NVD.js} +162 -188
  16. package/dist/core-Dr4u1NVD.js.map +1 -0
  17. package/dist/{css-writer-C7HJGEmN.js → css-writer-B-J87ncv.js} +78 -17
  18. package/dist/css-writer-B-J87ncv.js.map +1 -0
  19. package/dist/{format-global-rules-Dbc_1tc3.js → format-global-rules-DklyaXv-.js} +1 -1
  20. package/dist/{format-global-rules-Dbc_1tc3.js.map → format-global-rules-DklyaXv-.js.map} +1 -1
  21. package/dist/{format-rules-BvokPr1L.js → format-rules-DKOA-6qu.js} +4 -17
  22. package/dist/format-rules-DKOA-6qu.js.map +1 -0
  23. package/dist/{hydrate-Dsv7Pwon.js → hydrate-OeMX99We.js} +3 -11
  24. package/dist/{hydrate-Dsv7Pwon.js.map → hydrate-OeMX99We.js.map} +1 -1
  25. package/dist/{index-dUtwpOux.d.ts → index-Cd45t5NM.d.ts} +319 -64
  26. package/dist/{index-ZRxZWzlj.d.ts → index-PqN-DIpn.d.ts} +498 -189
  27. package/dist/index.d.ts +5 -5
  28. package/dist/index.js +253 -63
  29. package/dist/index.js.map +1 -1
  30. package/dist/{keyframes-DDqRjwa9.js → keyframes-CV8azJf3.js} +97 -191
  31. package/dist/keyframes-CV8azJf3.js.map +1 -0
  32. package/dist/{merge-styles-CtDJMhpJ.d.ts → merge-styles-CU7JbEwg.d.ts} +2 -2
  33. package/dist/{merge-styles-B8jV6zu3.js → merge-styles-oklji0KB.js} +2 -2
  34. package/dist/{merge-styles-B8jV6zu3.js.map → merge-styles-oklji0KB.js.map} +1 -1
  35. package/dist/{resolve-recipes-BnTZz2I_.js → resolve-recipes-DTG81rzl.js} +3 -3
  36. package/dist/{resolve-recipes-BnTZz2I_.js.map → resolve-recipes-DTG81rzl.js.map} +1 -1
  37. package/dist/ssr/astro-client.js +1 -1
  38. package/dist/ssr/astro-client.js.map +1 -1
  39. package/dist/ssr/astro-middleware-static.d.ts +16 -0
  40. package/dist/ssr/astro-middleware-static.js +18 -0
  41. package/dist/ssr/astro-middleware-static.js.map +1 -0
  42. package/dist/ssr/astro-middleware.d.ts +8 -6
  43. package/dist/ssr/astro-middleware.js +10 -10
  44. package/dist/ssr/astro-middleware.js.map +1 -1
  45. package/dist/ssr/astro.d.ts +2 -17
  46. package/dist/ssr/astro.js +29 -21
  47. package/dist/ssr/astro.js.map +1 -1
  48. package/dist/ssr/index.d.ts +2 -9
  49. package/dist/ssr/index.js +5 -5
  50. package/dist/ssr/index.js.map +1 -1
  51. package/dist/ssr/next.d.ts +2 -3
  52. package/dist/ssr/next.js +6 -7
  53. package/dist/ssr/next.js.map +1 -1
  54. package/dist/static/index.d.ts +2 -2
  55. package/dist/static/index.js +4 -4
  56. package/dist/static/index.js.map +1 -1
  57. package/dist/static/inject.js.map +1 -1
  58. package/dist/zero/babel.d.ts +2 -81
  59. package/dist/zero/babel.js +39 -27
  60. package/dist/zero/babel.js.map +1 -1
  61. package/dist/zero/index.d.ts +16 -2
  62. package/dist/zero/index.js +2 -2
  63. package/dist/zero/next.d.ts +1 -1
  64. package/dist/zero/next.js +1 -1
  65. package/dist/zero/next.js.map +1 -1
  66. package/docs/README.md +12 -6
  67. package/docs/adoption.md +53 -28
  68. package/docs/ai-agents.md +224 -0
  69. package/docs/comparison.md +59 -30
  70. package/docs/configuration.md +498 -69
  71. package/docs/debug.md +7 -7
  72. package/docs/design-system.md +43 -24
  73. package/docs/dsl.md +510 -178
  74. package/docs/getting-started.md +55 -34
  75. package/docs/injector.md +58 -5
  76. package/docs/methodology.md +68 -36
  77. package/docs/migration-v3.md +285 -0
  78. package/docs/pipeline.md +93 -25
  79. package/docs/plugins.md +349 -0
  80. package/docs/react-api.md +162 -38
  81. package/docs/ssr.md +45 -35
  82. package/docs/styles.md +65 -16
  83. package/docs/tasty-static.md +25 -8
  84. package/package.json +43 -21
  85. package/tasty.config.ts +6 -0
  86. package/dist/collector-QwpPODsy.js.map +0 -1
  87. package/dist/config-rrijM-U2.js.map +0 -1
  88. package/dist/core-BvTG0J_M.js.map +0 -1
  89. package/dist/css-writer-C7HJGEmN.js.map +0 -1
  90. package/dist/format-rules-BvokPr1L.js.map +0 -1
  91. package/dist/keyframes-DDqRjwa9.js.map +0 -1
package/docs/react-api.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # React API
2
2
 
3
- The React-specific `tasty()` component factory, component props, and style functions. All Tasty style functions — `tasty()` components, `useStyles()`, `useGlobalStyles()`, `useRawCSS()`, `useKeyframes()`, `useProperty()`, `useFontFace()`, and `useCounterStyle()` — are hook-free and compatible with React Server Components. No `'use client'` directive needed. For the shared style language (state maps, tokens, units, extending semantics), see [Style DSL](dsl.md). For global configuration, see [Configuration](configuration.md). For the broader docs map, see the [Docs Hub](README.md).
3
+ Use `tasty()` to turn state-aware style definitions into normal React components, extend existing Tasty components, and expose typed styling APIs to consumers.
4
+
5
+ All Tasty style functions — `tasty()` components, `useStyles()`, `useGlobalStyles()`, `useRawCSS()`, `useKeyframes()`, `useProperty()`, `useFontFace()`, `useCounterStyle()`, and `useFunction()` — are hook-free and compatible with React Server Components. No `'use client'` directive is needed. For state maps, tokens, units, and extension semantics, see [Style DSL](dsl.md). For global configuration, see [Configuration](configuration.md). For the broader docs map, see the [Docs Hub](README.md).
4
6
 
5
7
  > **Note:** This file was previously named `runtime.md`. All functionality documented here works in both server and client contexts — "runtime" referred to style computation during React rendering, not to client-side JavaScript.
6
8
 
@@ -42,6 +44,32 @@ const PrimaryButton = tasty(Button, {
42
44
 
43
45
  Style maps merge intelligently — see [Style DSL — Extending vs. Replacing State Maps](dsl.md#extending-vs-replacing-state-maps) for extend mode, replace mode, `@inherit`, `null`, and `false` tombstones.
44
46
 
47
+ `tasty(Component, ...)` always wraps `Component` and forwards every prop to it, so `Component` must be Tasty-aware (i.e. it accepts `styles`, `mods`, `qa`, etc. and renders them through its own Tasty pipeline). To apply styles to a third-party component or a string DOM tag via `className`, use the options-only form with `as`:
48
+
49
+ ```jsx
50
+ import NextLink from 'next/link';
51
+
52
+ const Link = tasty({
53
+ as: NextLink,
54
+ styles: {
55
+ color: { '': '#accent-text', ':hover': '#text' },
56
+ textDecoration: 'underline',
57
+ },
58
+ styleProps: ['padding'],
59
+ });
60
+
61
+ const Span = tasty({
62
+ as: 'span',
63
+ styles: { preset: 'strong' },
64
+ });
65
+
66
+ <Link href="/blog" padding="1x">
67
+ Blog
68
+ </Link>;
69
+ ```
70
+
71
+ The wrapped component only needs to forward `className` (and ideally `style`/`ref`). Tasty-specific props (`qa`, `qaVal`, `mods`, `tokens`, `styleProps`, `modProps`, `tokenProps`) are consumed by Tasty and never leak to the DOM.
72
+
45
73
  ---
46
74
 
47
75
  ## Style Props
@@ -60,7 +88,7 @@ const FlexibleBox = tasty({
60
88
 
61
89
  <FlexibleBox gap="2x" align="center" fill="#surface">
62
90
  Content
63
- </FlexibleBox>
91
+ </FlexibleBox>;
64
92
  ```
65
93
 
66
94
  Style props accept state maps, so responsive values work through the same API:
@@ -74,6 +102,26 @@ Style props accept state maps, so responsive values work through the same API:
74
102
 
75
103
  For predefined style prop lists (`FLOW_STYLES`, `POSITION_STYLES`, `DIMENSION_STYLES`, etc.) and guidance on which props to expose per component category, see [Methodology — styleProps as the public API](methodology.md#styleprops-as-the-public-api).
76
104
 
105
+ ### Always-available style props
106
+
107
+ A small set of style properties — `display`, `font`, `preset`, `hide`, `whiteSpace`, `opacity`, and `transition` — are always harvested as style props on every `tasty()` component, even when `styleProps` is omitted. This means you can pass `<Card display="grid" />` or `<Text preset="h1" />` without declaring them. When you do declare `styleProps`, these base props are unioned with your list (not replaced).
108
+
109
+ ---
110
+
111
+ ## `Element`
112
+
113
+ `Element` is the unstyled base component exported from the main entry — equivalent to `tasty({})` (a `div` with no default styles). It accepts all Tasty props (`styles`, `styleProps`, `mods`, `tokens`, `as`, `qa`, `theme`, the `is*` props, etc.) and is useful as a generic styled box or as a building block for layout primitives.
114
+
115
+ ```jsx
116
+ import { Element } from '@tenphi/tasty';
117
+
118
+ <Element as="section" padding="4x" fill="#surface">
119
+ Content
120
+ </Element>;
121
+ ```
122
+
123
+ > Note: `Element` shadows the global DOM `Element` type when imported from `@tenphi/tasty`. In files that need the DOM type, alias the import: `import { Element as TastyElement } from '@tenphi/tasty'`.
124
+
77
125
  ---
78
126
 
79
127
  ## Mod Props
@@ -112,9 +160,9 @@ Map modifier names to type descriptors for precise TypeScript types:
112
160
  ```tsx
113
161
  const Button = tasty({
114
162
  modProps: {
115
- isLoading: Boolean, // isLoading?: boolean
116
- isSelected: Boolean, // isSelected?: boolean
117
- size: ['small', 'medium', 'large'] as const, // size?: 'small' | 'medium' | 'large'
163
+ isLoading: Boolean, // isLoading?: boolean
164
+ isSelected: Boolean, // isSelected?: boolean
165
+ size: ['small', 'medium', 'large'] as const, // size?: 'small' | 'medium' | 'large'
118
166
  },
119
167
  styles: {
120
168
  padding: { '': '2x 4x', 'size=small': '1x 2x', 'size=large': '3x 6x' },
@@ -122,18 +170,20 @@ const Button = tasty({
122
170
  },
123
171
  });
124
172
 
125
- <Button isLoading size="large">Submit</Button>
173
+ <Button isLoading size="large">
174
+ Submit
175
+ </Button>;
126
176
  // Renders: <button data-is-loading="" data-size="large">Submit</button>
127
177
  ```
128
178
 
129
179
  Available type descriptors:
130
180
 
131
- | Descriptor | TypeScript type | Example |
132
- |---|---|---|
133
- | `Boolean` | `boolean` | `isLoading: Boolean` |
134
- | `String` | `string` | `label: String` |
135
- | `Number` | `number` | `count: Number` |
136
- | `['a', 'b'] as const` | `'a' \| 'b'` | `size: ['sm', 'md', 'lg'] as const` |
181
+ | Descriptor | TypeScript type | Example |
182
+ | --------------------- | --------------- | ----------------------------------- |
183
+ | `Boolean` | `boolean` | `isLoading: Boolean` |
184
+ | `String` | `string` | `label: String` |
185
+ | `Number` | `number` | `count: Number` |
186
+ | `['a', 'b'] as const` | `'a' \| 'b'` | `size: ['sm', 'md', 'lg'] as const` |
137
187
 
138
188
  ### Merge with `mods`
139
189
 
@@ -146,11 +196,11 @@ Mod props and the `mods` object can be used together. Mod props take precedence:
146
196
 
147
197
  ### When to use `modProps` vs `mods`
148
198
 
149
- | Use case | Recommendation |
150
- |---|---|
199
+ | Use case | Recommendation |
200
+ | -------------------------------------------- | -------------------------------------------------------- |
151
201
  | Component has a fixed set of known modifiers | `modProps` — cleaner API, better TypeScript autocomplete |
152
- | Component needs arbitrary/dynamic modifiers | `mods` — open-ended `Record<string, ModValue>` |
153
- | Both fixed and dynamic | Combine: `modProps` for known keys, `mods` for ad-hoc |
202
+ | Component needs arbitrary/dynamic modifiers | `mods` — open-ended `Record<string, ModValue>` |
203
+ | Both fixed and dynamic | Combine: `modProps` for known keys, `mods` for ad-hoc |
154
204
 
155
205
  For architecture guidance on when to use modifiers vs `styleProps`, see [Methodology — modProps and mods](methodology.md#modprops-and-mods).
156
206
 
@@ -180,7 +230,7 @@ const ProgressBar = tasty({
180
230
 
181
231
  <ProgressBar progress="75%" accentColor="#purple" />
182
232
  // 'progress' → $progress → --progress
183
- // 'accentColor' → #accent → --accent-color + --accent-color-oklch
233
+ // 'accentColor' → #accent → --accent-color
184
234
  ```
185
235
 
186
236
  ### Object form
@@ -196,7 +246,7 @@ const Card = tasty({
196
246
  styles: { padding: '$card-size', fill: '#card-accent' },
197
247
  });
198
248
 
199
- <Card size="4x" color="#purple" />
249
+ <Card size="4x" color="#purple" />;
200
250
  ```
201
251
 
202
252
  ### Merge with `tokens`
@@ -215,11 +265,11 @@ const Bar = tasty({
215
265
 
216
266
  ### When to use `tokenProps` vs `tokens`
217
267
 
218
- | Use case | Recommendation |
219
- |---|---|
220
- | Component has a fixed set of known token keys | `tokenProps` — cleaner API, better TypeScript autocomplete |
221
- | Component needs arbitrary/dynamic token values | `tokens` — open-ended `Record<string, TokenValue>` |
222
- | Both fixed and dynamic | Combine: `tokenProps` for known keys, `tokens` for ad-hoc |
268
+ | Use case | Recommendation |
269
+ | ---------------------------------------------- | ---------------------------------------------------------- |
270
+ | Component has a fixed set of known token keys | `tokenProps` — cleaner API, better TypeScript autocomplete |
271
+ | Component needs arbitrary/dynamic token values | `tokens` — open-ended `Record<string, TokenValue>` |
272
+ | Both fixed and dynamic | Combine: `tokenProps` for known keys, `tokens` for ad-hoc |
223
273
 
224
274
  For architecture guidance, see [Methodology — tokenProps](methodology.md#tokenprops).
225
275
 
@@ -238,11 +288,11 @@ const Button = tasty({
238
288
  variants: {
239
289
  default: { fill: '#blue', color: '#white' },
240
290
  danger: { fill: '#red', color: '#white' },
241
- outline: { fill: 'transparent', color: '#blue', border: '1bw solid #blue' },
291
+ outline: { fill: '#clear', color: '#blue', border: '1bw solid #blue' },
242
292
  },
243
293
  });
244
294
 
245
- <Button variant="danger">Delete</Button>
295
+ <Button variant="danger">Delete</Button>;
246
296
  ```
247
297
 
248
298
  ### Extending Variants with Base State Maps
@@ -298,7 +348,7 @@ const Card = tasty({
298
348
  <Card>
299
349
  <Card.Title>Card Title</Card.Title>
300
350
  <Card.Content>Card content</Card.Content>
301
- </Card>
351
+ </Card>;
302
352
  ```
303
353
 
304
354
  Each entry in `elements` can be a tag name string or a config object:
@@ -324,7 +374,7 @@ const Card = tasty({
324
374
 
325
375
  <Card>
326
376
  <div data-element="Title">Card Title</div>
327
- </Card>
377
+ </Card>;
328
378
  ```
329
379
 
330
380
  ### Selector Affix (`$`)
@@ -395,6 +445,15 @@ function ThemeStyles() {
395
445
  }
396
446
  ```
397
447
 
448
+ A slot — the `id`, or the selector when no `id` is given — holds exactly one
449
+ injection **per `root`**. So:
450
+
451
+ - Changing the styles replaces the previous CSS rather than adding to it.
452
+ - Passing styles that produce no CSS (for example `{}`) clears the slot.
453
+ - The same selector used in two shadow roots keeps a separate injection in each.
454
+ - Two independent call sites that share a selector share a slot, and the last
455
+ render wins. Give them distinct `id`s if they should coexist.
456
+
398
457
  ### useRawCSS
399
458
 
400
459
  Inject raw CSS strings. Accepts an optional `id` in the options for update tracking — when the CSS changes for the same id, the previous injection is replaced:
@@ -411,6 +470,9 @@ function GlobalReset() {
411
470
  }
412
471
  ```
413
472
 
473
+ An `id` slot holds one injection per `root`. Without an `id` the CSS is deduped
474
+ by content and permanent — there is nothing to replace it with later.
475
+
414
476
  ### useKeyframes
415
477
 
416
478
  Inject `@keyframes` rules and return the generated animation name:
@@ -424,14 +486,14 @@ function Spinner() {
424
486
  from: { transform: 'rotate(0deg)' },
425
487
  to: { transform: 'rotate(360deg)' },
426
488
  },
427
- { name: 'spin' }
489
+ { name: 'spin' },
428
490
  );
429
491
 
430
492
  return <div style={{ animation: `${spin} 1s linear infinite` }} />;
431
493
  }
432
494
  ```
433
495
 
434
- `useKeyframes()` also supports a factory function. The deps array is accepted for backward compatibility but the factory is called on every invocation — deduplication is handled internally by content hash:
496
+ `useKeyframes()` also supports a factory function. Without a `name` the factory runs on every invocation and deduplication is handled internally by content hash; with a `name`, matching deps skip the factory entirely:
435
497
 
436
498
  ```tsx
437
499
  function Pulse({ scale }: { scale: number }) {
@@ -440,13 +502,24 @@ function Pulse({ scale }: { scale: number }) {
440
502
  '0%': { transform: 'scale(1)' },
441
503
  '100%': { transform: `scale(${scale})` },
442
504
  }),
443
- [scale]
505
+ [scale],
506
+ { name: 'pulse' },
444
507
  );
445
508
 
446
- return <div style={{ animation: `${pulse} 500ms ease-in-out alternate infinite` }} />;
509
+ return (
510
+ <div
511
+ style={{ animation: `${pulse} 500ms ease-in-out alternate infinite` }}
512
+ />
513
+ );
447
514
  }
448
515
  ```
449
516
 
517
+ Passing `name` claims a slot owned by that one call site, per `root` — much like
518
+ `id` in `useGlobalStyles()` and `useRawCSS()`. When the steps change the previous
519
+ `@keyframes` rule is disposed and the name is reused, so the rules don't
520
+ accumulate and the returned name stays stable. Anonymous keyframes are permanent
521
+ and shared by content.
522
+
450
523
  ### useProperty
451
524
 
452
525
  Register a CSS `@property` rule so a custom property can animate smoothly:
@@ -493,8 +566,16 @@ For multiple weights/styles, pass an array:
493
566
 
494
567
  ```tsx
495
568
  useFontFace('Brand Sans', [
496
- { src: 'url("/fonts/brand-regular.woff2") format("woff2")', fontWeight: 400, fontDisplay: 'swap' },
497
- { src: 'url("/fonts/brand-bold.woff2") format("woff2")', fontWeight: 700, fontDisplay: 'swap' },
569
+ {
570
+ src: 'url("/fonts/brand-regular.woff2") format("woff2")',
571
+ fontWeight: 400,
572
+ fontDisplay: 'swap',
573
+ },
574
+ {
575
+ src: 'url("/fonts/brand-bold.woff2") format("woff2")',
576
+ fontWeight: 700,
577
+ fontDisplay: 'swap',
578
+ },
498
579
  ]);
499
580
  ```
500
581
 
@@ -512,11 +593,14 @@ Inject a `@counter-style` rule and get back the counter style name. Permanent
512
593
  import { useCounterStyle } from '@tenphi/tasty';
513
594
 
514
595
  function EmojiList() {
515
- const styleName = useCounterStyle({
516
- system: 'cyclic',
517
- symbols: '"👍"',
518
- suffix: '" "',
519
- }, { name: 'thumbs' });
596
+ const styleName = useCounterStyle(
597
+ {
598
+ system: 'cyclic',
599
+ symbols: '"👍"',
600
+ suffix: '" "',
601
+ },
602
+ { name: 'thumbs' },
603
+ );
520
604
 
521
605
  return (
522
606
  <ol style={{ listStyleType: styleName }}>
@@ -536,6 +620,46 @@ function useCounterStyle(
536
620
  ): string;
537
621
  ```
538
622
 
623
+ ### useFunction
624
+
625
+ Register a CSS `@function` (custom function). Permanent — no cleanup on unmount. Deduplicates by function name. The function name accepts `$$name` (matching the call site `$$name(...)`), `$name`, or `--name`.
626
+
627
+ ```tsx
628
+ import { tasty, useFunction } from '@tenphi/tasty';
629
+
630
+ const Box = tasty({ styles: { margin: '$$negative(10px) top' } });
631
+
632
+ function Layout() {
633
+ useFunction('$$negative', { args: ['$value'], result: '(-1 * $value)' });
634
+ return <Box />;
635
+ }
636
+ ```
637
+
638
+ Call the function through the Tasty DSL rather than a raw `style` prop. An inline `style` value reaches the browser unparsed, so the `$$name(...)` sugar is never expanded — and under `configure({ polyfills: { functions: true } })` it silently does nothing, because the polyfill rewrites calls at parse time.
639
+
640
+ Inside a `tasty()` component you call functions with the same `$$name(...)` sugar:
641
+
642
+ ```tsx
643
+ const Box = tasty({
644
+ styles: {
645
+ '@function': { $$negative: { args: ['$value'], result: '(-1 * $value)' } },
646
+ margin: '$$negative(10px) top',
647
+ },
648
+ });
649
+ ```
650
+
651
+ Signature:
652
+
653
+ ```ts
654
+ function useFunction(
655
+ name: string,
656
+ definition: FunctionDefinition,
657
+ options?: { root?: Document | ShadowRoot },
658
+ ): void;
659
+ ```
660
+
661
+ See the [Functions section of the DSL reference](dsl.md#functions-function) for the full descriptor shape, token conventions, and value-sugar support. `@function` is an experimental CSS feature — unsupported browsers safely ignore the native rule, or enable the [`polyfills.functions`](configuration.md#polyfills) inline polyfill for full cross-browser support.
662
+
539
663
  ### Troubleshooting
540
664
 
541
665
  - Styles are not updating: make sure `configure()` runs before first render, and verify the generated class name or global rule with [Debug Utilities](debug.md).
package/docs/ssr.md CHANGED
@@ -18,18 +18,18 @@ The Astro integration (`@tenphi/tasty/ssr/astro`) has no additional dependencies
18
18
 
19
19
  ## How It Works
20
20
 
21
- `tasty()` components are hook-free and use `computeStyles()` internally — a synchronous, framework-agnostic function. On the server, `computeStyles()` discovers a `ServerStyleCollector` via a registered getter (module-level for Next.js, `globalThis` for Astro/generic frameworks using `AsyncLocalStorage`) and collects CSS into it instead of trying to access the DOM. On the client, CSS is injected synchronously into the DOM during render; the injector's content-based cache makes this idempotent. The collector accumulates all styles, serializes them as `<style>` tags and a cache state script in the HTML. On the client, `hydrateTastyCache()` pre-populates the injector cache so that `computeStyles()` skips the rendering pipeline entirely during hydration.
21
+ `tasty()` components are hook-free and use `computeStyles()` internally — a synchronous, framework-agnostic function. On the server, `computeStyles()` discovers a `ServerStyleCollector` via a registered getter (module-level for Next.js, `globalThis` for Astro/generic frameworks using `AsyncLocalStorage`) and collects CSS into it instead of trying to access the DOM. On the client, CSS is injected synchronously into the DOM during render; the injector's content-based cache makes this idempotent. The collector accumulates all styles and serializes them as `<style>` tags plus a class-list script in the HTML. On the client, `hydrateTastyClasses()` pre-populates the injector's rules map with the rendered class names so that `computeStyles()` skips the rendering pipeline entirely during hydration.
22
22
 
23
23
  ```
24
24
  Server Client
25
25
  ────── ──────
26
- tasty() renders hydrateTastyCache() pre-populates cache
27
- └─ computeStyles() └─ cacheKey → className map ready
26
+ tasty() renders hydrateTastyClasses() reads window.__TASTY__
27
+ └─ computeStyles() └─ marks rendered class names as already-in-DOM
28
28
  └─ collector.collect()
29
29
  tasty() renders
30
30
  After render: └─ computeStyles()
31
- <style data-tasty-ssr> └─ cache hit → skip pipeline
32
- <script data-tasty-cache> └─ no CSS re-injection
31
+ <style data-tasty-ssr> └─ class name known → skip pipeline
32
+ <script> (pushes to __TASTY__) └─ no CSS re-injection
33
33
  ```
34
34
 
35
35
  ---
@@ -85,8 +85,8 @@ That's it. All `tasty()` components inside the tree automatically get SSR suppor
85
85
  - `TastyRegistry` is a `'use client'` component, but Next.js still server-renders it on initial page load. The `'use client'` boundary is required solely to access `useServerInsertedHTML` — **not** because `tasty()` components need the client.
86
86
  - During SSR, `TastyRegistry` creates a `ServerStyleCollector` and registers it via a module-level getter (not `globalThis` — this avoids leaking between Next.js's separate RSC and SSR module graphs). It also wraps children in a React context provider so that hooks inside the SSR tree can discover the collector. All style functions — `tasty()` components, `computeStyles()`, `useStyles()`, `useGlobalStyles()`, `useRawCSS()`, `useKeyframes()`, `useProperty()`, `useFontFace()`, and `useCounterStyle()` — discover the collector through the module-level getter or context provider.
87
87
  - `TastyRegistry` uses `useServerInsertedHTML` to flush collected CSS into the HTML stream as `<style data-tasty-ssr>` tags. This is fully streaming-compatible — styles are injected alongside each Suspense boundary as it resolves.
88
- - A companion inline `<script>` tag merges the `cacheKey → className` mapping into `window.__TASTY_SSR_CACHE__` for each flush. This streaming-friendly approach accumulates cache entries incrementally as Suspense boundaries resolve.
89
- - When the `@tenphi/tasty/ssr/next` module loads on the client, `hydrateTastyCache()` runs automatically from `window.__TASTY_SSR_CACHE__` and pre-populates the injector cache. During hydration, `computeStyles()` hits the cache and skips the entire pipeline.
88
+ - A companion inline `<script>` tag pushes the rendered class names into `window.__TASTY__` for each flush. This streaming-friendly approach accumulates the class list incrementally as Suspense boundaries resolve.
89
+ - When the `@tenphi/tasty/ssr/next` module loads on the client, `hydrateTastyClasses()` runs automatically from `window.__TASTY__` and pre-populates the injector's rules map. During hydration, `computeStyles()` sees the class name is already registered and skips the entire pipeline.
90
90
 
91
91
  ### Using Tasty in Server Components
92
92
 
@@ -188,7 +188,7 @@ This gives you:
188
188
 
189
189
  - A `ServerStyleCollector` per request via `AsyncLocalStorage`, deduplicating CSS across all React trees on the page
190
190
  - A single consolidated `<style data-tasty-ssr>` injected into `</head>`
191
- - A `<script data-tasty-cache>` tag with the `cacheKey -> className` map for client hydration
191
+ - A `<script>` tag pushing the rendered class names into `window.__TASTY__` for client hydration
192
192
  - Auto-injected client hydration script (via `injectScript('before-hydration')`) so islands skip the style pipeline during hydration -- no need to import anything manually in each island component
193
193
 
194
194
  All style functions (`useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useProperty`, `useFontFace`, `useCounterStyle`) work on the server.
@@ -223,7 +223,7 @@ export default defineConfig({
223
223
  });
224
224
  ```
225
225
 
226
- This gives the same middleware deduplication and hook support, but ships zero client-side JavaScript. No `<script data-tasty-cache>` is emitted.
226
+ This gives the same middleware deduplication and hook support, but ships zero client-side JavaScript. No class-list `<script>` is emitted.
227
227
 
228
228
  ### Manual middleware (advanced)
229
229
 
@@ -258,7 +258,7 @@ export const onRequest = tastyMiddleware({ transferCache: false });
258
258
  Astro's `@astrojs/react` renderer calls `renderToString()` for each React component without wrapping the tree in a provider. The middleware creates a `ServerStyleCollector` and binds it via `AsyncLocalStorage`. All `computeStyles()` calls within the request discover this collector automatically.
259
259
 
260
260
  - **Static components** (no `client:*`): Styles are collected during `renderToString` and injected into `</head>` as a single `<style>` tag. No JavaScript is shipped.
261
- - **Islands** (`client:load`, `client:visible`, etc.): Styles are collected during SSR the same way. On the client, the hydration script (auto-injected by `tastyIntegration()` or manually via `@tenphi/tasty/ssr/astro-client`) reads the cache state from `<script data-tasty-cache>` and pre-populates the injector. The island's `computeStyles()` calls hit the cache during hydration.
261
+ - **Islands** (`client:load`, `client:visible`, etc.): Styles are collected during SSR the same way. On the client, the hydration script (auto-injected by `tastyIntegration()` or manually via `@tenphi/tasty/ssr/astro-client`) reads the class list from `window.__TASTY__` and pre-populates the injector's rules map. The island's `computeStyles()` calls see the class names as already registered and skip the pipeline during hydration.
262
262
  - The middleware reads the full response body, then injects the collected CSS into `</head>` before sending the final HTML.
263
263
 
264
264
  ### CSP nonce
@@ -274,31 +274,30 @@ Any React-based framework can integrate using `runWithCollector`, which binds a
274
274
  ```tsx
275
275
  import {
276
276
  ServerStyleCollector,
277
+ createServerStyleCollector,
277
278
  runWithCollector,
278
- hydrateTastyCache,
279
+ hydrateTastyClasses,
279
280
  } from '@tenphi/tasty/ssr';
280
281
  import { renderToString } from 'react-dom/server';
281
282
  import { hydrateRoot } from 'react-dom/client';
282
283
 
283
284
  // ── Server ──────────────────────────────────────────────
284
285
 
285
- const collector = new ServerStyleCollector();
286
+ const collector = createServerStyleCollector();
286
287
 
287
288
  const html = await runWithCollector(collector, () =>
288
289
  renderToString(<App />)
289
290
  );
290
291
 
291
292
  const css = collector.getCSS();
292
- const cacheState = collector.getCacheState();
293
+ const classNames = collector.getRenderedClassNames();
293
294
 
294
295
  // Embed in your HTML template:
295
296
  const fullHtml = `
296
297
  <html>
297
298
  <head>
298
299
  <style data-tasty-ssr>${css}</style>
299
- <script data-tasty-cache type="application/json">
300
- ${JSON.stringify(cacheState)}
301
- </script>
300
+ <script>(window.__TASTY__=window.__TASTY__||[]).push(${JSON.stringify(classNames)})</script>
302
301
  </head>
303
302
  <body>
304
303
  <div id="root">${html}</div>
@@ -309,7 +308,7 @@ const fullHtml = `
309
308
  // ── Client ──────────────────────────────────────────────
310
309
 
311
310
  // Before hydration:
312
- hydrateTastyCache(); // reads from <script data-tasty-cache>
311
+ hydrateTastyClasses(); // reads from window.__TASTY__
313
312
 
314
313
  hydrateRoot(document.getElementById('root'), <App />);
315
314
  ```
@@ -319,7 +318,7 @@ hydrateRoot(document.getElementById('root'), <App />);
319
318
  For streaming with `renderToPipeableStream`, use `flushCSS()` instead of `getCSS()`:
320
319
 
321
320
  ```tsx
322
- const collector = new ServerStyleCollector();
321
+ const collector = createServerStyleCollector();
323
322
 
324
323
  const stream = await runWithCollector(collector, () =>
325
324
  renderToPipeableStream(<App />, {
@@ -330,12 +329,14 @@ const stream = await runWithCollector(collector, () =>
330
329
  stream.pipe(res);
331
330
  },
332
331
  onAllReady() {
333
- // Flush any remaining styles + cache state
332
+ // Flush any remaining styles + class list
334
333
  const css = collector.flushCSS();
335
334
  if (css) res.write(`<style data-tasty-ssr>${css}</style>`);
336
335
 
337
- const state = collector.getCacheState();
338
- res.write(`<script data-tasty-cache type="application/json">${JSON.stringify(state)}</script>`);
336
+ const classNames = collector.getRenderedClassNames();
337
+ res.write(
338
+ `<script>(window.__TASTY__=window.__TASTY__||[]).push(${JSON.stringify(classNames)})</script>`,
339
+ );
339
340
  },
340
341
  })
341
342
  );
@@ -349,31 +350,34 @@ const stream = await runWithCollector(collector, () =>
349
350
 
350
351
  | Import path | Description |
351
352
  |---|---|
352
- | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `runWithCollector`, `hydrateTastyCache` |
353
+ | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `createServerStyleCollector`, `runWithCollector`, `hydrateTastyClasses` |
353
354
  | `@tenphi/tasty/ssr/next` | Next.js App Router: `TastyRegistry` component |
354
355
  | `@tenphi/tasty/ssr/astro` | Astro: `tastyIntegration`, `tastyMiddleware` |
355
356
  | `@tenphi/tasty/ssr/astro-client` | Astro: client-side cache hydration (auto-injected by integration, or import manually) |
357
+ | `@tenphi/tasty/ssr/astro-middleware`<br>`@tenphi/tasty/ssr/astro-middleware-static` | Astro: the middleware entrypoints `tastyIntegration()` registers via `addMiddleware()`. Exported so Astro can resolve them by specifier; you should not import them. For manual setups use `tastyMiddleware()`. |
356
358
 
357
359
  ### `ServerStyleCollector`
358
360
 
359
361
  Server-safe style collector. One instance per request.
360
362
 
363
+ Constructor: `new ServerStyleCollector(namePrefix?)`, or use the `createServerStyleCollector(namePrefix?)` factory. The optional `namePrefix` overrides the value from `configure({ namePrefix })`; in normal usage you pass nothing and let the global config drive it. See [Configuration: Name prefix](configuration.md#name-prefix).
364
+
361
365
  | Method | Description |
362
366
  |---|---|
363
- | `allocateClassName(cacheKey)` | Allocate a sequential class name (`t0`, `t1`, ...) for a cache key. Returns `{ className, isNewAllocation }`. |
367
+ | `allocateClassName(cacheKey)` | Allocate a deterministic, content-hashed class name for a cache key (e.g. `t1a2b3` with the default prefix). The same `cacheKey` always produces the same class name on server and client when both share the same `namePrefix`. Returns `{ className, isNewAllocation }`. |
364
368
  | `collectChunk(cacheKey, className, rules)` | Record CSS rules for a chunk. Deduplicated by `cacheKey`. |
365
369
  | `collectKeyframes(name, css)` | Record a `@keyframes` rule. Deduplicated by name. |
366
- | `allocateKeyframeName(providedName?)` | Allocate a keyframe name. Returns `providedName` if given, otherwise generates one (`k0`, `k1`, ...). |
370
+ | `allocateKeyframeName(providedName?)` | Allocate a keyframe name. Returns `providedName` if given, otherwise generates one using `${namePrefix}k${counter}` (e.g. `tk0`, `tk1`, ...). |
367
371
  | `collectProperty(name, css)` | Record a `@property` rule. Deduplicated by name. |
368
372
  | `collectFontFace(key, css)` | Record a `@font-face` rule. Deduplicated by content hash. |
369
373
  | `collectCounterStyle(name, css)` | Record a `@counter-style` rule. Deduplicated by name. |
370
- | `allocateCounterStyleName(providedName?)` | Allocate a counter-style name. Returns `providedName` if given, otherwise generates one (`cs0`, `cs1`, ...). |
374
+ | `allocateCounterStyleName(providedName?)` | Allocate a counter-style name. Returns `providedName` if given, otherwise generates one using `${namePrefix}c${counter}` (e.g. `tc0`, `tc1`, ...). |
371
375
  | `collectGlobalStyles(key, css)` | Record global styles (from `useGlobalStyles`). Deduplicated by key. |
372
376
  | `collectRawCSS(key, css)` | Record raw CSS text (from `useRawCSS`). Deduplicated by key. |
373
377
  | `collectInternals()` | Collect internal `@property` rules, `:root` token defaults, `@font-face`, and `@counter-style` rules from the global config. Called automatically on first chunk collection; idempotent. |
374
378
  | `getCSS()` | Get all collected CSS as a single string. For non-streaming SSR. |
375
379
  | `flushCSS()` | Get only CSS collected since the last flush. For streaming SSR. |
376
- | `getCacheState()` | Serialize `{ entries: Record<cacheKey, className>, classCounter }` for client hydration. |
380
+ | `getRenderedClassNames()` | Get the list of class names rendered so far. Serialized to `window.__TASTY__` for client hydration via `hydrateTastyClasses()`. |
377
381
 
378
382
  ### `TastyRegistry`
379
383
 
@@ -400,9 +404,9 @@ Astro middleware factory. Use for manual middleware composition.
400
404
  |---|---|---|---|
401
405
  | `transferCache` | `boolean` | `true` | Embed cache state script for island hydration |
402
406
 
403
- ### `hydrateTastyCache(state?)`
407
+ ### `hydrateTastyClasses(classes?)`
404
408
 
405
- Pre-populate the client injector cache. When called without arguments, reads from `window.__TASTY_SSR_CACHE__` (streaming) or `<script data-tasty-cache>` (non-streaming).
409
+ Pre-populate the client injector's rules map with class names rendered on the server, marking them as already present in the DOM so `computeStyles()` skips re-injection during hydration. When called without arguments, reads the class list from `window.__TASTY__` (populated by the streaming `<script>` tags emitted during SSR).
406
410
 
407
411
  ### `runWithCollector(collector, fn)`
408
412
 
@@ -418,23 +422,29 @@ The `TastyRegistry` or `tastyIntegration` is missing. Ensure your layout wraps t
418
422
 
419
423
  ### Hydration mismatch warnings
420
424
 
421
- Class names are deterministic for the same render order. If you see mismatches, ensure `hydrateTastyCache()` runs before React hydration. For Next.js, this is automatic. For Astro with `tastyIntegration()`, this is also automatic. For manual Astro middleware setups, import `@tenphi/tasty/ssr/astro-client` in your island components. For custom setups, call `hydrateTastyCache()` before `hydrateRoot()`.
425
+ Class names are deterministic for the same render order. If you see mismatches, ensure `hydrateTastyClasses()` runs before React hydration. For Next.js, this is automatic. For Astro with `tastyIntegration()`, this is also automatic. For manual Astro middleware setups, import `@tenphi/tasty/ssr/astro-client` in your island components. For custom setups, call `hydrateTastyClasses()` before `hydrateRoot()`.
426
+
427
+ Class names are also derived from the *resolved* styles, so the server and the client must configure Tasty identically. Anything that changes what a component's styles resolve to will produce a mismatch if it is registered on only one side — `namePrefix`, `recipes`, `handlers`, and the `propHandlers` / `baseStyleProps` extension points described in [Plugins](plugins.md). Call the same `configure()` on both; global CSS is deduplicated automatically, so no `typeof window` guard is needed.
422
428
 
423
429
  ### Styles duplicated after hydration
424
430
 
425
431
  **Global CSS** (`:root` tokens, `@property`, `globalStyles`, `@font-face`, `@counter-style`) configured via `configure()` is automatically deduplicated. When Tasty detects `<style data-tasty-ssr>` in the document, it skips client-side injection of globals that were already rendered by the SSR collector. This means `configure()` can be called with the full config on both server and client — no `typeof window === 'undefined'` guard is needed.
426
432
 
427
- **Component CSS**: SSR `<style data-tasty-ssr>` tags remain in the DOM. The client injector creates separate `<style>` elements for any new styles. SSR styles are never modified or removed by the client. If this is a concern for very large apps, call `cleanupSSRStyles()` after hydration:
433
+ **Component CSS**: SSR `<style data-tasty-ssr>` tags remain in the DOM. The client injector creates separate `<style>` elements for any new styles. SSR styles are never modified or removed by the client. If this is a concern for very large apps, you can remove the SSR style tags and hydration scripts manually after hydration:
428
434
 
429
435
  ```tsx
430
- import { hydrateTastyCache } from '@tenphi/tasty/ssr';
436
+ import { hydrateTastyClasses } from '@tenphi/tasty/ssr';
431
437
 
432
- hydrateTastyCache();
438
+ hydrateTastyClasses();
433
439
  hydrateRoot(root, <App />);
434
440
 
435
- // Optional: remove SSR style tags after hydration
436
- document.querySelectorAll('style[data-tasty-ssr]').forEach(el => el.remove());
437
- document.querySelectorAll('script[data-tasty-cache]').forEach(el => el.remove());
441
+ // Optional: remove SSR style tags and class-list scripts after hydration
442
+ document.querySelectorAll('style[data-tasty-ssr]').forEach((el) => el.remove());
443
+ document
444
+ .querySelectorAll('script')
445
+ .forEach((el) => {
446
+ if (el.textContent?.includes('__TASTY__')) el.remove();
447
+ });
438
448
  ```
439
449
 
440
450
  ### `AsyncLocalStorage` not available