@tenphi/tasty 0.0.0-snapshot.a85ade8 → 0.0.0-snapshot.a8a2a5d

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 (137) hide show
  1. package/README.md +418 -381
  2. package/dist/babel-types-BOABQvEI.d.ts +16 -0
  3. package/dist/chunks/async-storage-CzSKAyrI.js +36 -0
  4. package/dist/chunks/async-storage-CzSKAyrI.js.map +1 -0
  5. package/dist/chunks/build-config-DQkT3Wru.js +59 -0
  6. package/dist/chunks/build-config-DQkT3Wru.js.map +1 -0
  7. package/dist/{collector-C6TtL8HJ.js → chunks/collector-Df9zcabl.js} +11 -129
  8. package/dist/chunks/collector-Df9zcabl.js.map +1 -0
  9. package/dist/chunks/config-engine-C7OUmM1J.js +269 -0
  10. package/dist/chunks/config-engine-C7OUmM1J.js.map +1 -0
  11. package/dist/chunks/config-file-BX3F_61U.js +24 -0
  12. package/dist/chunks/config-file-BX3F_61U.js.map +1 -0
  13. package/dist/chunks/css-definitions-BkdTqT7G.js +896 -0
  14. package/dist/chunks/css-definitions-BkdTqT7G.js.map +1 -0
  15. package/dist/chunks/css-resources-C0zT36nQ.js +141 -0
  16. package/dist/chunks/css-resources-C0zT36nQ.js.map +1 -0
  17. package/dist/chunks/debug-CwGMB2RI.js +501 -0
  18. package/dist/chunks/debug-CwGMB2RI.js.map +1 -0
  19. package/dist/chunks/dsl-BAwiOznp.js +1442 -0
  20. package/dist/chunks/dsl-BAwiOznp.js.map +1 -0
  21. package/dist/chunks/hydration-DEmoq1sQ.js +39 -0
  22. package/dist/chunks/hydration-DEmoq1sQ.js.map +1 -0
  23. package/dist/chunks/react-runtime-B8YqpFx7.js +678 -0
  24. package/dist/chunks/react-runtime-B8YqpFx7.js.map +1 -0
  25. package/dist/chunks/runtime-engine-CHNH2nGy.js +2418 -0
  26. package/dist/chunks/runtime-engine-CHNH2nGy.js.map +1 -0
  27. package/dist/chunks/runtime-state-BxLKsQzs.js +150 -0
  28. package/dist/chunks/runtime-state-BxLKsQzs.js.map +1 -0
  29. package/dist/{merge-styles-DuoZEsm9.js → chunks/shared-utils-CYgOs2mp.js} +58 -57
  30. package/dist/chunks/shared-utils-CYgOs2mp.js.map +1 -0
  31. package/dist/chunks/style-engine-DkKH-TqL.js +5573 -0
  32. package/dist/chunks/style-engine-DkKH-TqL.js.map +1 -0
  33. package/dist/{css-writer-Bgowobbx.js → chunks/zero-engine-C-0ar_PT.js} +67 -149
  34. package/dist/chunks/zero-engine-C-0ar_PT.js.map +1 -0
  35. package/dist/{collector-BTVXj2hS.d.ts → collector-BN6hCWIx.d.ts} +3 -6
  36. package/dist/{config-LfIDmVHx.d.ts → config-Chmu-PnP.d.ts} +49 -63
  37. package/dist/core/index.d.ts +5 -5
  38. package/dist/core/index.js +9 -6
  39. package/dist/hydrate-CTh8SGd9.d.ts +20 -0
  40. package/dist/{index-Bm9ltvdH.d.ts → index-szujmf6W.d.ts} +263 -348
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +11 -922
  43. package/dist/merge-styles-Cx25bpax.d.ts +4 -0
  44. package/dist/ssr/astro-client.d.ts +1 -1
  45. package/dist/ssr/astro-client.js +2 -16
  46. package/dist/ssr/astro-client.js.map +1 -1
  47. package/dist/ssr/astro-middleware-extract-static.d.ts +1 -4
  48. package/dist/ssr/astro-middleware-extract-static.js +1 -2
  49. package/dist/ssr/astro-middleware-extract.d.ts +1 -4
  50. package/dist/ssr/astro-middleware-extract.js +1 -2
  51. package/dist/ssr/astro-middleware-static.d.ts +1 -4
  52. package/dist/ssr/astro-middleware-static.js +2 -14
  53. package/dist/ssr/astro-middleware-static.js.map +1 -1
  54. package/dist/ssr/astro-middleware.d.ts +1 -4
  55. package/dist/ssr/astro-middleware.js +2 -15
  56. package/dist/ssr/astro-middleware.js.map +1 -1
  57. package/dist/ssr/astro.d.ts +17 -19
  58. package/dist/ssr/astro.js +218 -1
  59. package/dist/ssr/astro.js.map +1 -0
  60. package/dist/ssr/client.d.ts +2 -0
  61. package/dist/ssr/client.js +1 -0
  62. package/dist/ssr/index.d.ts +5 -27
  63. package/dist/ssr/index.js +6 -7
  64. package/dist/ssr/index.js.map +1 -1
  65. package/dist/ssr/next-config.d.ts +63 -0
  66. package/dist/ssr/next-config.js +122 -0
  67. package/dist/ssr/next-config.js.map +1 -0
  68. package/dist/ssr/next.d.ts +9 -10
  69. package/dist/ssr/next.js +30 -45
  70. package/dist/ssr/next.js.map +1 -1
  71. package/dist/static/index.d.ts +8 -13
  72. package/dist/static/index.js +6 -26
  73. package/dist/static/index.js.map +1 -1
  74. package/dist/static/inject.d.ts +1 -4
  75. package/dist/static/inject.js +1 -2
  76. package/dist/{index-BmogEzTo.d.ts → types-DbMN-Yyn.d.ts} +1013 -1043
  77. package/dist/zero/babel.d.ts +71 -2
  78. package/dist/zero/babel.js +84 -150
  79. package/dist/zero/babel.js.map +1 -1
  80. package/dist/zero/index.d.ts +61 -12
  81. package/dist/zero/index.js +24 -2
  82. package/dist/zero/index.js.map +1 -0
  83. package/dist/zero/next.d.ts +5 -7
  84. package/dist/zero/next.js +4 -40
  85. package/dist/zero/next.js.map +1 -1
  86. package/docs/README.md +4 -1
  87. package/docs/adoption.md +25 -17
  88. package/docs/ai-agents.md +69 -34
  89. package/docs/comparison.md +9 -8
  90. package/docs/configuration.md +204 -70
  91. package/docs/debug.md +18 -7
  92. package/docs/design-system.md +129 -15
  93. package/docs/dsl.md +327 -117
  94. package/docs/getting-started.md +81 -22
  95. package/docs/injector.md +41 -40
  96. package/docs/llms.txt +31 -0
  97. package/docs/methodology.md +48 -23
  98. package/docs/migration-v3.md +3 -3
  99. package/docs/pipeline.md +55 -28
  100. package/docs/plugins.md +22 -42
  101. package/docs/react-api.md +76 -11
  102. package/docs/runtime-benchmarks.md +257 -47
  103. package/docs/ssr.md +226 -80
  104. package/docs/styles.md +169 -33
  105. package/docs/tasty-static.md +176 -58
  106. package/harness/dev.harnesspm/rules/usage.md +12 -0
  107. package/harness/dev.harnesspm/scripts/render.mjs +320 -0
  108. package/harness/dev.harnesspm/scripts/styles.mjs +299 -0
  109. package/harness/plugin.json +20 -0
  110. package/package.json +116 -48
  111. package/tasty.config.ts +1 -0
  112. package/dist/astro-ib7E7V4Y.js +0 -307
  113. package/dist/astro-ib7E7V4Y.js.map +0 -1
  114. package/dist/async-storage-DKK-wTD4.js +0 -44
  115. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  116. package/dist/babel-DWCsafYw.d.ts +0 -83
  117. package/dist/collector-C6TtL8HJ.js.map +0 -1
  118. package/dist/config-B3gPdCqd.js +0 -12421
  119. package/dist/config-B3gPdCqd.js.map +0 -1
  120. package/dist/context-CA8YKeMn.js +0 -24
  121. package/dist/context-CA8YKeMn.js.map +0 -1
  122. package/dist/core-Bq7w2kti.js +0 -1686
  123. package/dist/core-Bq7w2kti.js.map +0 -1
  124. package/dist/css-writer-Bgowobbx.js.map +0 -1
  125. package/dist/format-global-rules-DklyaXv-.js +0 -22
  126. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  127. package/dist/format-rules-rCZ37rqY.js +0 -130
  128. package/dist/format-rules-rCZ37rqY.js.map +0 -1
  129. package/dist/hydrate-CNOmZprz.js +0 -37
  130. package/dist/hydrate-CNOmZprz.js.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/keyframes-DE-OE76F.js +0 -535
  133. package/dist/keyframes-DE-OE76F.js.map +0 -1
  134. package/dist/merge-styles-BcLl1u_d.d.ts +0 -7
  135. package/dist/merge-styles-DuoZEsm9.js.map +0 -1
  136. package/dist/resolve-recipes-H9NqOQuP.js +0 -144
  137. package/dist/resolve-recipes-H9NqOQuP.js.map +0 -1
package/docs/ssr.md CHANGED
@@ -15,10 +15,10 @@ Zero-runtime delivery is an outcome, not an alias for `tastyStatic()`. When `tas
15
15
  | Dependency | Version | Required for |
16
16
  | ---------- | ------- | ----------------------------------------------------------------------------------------------- |
17
17
  | `react` | >= 18 | All SSR entry points (matches the current peer dependency of `@tenphi/tasty`) |
18
- | `next` | >= 13 | Next.js integration (`@tenphi/tasty/ssr/next`) — App Router with `useServerInsertedHTML` |
18
+ | `next` | >= 14 | Next.js integration (`@tenphi/tasty/ssr/next`) — App Router with `useServerInsertedHTML` |
19
19
  | Node.js | >= 20 | Generic / streaming SSR (`@tenphi/tasty/ssr`) — uses `node:async_hooks` for `AsyncLocalStorage` |
20
20
 
21
- The Astro integration (`@tenphi/tasty/ssr/astro`) has no additional dependencies beyond `react`.
21
+ The Astro integration (`@tenphi/tasty/ssr/astro`) needs `@astrojs/react`. Like `@tenphi/tasty/ssr`, it imports `node:async_hooks`, so the server runtime must provide it. `css: { mode: 'extract' }` requires Astro 5 or newer.
22
22
 
23
23
  ---
24
24
 
@@ -86,23 +86,115 @@ export default function RootLayout({
86
86
 
87
87
  That's it. All `tasty()` components inside the tree automatically get SSR support. No per-component changes needed.
88
88
 
89
+ ### Optional shared globals stylesheet
90
+
91
+ By default, configured global CSS is included in the streamed Tasty style tag
92
+ for every route. `withTastyNext()` can move that stable CSS into one
93
+ content-hashed stylesheet shared by all routes while leaving component and hook
94
+ styles in the normal streaming path.
95
+
96
+ Keep the Tasty config in a side-effect-free module:
97
+
98
+ ```ts
99
+ // app/tasty.config.ts
100
+ import type { TastyConfig } from '@tenphi/tasty';
101
+
102
+ const config: TastyConfig = {
103
+ tokens: { $gap: '8px', '#brand': 'rebeccapurple' },
104
+ globalStyles: { body: { margin: '0', color: '#brand' } },
105
+ fontFaces: {
106
+ Brand: { src: 'url("/fonts/brand.woff2") format("woff2")' },
107
+ },
108
+ };
109
+
110
+ export default config;
111
+ ```
112
+
113
+ Use it from the Next config:
114
+
115
+ ```ts
116
+ // next.config.ts
117
+ import { withTastyNext } from '@tenphi/tasty/ssr/next-config';
118
+ import config from './app/tasty.config';
119
+
120
+ export default withTastyNext({
121
+ config,
122
+ })({
123
+ // your Next.js config
124
+ });
125
+ ```
126
+
127
+ The runtime must receive the same config. Import and configure it before the
128
+ registry renders:
129
+
130
+ ```tsx
131
+ // app/tasty-registry.tsx
132
+ 'use client';
133
+
134
+ import { configure } from '@tenphi/tasty';
135
+ import { TastyRegistry } from '@tenphi/tasty/ssr/next';
136
+ import config from './tasty.config';
137
+
138
+ configure(config);
139
+
140
+ export default function TastyStyleRegistry({
141
+ children,
142
+ }: {
143
+ children: React.ReactNode;
144
+ }) {
145
+ return <TastyRegistry>{children}</TastyRegistry>;
146
+ }
147
+ ```
148
+
149
+ The generated file contains eager configuration artifacts: built-in and custom
150
+ `@property` rules, tokens and presets, `@font-face`, `@counter-style`, native
151
+ CSS `@function` definitions, and `globalStyles`. Route-dependent component
152
+ rules and calls to `useGlobalStyles`, `useRawCSS`, `useKeyframes`,
153
+ `useProperty`, `useFontFace`, `useCounterStyle`, and `useFunction` remain
154
+ route-specific. Configured keyframes referenced by `globalStyles` are included in the file; all
155
+ other configured keyframes stay lazy and stream only when a route references
156
+ them.
157
+
158
+ The default output directory is `public/_tasty`. The wrapper adds the generated
159
+ URL to `TastyRegistry`, respects `basePath`, preserves existing `env` and
160
+ `headers` config, and serves the content-hashed file with an immutable one-year
161
+ cache header on Next server deployments. Static exports keep the content-hashed
162
+ URL and leave cache headers to the hosting provider. Older hashes are not
163
+ deleted automatically, so rolling deployments cannot break pages from the
164
+ previous build; clean the generated directory as part of a clean deployment if
165
+ needed. Page-relative CSS resources such as
166
+ `url(../fonts/brand.woff2)` are rejected because moving them would change their
167
+ meaning; use root-relative, absolute, or data URLs.
168
+
169
+ `withTastyNext()` options:
170
+
171
+ | Option | Type | Default | Description |
172
+ | ------------ | ------------- | ------------------------- | ---------------------------------------------------------------------- |
173
+ | `config` | `TastyConfig` | — | Config object; takes precedence over `configFile` |
174
+ | `configFile` | `string` | — | Project-relative config module path; requires the optional `jiti` peer |
175
+ | `rootDir` | `string` | current directory | Next app root when the build runs from a monorepo root |
176
+ | `outputDir` | `string` | `public/_tasty` | Filesystem output directory |
177
+ | `publicPath` | `string` | inferred from `outputDir` | Root-relative URL; required when output is outside `public` |
178
+ | `enabled` | `boolean` | `true` | Disable generation without changing wrapper composition |
179
+
89
180
  ### How it works
90
181
 
91
182
  - `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.
92
- - 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.
183
+ - 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()`, `useCounterStyle()`, and `useFunction()` — discover the collector through the module-level getter or context provider.
93
184
  - `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.
94
185
  - 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.
95
186
  - 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.
96
187
 
97
188
  ### Using Tasty in Server Components
98
189
 
99
- All Tasty style functions are hook-free and do not require `'use client'`. They can be used directly in React Server Components:
190
+ Every Tasty style function needs no `'use client'`, so it can be used directly in React Server Components:
100
191
 
101
192
  - `tasty()` components — dynamic `styleProps` like `<Grid flow="column">` work normally
102
- - `useStyles()`, `useGlobalStyles()`, `useRawCSS()` — inject styles by class or selector
103
- - `useKeyframes()`, `useProperty()`, `useFontFace()`, `useCounterStyle()` — inject ancillary CSS rules
193
+ - `useStyles()` and its hook-free equivalent `computeStyles()` — a class name for any element
194
+ - `useGlobalStyles()`, `useRawCSS()` — inject styles by selector
195
+ - `useKeyframes()`, `useProperty()`, `useFontFace()`, `useCounterStyle()`, `useFunction()` — inject ancillary CSS rules
104
196
 
105
- During SSR, all functions discover the collector via the same global getter registered by `TastyRegistry` — no React context or client boundary needed. In RSC mode without a collector (e.g., Astro zero-setup), CSS is accumulated in a per-request cache and flushed into an inline `<style>` tag by the next `tasty()` component in the tree. Ensure at least one `tasty()` component is present in every RSC render tree — standalone style functions alone cannot emit their CSS without a `tasty()` component to trigger the flush.
197
+ Next.js renders Server Components in a separate module graph that cannot see the collector `TastyRegistry` registers, so their CSS takes the RSC inline path: it is accumulated in a per-request `React.cache` and emitted as an inline `<style>` tag by the next `tasty()` component in the tree. Standalone style functions, `useStyles()` included, cannot emit CSS on their own, so make sure a `tasty()` component renders after them in every RSC tree. The RSC path does not emit configured globals (tokens, `@property`, `globalStyles`); those come from `TastyRegistry`'s collector or the `withTastyNext()` shared stylesheet. For the same reason, import the module that calls `configure()` from `app/layout.tsx` as well as from the registry module, so the RSC graph sees the same states, recipes, and units.
106
198
 
107
199
  ### Options
108
200
 
@@ -116,13 +208,13 @@ During SSR, all functions discover the collector via the same global getter regi
116
208
  If your app uses Content Security Policy with nonces, configure it before rendering:
117
209
 
118
210
  ```tsx
119
- // app/layout.tsx or a server-side init file
211
+ // app/tasty-registry.tsx: the 'use client' module that renders TastyRegistry
120
212
  import { configure } from '@tenphi/tasty';
121
213
 
122
214
  configure({ nonce: 'your-nonce-value' });
123
215
  ```
124
216
 
125
- The nonce is automatically applied to all `<style>` and `<script>` tags injected by `TastyRegistry`.
217
+ The nonce is automatically applied to all `<style>` and `<script>` tags injected by `TastyRegistry`. Call it in the module that renders `TastyRegistry`; `app/layout.tsx` is a Server Component and configures a separate module instance.
126
218
 
127
219
  ---
128
220
 
@@ -130,13 +222,13 @@ The nonce is automatically applied to all `<style>` and `<script>` tags injected
130
222
 
131
223
  Tasty offers several levels of Astro integration. Choose the one that matches your needs:
132
224
 
133
- | Setup | Config needed | Deduplication | Hooks work | Client JS |
134
- | --------------------------------------------------------- | ------------- | ----------------------------- | ---------------------- | -------------- |
135
- | Zero setup | None | Per render tree | Yes (within each tree) | None |
136
- | `tastyIntegration({ islands: false })` | One line | Cross-tree | Yes | None |
137
- | `tastyIntegration()` | One line | Cross-tree | Yes | Auto-hydration |
138
- | `tastyIntegration({ css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | Auto-hydration |
139
- | `tastyIntegration({ islands: false, css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | None |
225
+ | Setup | Config needed | Deduplication | Hooks work | Client JS |
226
+ | ---------------------------------------------------------------- | ------------- | ----------------------------------- | --------------------------------- | -------------- |
227
+ | Zero setup | None | None (each element inlines its CSS) | No (style functions emit nothing) | None |
228
+ | `tastyIntegration({ islands: false })` | One line | Cross-tree | Yes | None |
229
+ | `tastyIntegration()` | One line | Cross-tree | Yes | Auto-hydration |
230
+ | `tastyIntegration({ css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | Auto-hydration |
231
+ | `tastyIntegration({ islands: false, css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | None |
140
232
 
141
233
  ### Zero setup (static pages)
142
234
 
@@ -149,9 +241,9 @@ import { tasty } from '@tenphi/tasty';
149
241
  const Card = tasty({
150
242
  styles: {
151
243
  padding: '4x',
152
- fill: '#surface',
244
+ fill: '#fff',
153
245
  radius: '1r',
154
- border: true,
246
+ border: '1bw solid #ddd',
155
247
  },
156
248
  });
157
249
 
@@ -171,9 +263,9 @@ import Card from '../components/Card.tsx';
171
263
  </html>
172
264
  ```
173
265
 
174
- **Trade-offs**: Styles are deduplicated within each React render tree, but Astro renders separate component trees independently, so shared CSS (tokens, `@property` rules) may appear more than once. All style functions (`useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useProperty`, `useFontFace`, `useCounterStyle`) work in zero-setup mode — their CSS is accumulated in the RSC cache and flushed by the next `tasty()` component in the tree.
266
+ **Trade-offs**: Astro renders React with the standard `react` build, where `React.cache` does nothing, so there is no per-request style cache. Every `tasty()` element inlines the full CSS for its classes, even when the same component renders twice. Configured globals (`:root` tokens, `@property` defaults, `globalStyles`, `@font-face`) are never emitted, because only the SSR collector emits them, and CSS from `useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useProperty`, `useFontFace`, `useCounterStyle`, and `useFunction` is dropped. Without the [default properties](dsl.md#default-properties), styles that read them resolve to nothing: `border: true` and `outline: true` draw nothing, and `transition` with no duration does not animate. In development, Tasty warns once that it is rendering without a style collector.
175
267
 
176
- Best for quick prototyping, small static sites, or trying Tasty out in Astro.
268
+ Best for trying Tasty out with plain values, as above. Use `tastyIntegration()` for anything that relies on `configure()` or on Tasty's default tokens.
177
269
 
178
270
  ### Astro Integration (recommended)
179
271
 
@@ -210,7 +302,7 @@ import Interactive from '../components/Interactive.tsx';
210
302
 
211
303
  <html>
212
304
  <body>
213
- <Card>Static -- styles in <style data-tasty-ssr></Card>
305
+ <Card>Static -- styles are inlined into the page head</Card>
214
306
  <Interactive client:load>Island -- cache hydrated automatically</Interactive>
215
307
  </body>
216
308
  </html>
@@ -235,8 +327,8 @@ This gives the same middleware deduplication and hook support, but ships zero cl
235
327
 
236
328
  #### Build-wide CSS extraction
237
329
 
238
- Static Astro builds can move repeated Tasty CSS into a content-hashed,
239
- browser-cacheable asset:
330
+ Static Astro builds can move Tasty CSS into content-hashed, browser-cacheable
331
+ shared and page assets:
240
332
 
241
333
  ```ts
242
334
  export default defineConfig({
@@ -257,14 +349,38 @@ output. Extraction requires Astro 5 or newer and only applies to prerendered
257
349
  production pages. Development, preview-time SSR, and on-demand routes continue
258
350
  to receive the normal inline `<style data-tasty-ssr>` output.
259
351
 
260
- Extraction moves the largest common block whose position can be preserved on
261
- every generated page into one stylesheet. Page-only component, global, and raw
262
- CSS stays inline, so unvisited routes do not receive unrelated styles.
263
-
264
- The asset is written under Astro's configured `build.assets` directory (for
265
- example, `/_astro/tasty.a1b2c3.css`). Links include the configured Astro
266
- `base`, so nested routes do not need relative-path handling. The content hash
267
- and output are deterministic for identical builds.
352
+ Extraction writes every artifact emitted by all styled pages to a shared
353
+ stylesheet. Each page's strict set difference is written to a separate page
354
+ stylesheet. The shared link comes first and the page link follows, so shared
355
+ styles form the base cascade and page-only styles can override them. A fully
356
+ shared page omits the empty page stylesheet. If generated pages have no common
357
+ artifacts, each page receives only its page stylesheet.
358
+
359
+ The shared-base/page-override order is the extraction-mode cascade contract.
360
+ It does not preserve an inline artifact order where a page-only rule originally
361
+ appeared before a shared rule. Use shared styles for defaults and page-only
362
+ styles for overrides.
363
+
364
+ Extracted CSS preserves resource URLs verbatim. Relative URLs in an inline
365
+ style resolve from the page, but in an extracted stylesheet they resolve from
366
+ the asset directory. Use absolute URLs or data URLs when extraction is enabled.
367
+ Root-relative URLs such as `url(/fonts/brand.woff2)` are also safe while the
368
+ stylesheet stays on the page's origin. The build fails with a clear error if an
369
+ artifact contains a page-relative or fragment-only URL, including URL strings
370
+ in `image-set()`, `image()`, `src()`, and `@import`.
371
+
372
+ Assets are written under Astro's configured `build.assets` directory (for
373
+ example, `/_astro/tasty.shared.a1b2c3.css` and
374
+ `/_astro/tasty.page.d4e5f6.css`). Links include the configured Astro `base`, so
375
+ nested routes do not need relative-path handling. Content hashes and output are
376
+ deterministic for identical builds. If `build.assetsPrefix` is configured,
377
+ Tasty uses its CSS-specific prefix (or `fallback`) just like Astro-generated
378
+ stylesheets. When that prefix points to a different origin, root-relative
379
+ resources would resolve against the asset origin rather than the page's origin,
380
+ so the build rejects them as well. Tasty compares the prefix with Astro's `site`
381
+ when it is configured; without `site`, an absolute or protocol-relative prefix
382
+ is treated conservatively as cross-origin. Use a fully absolute resource URL in
383
+ that configuration.
268
384
 
269
385
  ### Manual middleware (advanced)
270
386
 
@@ -291,6 +407,8 @@ import '@tenphi/tasty/ssr/astro-client';
291
407
  export const onRequest = tastyMiddleware({ transferCache: false });
292
408
  ```
293
409
 
410
+ Build-wide extraction (`css: { mode: 'extract' }`) is available only through `tastyIntegration()`; `tastyMiddleware()` always inlines CSS.
411
+
294
412
  ### How it works
295
413
 
296
414
  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.
@@ -300,12 +418,13 @@ Astro's `@astrojs/react` renderer calls `renderToString()` for each React compon
300
418
  - The middleware reads the full response body, then injects the collected CSS into `</head>` before sending the final HTML.
301
419
  - In extraction mode, prerendered responses also carry temporary structured
302
420
  artifact metadata. `astro:build:done` uses those collector-provided
303
- boundaries to write the shared asset and rewrite generated HTML, then removes
304
- the metadata. CSS is never split on newlines or parsed heuristically.
421
+ boundaries to write shared and page assets and rewrite generated HTML, then
422
+ removes the metadata. Artifact boundaries are never inferred by splitting or
423
+ reparsing the generated CSS.
305
424
 
306
425
  ### CSP nonce
307
426
 
308
- Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags. In extraction mode, page-local inline style tags and the external stylesheet link retain the nonce.
427
+ Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags. In extraction mode, the external stylesheet links retain the nonce.
309
428
 
310
429
  ---
311
430
 
@@ -314,20 +433,16 @@ Call `configure({ nonce: '...' })` before any rendering happens. The middleware
314
433
  Any React-based framework can integrate using `runWithCollector`, which binds a `ServerStyleCollector` to the current async context via `AsyncLocalStorage`. All style function calls within the render automatically discover the collector.
315
434
 
316
435
  ```tsx
436
+ // ── Server ──────────────────────────────────────────────
317
437
  import {
318
- ServerStyleCollector,
319
438
  createServerStyleCollector,
320
439
  runWithCollector,
321
- hydrateTastyClasses,
322
440
  } from '@tenphi/tasty/ssr';
323
441
  import { renderToString } from 'react-dom/server';
324
- import { hydrateRoot } from 'react-dom/client';
325
-
326
- // ── Server ──────────────────────────────────────────────
327
442
 
328
443
  const collector = createServerStyleCollector();
329
444
 
330
- const html = await runWithCollector(collector, () => renderToString(<App />));
445
+ const html = runWithCollector(collector, () => renderToString(<App />));
331
446
 
332
447
  const css = collector.getCSS();
333
448
  const classNames = collector.getRenderedClassNames();
@@ -344,42 +459,56 @@ const fullHtml = `
344
459
  </body>
345
460
  </html>
346
461
  `;
462
+ ```
347
463
 
464
+ ```tsx
348
465
  // ── Client ──────────────────────────────────────────────
466
+ import { hydrateTastyClasses } from '@tenphi/tasty/ssr/client';
467
+ import { hydrateRoot } from 'react-dom/client';
349
468
 
350
- // Before hydration:
351
- hydrateTastyClasses(); // reads from window.__TASTY__
352
-
469
+ hydrateTastyClasses(); // reads window.__TASTY__
353
470
  hydrateRoot(document.getElementById('root'), <App />);
354
471
  ```
355
472
 
473
+ `@tenphi/tasty/ssr/client` is the browser half: it exports `hydrateTastyClasses()` and has no import side effects. A module shared by the server and the client can import `@tenphi/tasty/ssr` too. It is safe in a browser bundle, where there is no server collector to find, and only `runWithCollector()` throws there.
474
+
356
475
  ### Streaming SSR
357
476
 
358
477
  For streaming with `renderToPipeableStream`, use `flushCSS()` instead of `getCSS()`:
359
478
 
360
479
  ```tsx
480
+ import { PassThrough } from 'node:stream';
481
+ import { renderToPipeableStream } from 'react-dom/server';
482
+
361
483
  const collector = createServerStyleCollector();
362
484
 
363
- const stream = await runWithCollector(collector, () =>
364
- renderToPipeableStream(<App />, {
485
+ // React ends the stream it pipes into, so pipe into a PassThrough and
486
+ // append the remaining styles and the class list after it ends.
487
+ const body = new PassThrough();
488
+ body.pipe(res, { end: false });
489
+ body.on('end', () => {
490
+ // Styles collected after the shell (Suspense boundaries) + class list
491
+ const css = collector.flushCSS();
492
+ if (css) res.write(`<style data-tasty-ssr>${css}</style>`);
493
+
494
+ const classNames = collector.getRenderedClassNames();
495
+ res.end(
496
+ `</div><script>(window.__TASTY__=window.__TASTY__||[]).push(${JSON.stringify(classNames)})</script></body></html>`,
497
+ );
498
+ });
499
+
500
+ runWithCollector(collector, () => {
501
+ const { pipe } = renderToPipeableStream(<App />, {
365
502
  onShellReady() {
366
- // Flush styles collected so far
367
- const css = collector.flushCSS();
368
- res.write(`<style data-tasty-ssr>${css}</style>`);
369
- stream.pipe(res);
370
- },
371
- onAllReady() {
372
- // Flush any remaining styles + class list
503
+ // Styles collected for the shell
373
504
  const css = collector.flushCSS();
374
- if (css) res.write(`<style data-tasty-ssr>${css}</style>`);
375
-
376
- const classNames = collector.getRenderedClassNames();
377
505
  res.write(
378
- `<script>(window.__TASTY__=window.__TASTY__||[]).push(${JSON.stringify(classNames)})</script>`,
506
+ `<!DOCTYPE html><html><head><style data-tasty-ssr>${css}</style></head><body><div id="root">`,
379
507
  );
508
+ pipe(body);
380
509
  },
381
- }),
382
- );
510
+ });
511
+ });
383
512
  ```
384
513
 
385
514
  ---
@@ -388,13 +517,15 @@ const stream = await runWithCollector(collector, () =>
388
517
 
389
518
  ### Entry points
390
519
 
391
- | Import path | Description |
392
- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
393
- | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `createServerStyleCollector`, `runWithCollector`, `hydrateTastyClasses` |
394
- | `@tenphi/tasty/ssr/next` | Next.js App Router: `TastyRegistry` component |
395
- | `@tenphi/tasty/ssr/astro` | Astro: `tastyIntegration`, `tastyMiddleware` |
396
- | `@tenphi/tasty/ssr/astro-client` | Astro: client-side cache hydration (auto-injected by integration, or import manually) |
397
- | `@tenphi/tasty/ssr/astro-middleware`<br>`@tenphi/tasty/ssr/astro-middleware-static`<br>`@tenphi/tasty/ssr/astro-middleware-extract`<br>`@tenphi/tasty/ssr/astro-middleware-extract-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()`. |
520
+ | Import path | Description |
521
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
522
+ | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `createServerStyleCollector`, `runWithCollector`, `getSSRCollector`, `hydrateTastyClasses`; types `ServerStyleArtifact`, `ServerStyleArtifactKind`. Safe to import in a browser bundle; `runWithCollector()` needs the server |
523
+ | `@tenphi/tasty/ssr/client` | Browser-safe client hydration for any framework: `hydrateTastyClasses`, no import side effects |
524
+ | `@tenphi/tasty/ssr/next` | Next.js App Router: `TastyRegistry` component |
525
+ | `@tenphi/tasty/ssr/next-config` | Next.js config wrapper: shared, content-hashed global stylesheet |
526
+ | `@tenphi/tasty/ssr/astro` | Astro: `tastyIntegration`, `tastyMiddleware` |
527
+ | `@tenphi/tasty/ssr/astro-client` | Astro: client-side cache hydration (auto-injected by integration, or import manually) |
528
+ | `@tenphi/tasty/ssr/astro-middleware`<br />`@tenphi/tasty/ssr/astro-middleware-static`<br />`@tenphi/tasty/ssr/astro-middleware-extract`<br />`@tenphi/tasty/ssr/astro-middleware-extract-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()`. |
398
529
 
399
530
  ### `ServerStyleCollector`
400
531
 
@@ -410,31 +541,42 @@ Constructor: `new ServerStyleCollector(namePrefix?)`, or use the `createServerSt
410
541
  | `allocateKeyframeName(providedName?)` | Allocate a keyframe name. Returns `providedName` if given, otherwise generates one using `${namePrefix}k${counter}` (e.g. `tk0`, `tk1`, ...). |
411
542
  | `collectProperty(name, css)` | Record a `@property` rule. Deduplicated by name. |
412
543
  | `collectFontFace(key, css)` | Record a `@font-face` rule. Deduplicated by content hash. |
413
- | `collectCounterStyle(name, css)` | Record a `@counter-style` rule. Deduplicated by name. |
544
+ | `collectCounterStyle(name, css, options?)` | Record a `@counter-style` rule, keyed by name. A different rule under the same name replaces the earlier one (and is re-flushed when streaming); `{ weak: true }`, used for `configure()` definitions, never replaces. |
545
+ | `collectFunction(name, css, options?)` | Record a CSS `@function` rule (from `useFunction` or `@function` styles). Same replace/`weak` semantics as `collectCounterStyle`. |
414
546
  | `allocateCounterStyleName(providedName?)` | Allocate a counter-style name. Returns `providedName` if given, otherwise generates one using `${namePrefix}c${counter}` (e.g. `tc0`, `tc1`, ...). |
415
547
  | `collectGlobalStyles(key, css)` | Record global styles (from `useGlobalStyles`). Deduplicated by key. |
416
548
  | `collectRawCSS(key, css)` | Record raw CSS text (from `useRawCSS`). Deduplicated by key. |
417
- | `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. |
549
+ | `collectInternals()` | Collect eager configured globals: `@property`, `:root` tokens and presets, `@font-face`, `@counter-style`, `@function`, and `globalStyles`. Called automatically on first chunk collection; idempotent. |
418
550
  | `getCSS()` | Get all collected CSS as a single string. For non-streaming SSR. |
419
551
  | `flushCSS()` | Get only CSS collected since the last flush. For streaming SSR. |
420
- | `getRenderedClassNames()` | Get the list of class names rendered so far. Serialized to `window.__TASTY__` for client hydration via `hydrateTastyClasses()`. |
552
+ | `getRenderedClassNames()` | Get the class names allocated since the previous call (the first call returns all so far). Push each batch to `window.__TASTY__` for hydration via `hydrateTastyClasses()`. |
553
+ | `getArtifacts()` | Return the collected CSS as ordered, typed artifacts (`property`, `font-face`, `counter-style`, `function`, `raw`, `global`, `chunk`, `keyframes`). |
421
554
 
422
555
  ### `TastyRegistry`
423
556
 
424
557
  Next.js App Router component. Props:
425
558
 
426
- | Prop | Type | Default | Description |
427
- | --------------- | ----------- | -------- | ------------------------------------------------ |
428
- | `children` | `ReactNode` | required | Application tree |
429
- | `transferCache` | `boolean` | `true` | Embed cache state script for zero-cost hydration |
559
+ | Prop | Type | Default | Description |
560
+ | ------------------ | ----------------- | --------- | ------------------------------------------------------------------------- |
561
+ | `children` | `ReactNode` | required | Application tree |
562
+ | `transferCache` | `boolean` | `true` | Embed cache state script for zero-cost hydration |
563
+ | `sharedStylesheet` | `string \| false` | generated | Override the shared URL, or disable generated shared CSS for the registry |
564
+
565
+ ### `withTastyNext(options)`
566
+
567
+ Next.js configuration wrapper exported from
568
+ `@tenphi/tasty/ssr/next-config`. It generates a shared stylesheet from eager
569
+ Tasty configuration artifacts and wires its URL and immutable cache header
570
+ into the Next config. Route-specific CSS continues through `TastyRegistry`.
430
571
 
431
572
  ### `tastyIntegration(options?)`
432
573
 
433
574
  Astro integration factory. Registers middleware and optionally injects client hydration.
434
575
 
435
- | Option | Type | Default | Description |
436
- | --------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
437
- | `islands` | `boolean` | `true` | When `true`, injects client hydration script and enables `transferCache`. When `false`, no client JS is shipped. |
576
+ | Option | Type | Default | Description |
577
+ | --------- | ---------------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
578
+ | `islands` | `boolean` | `true` | When `true`, injects client hydration script and enables `transferCache`. When `false`, no client JS is shipped. |
579
+ | `css` | `{ mode?: 'inline' \| 'extract' }` | `{ mode: 'inline' }` | `'extract'` writes content-hashed shared and per-page stylesheets for prerendered pages (Astro 5+). See [Build-wide CSS extraction](#build-wide-css-extraction). |
438
580
 
439
581
  ### `tastyMiddleware(options?)`
440
582
 
@@ -446,11 +588,11 @@ Astro middleware factory. Use for manual middleware composition.
446
588
 
447
589
  ### `hydrateTastyClasses(classes?)`
448
590
 
449
- 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).
591
+ Exported from `@tenphi/tasty/ssr/client` and `@tenphi/tasty/ssr`. 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).
450
592
 
451
593
  ### `runWithCollector(collector, fn)`
452
594
 
453
- Run a function with a `ServerStyleCollector` bound to the current async context via `AsyncLocalStorage`. All style function calls within `fn` (and async continuations) — including `computeStyles()`, `useStyles()`, `useGlobalStyles()`, `useRawCSS()`, `useKeyframes()`, `useProperty()`, `useFontFace()`, and `useCounterStyle()` — will find this collector.
595
+ Run a function with a `ServerStyleCollector` bound to the current async context via `AsyncLocalStorage`. All style function calls within `fn` (and async continuations) — including `computeStyles()`, `useStyles()`, `useGlobalStyles()`, `useRawCSS()`, `useKeyframes()`, `useProperty()`, `useFontFace()`, `useCounterStyle()`, and `useFunction()` — will find this collector. Returns `fn`'s return value, synchronously unless `fn` returns a promise. Throws where `AsyncLocalStorage` is unavailable, such as in a browser.
454
596
 
455
597
  ---
456
598
 
@@ -462,7 +604,7 @@ The `TastyRegistry` or `tastyIntegration` is missing. Ensure your layout wraps t
462
604
 
463
605
  ### Hydration mismatch warnings
464
606
 
465
- 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()`.
607
+ Class names are content hashes of the resolved styles, so render order does not affect them. Unnamed `useKeyframes()` and `useCounterStyle()` names are counters (`tk0`, `tc0`) on both server and client; pass `name` if the two sides can call them in a different 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()` from `@tenphi/tasty/ssr/client` before `hydrateRoot()`.
466
608
 
467
609
  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.
468
610
 
@@ -473,7 +615,7 @@ Class names are also derived from the _resolved_ styles, so the server and the c
473
615
  **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:
474
616
 
475
617
  ```tsx
476
- import { hydrateTastyClasses } from '@tenphi/tasty/ssr';
618
+ import { hydrateTastyClasses } from '@tenphi/tasty/ssr/client';
477
619
 
478
620
  hydrateTastyClasses();
479
621
  hydrateRoot(root, <App />);
@@ -487,4 +629,8 @@ document.querySelectorAll('script').forEach((el) => {
487
629
 
488
630
  ### `AsyncLocalStorage` not available
489
631
 
490
- The `@tenphi/tasty/ssr` entry point imports from `node:async_hooks`. This is excluded from client bundles by the build configuration. If you see import errors on the client, ensure your bundler treats `node:async_hooks` as external or use the `@tenphi/tasty/ssr/next` entry point (which does not use ALS).
632
+ `runWithCollector()` throws `runWithCollector() needs AsyncLocalStorage from node:async_hooks` where the runtime has no `AsyncLocalStorage`, such as in a browser bundle. Call it on the server. The rest of `@tenphi/tasty/ssr` is safe to import in a browser bundle; on the client, call `hydrateTastyClasses()` from `@tenphi/tasty/ssr/client`, or use `@tenphi/tasty/ssr/next`, which hydrates automatically.
633
+
634
+ ### "Server rendering without a style collector" warning
635
+
636
+ Tasty rendered on the server with no collector and no React Server Components request scope: Astro without `tastyIntegration()`, a client component server-rendered without `TastyRegistry`, or a custom setup that skips `runWithCollector()`. Each `tasty()` element then inlines all of its CSS, and configured globals (tokens, the default `@property` set, `globalStyles`, `@font-face`) and the CSS of the standalone style functions are not emitted. Add the integration for your framework. The warning is shown once, in development only.