@tenphi/tasty 0.0.0-snapshot.2705ab9 → 0.0.0-snapshot.275370e

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 (296) hide show
  1. package/README.md +26 -20
  2. package/dist/_virtual/_rolldown/runtime.js +1 -2
  3. package/dist/chunks/cacheKey.d.ts +1 -0
  4. package/dist/chunks/cacheKey.js +1 -2
  5. package/dist/chunks/cacheKey.js.map +1 -1
  6. package/dist/chunks/definitions.js +1 -2
  7. package/dist/chunks/definitions.js.map +1 -1
  8. package/dist/chunks/index.d.ts +1 -0
  9. package/dist/chunks/renderChunk.d.ts +1 -0
  10. package/dist/chunks/renderChunk.js +1 -2
  11. package/dist/chunks/renderChunk.js.map +1 -1
  12. package/dist/compute-styles.d.ts +31 -0
  13. package/dist/compute-styles.js +322 -0
  14. package/dist/compute-styles.js.map +1 -0
  15. package/dist/config.d.ts +61 -20
  16. package/dist/config.js +119 -32
  17. package/dist/config.js.map +1 -1
  18. package/dist/core/index.d.ts +6 -6
  19. package/dist/core/index.js +7 -7
  20. package/dist/counter-style/index.js +1 -1
  21. package/dist/counter-style/index.js.map +1 -1
  22. package/dist/debug.js +5 -6
  23. package/dist/debug.js.map +1 -1
  24. package/dist/font-face/index.js +1 -1
  25. package/dist/font-face/index.js.map +1 -1
  26. package/dist/hooks/index.d.ts +7 -0
  27. package/dist/hooks/useCounterStyle.d.ts +3 -17
  28. package/dist/hooks/useCounterStyle.js +56 -38
  29. package/dist/hooks/useCounterStyle.js.map +1 -1
  30. package/dist/hooks/useFontFace.d.ts +3 -1
  31. package/dist/hooks/useFontFace.js +22 -27
  32. package/dist/hooks/useFontFace.js.map +1 -1
  33. package/dist/hooks/useGlobalStyles.d.ts +18 -2
  34. package/dist/hooks/useGlobalStyles.js +52 -43
  35. package/dist/hooks/useGlobalStyles.js.map +1 -1
  36. package/dist/hooks/useKeyframes.d.ts +4 -2
  37. package/dist/hooks/useKeyframes.js +43 -53
  38. package/dist/hooks/useKeyframes.js.map +1 -1
  39. package/dist/hooks/useProperty.d.ts +4 -2
  40. package/dist/hooks/useProperty.js +30 -44
  41. package/dist/hooks/useProperty.js.map +1 -1
  42. package/dist/hooks/useRawCSS.d.ts +13 -44
  43. package/dist/hooks/useRawCSS.js +91 -24
  44. package/dist/hooks/useRawCSS.js.map +1 -1
  45. package/dist/hooks/useStyles.d.ts +3 -8
  46. package/dist/hooks/useStyles.js +7 -214
  47. package/dist/hooks/useStyles.js.map +1 -1
  48. package/dist/index.d.ts +7 -7
  49. package/dist/index.js +8 -8
  50. package/dist/injector/index.d.ts +18 -19
  51. package/dist/injector/index.js +25 -20
  52. package/dist/injector/index.js.map +1 -1
  53. package/dist/injector/injector.d.ts +35 -3
  54. package/dist/injector/injector.js +200 -14
  55. package/dist/injector/injector.js.map +1 -1
  56. package/dist/injector/sheet-manager.d.ts +9 -13
  57. package/dist/injector/sheet-manager.js +34 -69
  58. package/dist/injector/sheet-manager.js.map +1 -1
  59. package/dist/injector/types.d.ts +52 -21
  60. package/dist/keyframes/index.js +1 -1
  61. package/dist/parser/classify.js +1 -2
  62. package/dist/parser/classify.js.map +1 -1
  63. package/dist/parser/const.js +14 -3
  64. package/dist/parser/const.js.map +1 -1
  65. package/dist/parser/lru.js +1 -1
  66. package/dist/parser/lru.js.map +1 -1
  67. package/dist/parser/parser.js +1 -2
  68. package/dist/parser/parser.js.map +1 -1
  69. package/dist/parser/tokenizer.js +1 -1
  70. package/dist/parser/tokenizer.js.map +1 -1
  71. package/dist/parser/types.js +1 -1
  72. package/dist/parser/types.js.map +1 -1
  73. package/dist/pipeline/conditions.js +1 -1
  74. package/dist/pipeline/conditions.js.map +1 -1
  75. package/dist/pipeline/exclusive.js +58 -4
  76. package/dist/pipeline/exclusive.js.map +1 -1
  77. package/dist/pipeline/index.js +4 -5
  78. package/dist/pipeline/index.js.map +1 -1
  79. package/dist/pipeline/materialize.js +57 -4
  80. package/dist/pipeline/materialize.js.map +1 -1
  81. package/dist/pipeline/parseStateKey.js +5 -6
  82. package/dist/pipeline/parseStateKey.js.map +1 -1
  83. package/dist/pipeline/simplify.js +181 -7
  84. package/dist/pipeline/simplify.js.map +1 -1
  85. package/dist/pipeline/warnings.js +1 -1
  86. package/dist/plugins/index.d.ts +2 -0
  87. package/dist/plugins/okhsl-plugin.js +1 -2
  88. package/dist/plugins/okhsl-plugin.js.map +1 -1
  89. package/dist/plugins/types.d.ts +12 -1
  90. package/dist/properties/index.js +2 -3
  91. package/dist/properties/index.js.map +1 -1
  92. package/dist/properties/property-type-resolver.js +1 -2
  93. package/dist/properties/property-type-resolver.js.map +1 -1
  94. package/dist/rsc-cache.js +79 -0
  95. package/dist/rsc-cache.js.map +1 -0
  96. package/dist/ssr/astro-client.d.ts +1 -0
  97. package/dist/ssr/astro-client.js +19 -0
  98. package/dist/ssr/astro-client.js.map +1 -0
  99. package/dist/ssr/astro-middleware.d.ts +15 -0
  100. package/dist/ssr/astro-middleware.js +19 -0
  101. package/dist/ssr/astro-middleware.js.map +1 -0
  102. package/dist/ssr/astro.d.ts +89 -10
  103. package/dist/ssr/astro.js +113 -29
  104. package/dist/ssr/astro.js.map +1 -1
  105. package/dist/ssr/async-storage.js +15 -6
  106. package/dist/ssr/async-storage.js.map +1 -1
  107. package/dist/ssr/collect-auto-properties.js +29 -11
  108. package/dist/ssr/collect-auto-properties.js.map +1 -1
  109. package/dist/ssr/collector.d.ts +9 -13
  110. package/dist/ssr/collector.js +35 -27
  111. package/dist/ssr/collector.js.map +1 -1
  112. package/dist/ssr/context.js +4 -2
  113. package/dist/ssr/context.js.map +1 -1
  114. package/dist/ssr/format-global-rules.js +1 -1
  115. package/dist/ssr/format-keyframes.js +1 -2
  116. package/dist/ssr/format-keyframes.js.map +1 -1
  117. package/dist/ssr/format-property.js +1 -2
  118. package/dist/ssr/format-property.js.map +1 -1
  119. package/dist/ssr/format-rules.js +1 -1
  120. package/dist/ssr/hydrate.d.ts +20 -13
  121. package/dist/ssr/hydrate.js +25 -30
  122. package/dist/ssr/hydrate.js.map +1 -1
  123. package/dist/ssr/index.d.ts +3 -4
  124. package/dist/ssr/index.js +5 -7
  125. package/dist/ssr/index.js.map +1 -1
  126. package/dist/ssr/next.d.ts +6 -5
  127. package/dist/ssr/next.js +14 -10
  128. package/dist/ssr/next.js.map +1 -1
  129. package/dist/ssr/ssr-collector-ref.js +20 -3
  130. package/dist/ssr/ssr-collector-ref.js.map +1 -1
  131. package/dist/states/index.js +1 -2
  132. package/dist/states/index.js.map +1 -1
  133. package/dist/static/index.js +1 -2
  134. package/dist/static/inject.d.ts +5 -0
  135. package/dist/static/inject.js +17 -0
  136. package/dist/static/inject.js.map +1 -0
  137. package/dist/static/tastyStatic.js +1 -2
  138. package/dist/static/tastyStatic.js.map +1 -1
  139. package/dist/static/types.js +1 -1
  140. package/dist/styles/border.d.ts +1 -1
  141. package/dist/styles/border.js +28 -22
  142. package/dist/styles/border.js.map +1 -1
  143. package/dist/styles/color.d.ts +1 -1
  144. package/dist/styles/color.js +2 -3
  145. package/dist/styles/color.js.map +1 -1
  146. package/dist/styles/const.js +17 -0
  147. package/dist/styles/const.js.map +1 -0
  148. package/dist/styles/createStyle.js +4 -5
  149. package/dist/styles/createStyle.js.map +1 -1
  150. package/dist/styles/dimension.js +15 -3
  151. package/dist/styles/dimension.js.map +1 -1
  152. package/dist/styles/directional.js +133 -0
  153. package/dist/styles/directional.js.map +1 -0
  154. package/dist/styles/display.d.ts +3 -10
  155. package/dist/styles/display.js +45 -39
  156. package/dist/styles/display.js.map +1 -1
  157. package/dist/styles/fade.d.ts +1 -1
  158. package/dist/styles/fade.js +9 -5
  159. package/dist/styles/fade.js.map +1 -1
  160. package/dist/styles/fill.d.ts +2 -2
  161. package/dist/styles/fill.js +3 -4
  162. package/dist/styles/fill.js.map +1 -1
  163. package/dist/styles/flow.js +1 -1
  164. package/dist/styles/gap.d.ts +1 -1
  165. package/dist/styles/gap.js +4 -3
  166. package/dist/styles/gap.js.map +1 -1
  167. package/dist/styles/height.d.ts +1 -1
  168. package/dist/styles/height.js +1 -2
  169. package/dist/styles/height.js.map +1 -1
  170. package/dist/styles/index.d.ts +0 -1
  171. package/dist/styles/index.js +3 -4
  172. package/dist/styles/index.js.map +1 -1
  173. package/dist/styles/inset.d.ts +1 -29
  174. package/dist/styles/inset.js +19 -135
  175. package/dist/styles/inset.js.map +1 -1
  176. package/dist/styles/list.d.ts +5 -5
  177. package/dist/styles/list.js +4 -2
  178. package/dist/styles/list.js.map +1 -1
  179. package/dist/styles/margin.d.ts +1 -1
  180. package/dist/styles/margin.js +17 -89
  181. package/dist/styles/margin.js.map +1 -1
  182. package/dist/styles/outline.d.ts +1 -1
  183. package/dist/styles/outline.js +6 -16
  184. package/dist/styles/outline.js.map +1 -1
  185. package/dist/styles/padding.d.ts +1 -1
  186. package/dist/styles/padding.js +17 -89
  187. package/dist/styles/padding.js.map +1 -1
  188. package/dist/styles/placement.d.ts +37 -0
  189. package/dist/styles/placement.js +74 -0
  190. package/dist/styles/placement.js.map +1 -0
  191. package/dist/styles/predefined.d.ts +4 -4
  192. package/dist/styles/predefined.js +8 -9
  193. package/dist/styles/predefined.js.map +1 -1
  194. package/dist/styles/preset.d.ts +1 -1
  195. package/dist/styles/preset.js +7 -7
  196. package/dist/styles/preset.js.map +1 -1
  197. package/dist/styles/radius.d.ts +1 -3
  198. package/dist/styles/radius.js +38 -6
  199. package/dist/styles/radius.js.map +1 -1
  200. package/dist/styles/scrollMargin.d.ts +24 -0
  201. package/dist/styles/scrollMargin.js +32 -0
  202. package/dist/styles/scrollMargin.js.map +1 -0
  203. package/dist/styles/scrollbar.d.ts +1 -1
  204. package/dist/styles/scrollbar.js +8 -5
  205. package/dist/styles/scrollbar.js.map +1 -1
  206. package/dist/styles/shadow.d.ts +1 -1
  207. package/dist/styles/shadow.js +4 -3
  208. package/dist/styles/shadow.js.map +1 -1
  209. package/dist/styles/shared.js +17 -0
  210. package/dist/styles/shared.js.map +1 -0
  211. package/dist/styles/transition.d.ts +1 -1
  212. package/dist/styles/transition.js +5 -4
  213. package/dist/styles/transition.js.map +1 -1
  214. package/dist/styles/types.d.ts +24 -7
  215. package/dist/styles/width.d.ts +1 -1
  216. package/dist/styles/width.js +1 -2
  217. package/dist/styles/width.js.map +1 -1
  218. package/dist/tasty.d.ts +29 -14
  219. package/dist/tasty.js +78 -62
  220. package/dist/tasty.js.map +1 -1
  221. package/dist/utils/cache-wrapper.js +1 -2
  222. package/dist/utils/cache-wrapper.js.map +1 -1
  223. package/dist/utils/case-converter.js +1 -1
  224. package/dist/utils/color-math.js +1 -1
  225. package/dist/utils/color-math.js.map +1 -1
  226. package/dist/utils/color-space.js +1 -2
  227. package/dist/utils/color-space.js.map +1 -1
  228. package/dist/utils/colors.js +1 -2
  229. package/dist/utils/colors.js.map +1 -1
  230. package/dist/utils/deps-equal.js +15 -0
  231. package/dist/utils/deps-equal.js.map +1 -0
  232. package/dist/utils/dotize.js +1 -1
  233. package/dist/utils/dotize.js.map +1 -1
  234. package/dist/utils/filter-base-props.d.ts +1 -1
  235. package/dist/utils/filter-base-props.js +1 -1
  236. package/dist/utils/filter-base-props.js.map +1 -1
  237. package/dist/utils/get-display-name.js +1 -1
  238. package/dist/utils/has-keys.js +1 -1
  239. package/dist/utils/hash.js +14 -0
  240. package/dist/utils/hash.js.map +1 -0
  241. package/dist/utils/is-dev-env.js +1 -1
  242. package/dist/utils/is-dev-env.js.map +1 -1
  243. package/dist/utils/is-valid-element-type.js +1 -1
  244. package/dist/utils/merge-styles.js +1 -2
  245. package/dist/utils/merge-styles.js.map +1 -1
  246. package/dist/utils/mod-attrs.d.ts +0 -2
  247. package/dist/utils/mod-attrs.js +1 -2
  248. package/dist/utils/mod-attrs.js.map +1 -1
  249. package/dist/utils/process-tokens.d.ts +1 -5
  250. package/dist/utils/process-tokens.js +3 -11
  251. package/dist/utils/process-tokens.js.map +1 -1
  252. package/dist/utils/resolve-recipes.js +1 -2
  253. package/dist/utils/resolve-recipes.js.map +1 -1
  254. package/dist/utils/selector-transform.js +1 -1
  255. package/dist/utils/string.js +1 -1
  256. package/dist/utils/styles.d.ts +1 -1
  257. package/dist/utils/styles.js +2 -3
  258. package/dist/utils/styles.js.map +1 -1
  259. package/dist/utils/typography.d.ts +21 -10
  260. package/dist/utils/typography.js +2 -2
  261. package/dist/utils/typography.js.map +1 -1
  262. package/dist/utils/warnings.js +1 -1
  263. package/dist/zero/babel.d.ts +24 -110
  264. package/dist/zero/babel.js +130 -42
  265. package/dist/zero/babel.js.map +1 -1
  266. package/dist/zero/css-writer.js +1 -2
  267. package/dist/zero/css-writer.js.map +1 -1
  268. package/dist/zero/extractor.js +1 -2
  269. package/dist/zero/extractor.js.map +1 -1
  270. package/dist/zero/index.js +1 -2
  271. package/dist/zero/next.d.ts +12 -0
  272. package/dist/zero/next.js +5 -4
  273. package/dist/zero/next.js.map +1 -1
  274. package/docs/README.md +2 -2
  275. package/docs/adoption.md +5 -3
  276. package/docs/comparison.md +24 -25
  277. package/docs/configuration.md +69 -1
  278. package/docs/design-system.md +22 -10
  279. package/docs/dsl.md +23 -8
  280. package/docs/getting-started.md +10 -10
  281. package/docs/injector.md +41 -25
  282. package/docs/methodology.md +52 -3
  283. package/docs/{runtime.md → react-api.md} +104 -32
  284. package/docs/ssr.md +139 -81
  285. package/docs/styles.md +17 -0
  286. package/docs/tasty-static.md +101 -2
  287. package/package.json +20 -9
  288. package/dist/hooks/resolve-ssr-collector.js +0 -15
  289. package/dist/hooks/resolve-ssr-collector.js.map +0 -1
  290. package/dist/ssr/context.d.ts +0 -8
  291. package/dist/styles/align.d.ts +0 -15
  292. package/dist/styles/align.js +0 -14
  293. package/dist/styles/align.js.map +0 -1
  294. package/dist/styles/justify.d.ts +0 -15
  295. package/dist/styles/justify.js +0 -14
  296. package/dist/styles/justify.js.map +0 -1
@@ -1,28 +1,14 @@
1
- import { SheetManager } from "./sheet-manager.js";
1
+ import "./sheet-manager.js";
2
2
  import { StyleInjector } from "./injector.js";
3
3
  import { getConfig, getGlobalInjector, isTestEnvironment, markStylesGenerated } from "../config.js";
4
-
5
4
  //#region src/injector/index.ts
6
5
  /**
7
- * Allocate a className for a cacheKey without injecting styles yet
8
- */
9
- function allocateClassName(cacheKey, options) {
10
- return getGlobalInjector().allocateClassName(cacheKey, options);
11
- }
12
- /**
13
- * Track a reference to an already-injected cacheKey (refCount + dispose).
14
- * Used on cache hits (SSR hydration or runtime reuse) where the pipeline
15
- * was skipped. Returns null if the cacheKey is not in the cache.
16
- */
17
- function trackRef(cacheKey, options) {
18
- return getGlobalInjector().trackRef(cacheKey, options);
19
- }
20
- /**
21
6
  * Inject styles and return className with dispose function
22
7
  */
23
8
  function inject(rules, options) {
9
+ const injector = getGlobalInjector();
24
10
  markStylesGenerated();
25
- return getGlobalInjector().inject(rules, options);
11
+ return injector.inject(rules, options);
26
12
  }
27
13
  /**
28
14
  * Inject global rules that should not reserve tasty class names
@@ -133,7 +119,7 @@ function getCssTextForNode(node, options) {
133
119
  const readClasses = (el) => {
134
120
  const cls = el.getAttribute("class");
135
121
  if (!cls) return;
136
- for (const token of cls.split(/\s+/)) if (/^t\d+$/.test(token)) classSet.add(token);
122
+ for (const token of cls.split(/\s+/)) if (/^t[a-z0-9]+$/.test(token)) classSet.add(token);
137
123
  };
138
124
  if (node.getAttribute) readClasses(node);
139
125
  const elements = node.querySelectorAll ? node.querySelectorAll("[class]") : [];
@@ -147,6 +133,25 @@ function cleanup(root) {
147
133
  return getGlobalInjector().cleanup(root);
148
134
  }
149
135
  /**
136
+ * Record a render-time usage hit for one or more classNames.
137
+ * Used internally by computeStyles and tasty() to track usage for GC.
138
+ * When the global touch counter reaches `touchInterval`, schedules GC.
139
+ */
140
+ function touch(className, options) {
141
+ if (!getConfig().gc) return;
142
+ getGlobalInjector().touch(className, options);
143
+ }
144
+ /**
145
+ * Synchronous garbage collection of unused styles.
146
+ * Evicts the oldest unused styles when usageMap exceeds capacity.
147
+ * With `{ force: true }`, removes ALL unused styles regardless of capacity.
148
+ *
149
+ * @returns Number of styles evicted.
150
+ */
151
+ function gc(options) {
152
+ return getGlobalInjector().gc(options);
153
+ }
154
+ /**
150
155
  * Check if we're currently running in a test environment
151
156
  */
152
157
  function getIsTestEnvironment() {
@@ -174,7 +179,7 @@ function createInjector(config = {}) {
174
179
  ...config
175
180
  });
176
181
  }
177
-
178
182
  //#endregion
179
- export { allocateClassName, cleanup, counterStyle, createInjector, destroy, fontFace, getCssText, getCssTextForNode, getIsTestEnvironment, getRawCSSText, inject, injectGlobal, injectRawCSS, injector, isPropertyDefined, keyframes, property, trackRef };
183
+ export { cleanup, counterStyle, createInjector, destroy, fontFace, gc, getCssText, getCssTextForNode, getIsTestEnvironment, getRawCSSText, inject, injectGlobal, injectRawCSS, injector, isPropertyDefined, keyframes, property, touch };
184
+
180
185
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/injector/index.ts"],"sourcesContent":["import {\n getConfig,\n getGlobalInjector,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Allocate a className for a cacheKey without injecting styles yet\n */\nexport function allocateClassName(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n): { className: string; isNewAllocation: boolean } {\n return getGlobalInjector().allocateClassName(cacheKey, options);\n}\n\n/**\n * Track a reference to an already-injected cacheKey (refCount + dispose).\n * Used on cache hits (SSR hydration or runtime reuse) where the pipeline\n * was skipped. Returns null if the cacheKey is not in the cache.\n */\nexport function trackRef(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n): InjectResult | null {\n return getGlobalInjector().trackRef(cacheKey, options);\n}\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n): InjectResult {\n // Mark that styles have been generated (prevents configuration changes)\n markStylesGenerated();\n\n return getGlobalInjector().inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\nexport interface PropertyOptions {\n /**\n * CSS syntax string for the property (e.g., '<color>', '<length>', '<angle>')\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@property/syntax\n */\n syntax?: string;\n /**\n * Whether the property inherits from parent elements\n * @default true\n */\n inherits?: boolean;\n /**\n * Initial value for the property\n */\n initialValue?: string | number;\n /**\n * Shadow root or document to inject into\n */\n root?: Document | ShadowRoot;\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by name (first definition wins).\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCssText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCssText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCssTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names (t<number>) from the subtree\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (/^t\\d+$/.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCssTextForClasses(classSet, options);\n}\n\n/**\n * Force cleanup of unused rules\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Check if we're currently running in a test environment\n */\nexport function getIsTestEnvironment(): boolean {\n return isTestEnvironment();\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n} from './types';\n\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\n"],"mappings":";;;;;;;;AAsBA,SAAgB,kBACd,UACA,SACiD;AACjD,QAAO,mBAAmB,CAAC,kBAAkB,UAAU,QAAQ;;;;;;;AAQjE,SAAgB,SACd,UACA,SACqB;AACrB,QAAO,mBAAmB,CAAC,SAAS,UAAU,QAAQ;;;;;AAMxD,SAAgB,OACd,OACA,SACc;AAEd,sBAAqB;AAErB,QAAO,mBAAmB,CAAC,OAAO,OAAO,QAAQ;;;;;AAMnD,SAAgB,aACd,OACA,SACoB;AACpB,QAAO,mBAAmB,CAAC,aAAa,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;AAoBzD,SAAgB,aACd,KACA,SACyB;AACzB,QAAO,mBAAmB,CAAC,aAAa,KAAK,QAAQ;;;;;AAMvD,SAAgB,cAAc,SAEnB;AACT,QAAO,mBAAmB,CAAC,cAAc,QAAQ;;;;;AAMnD,SAAgB,UACd,OACA,eACiB;AACjB,QAAO,mBAAmB,CAAC,UAAU,OAAO,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,SAAgB,SAAS,MAAc,SAAiC;AACtE,QAAO,mBAAmB,CAAC,SAAS,MAAM,QAAQ;;;;;;;;AASpD,SAAgB,kBACd,MACA,SACS;AACT,QAAO,mBAAmB,CAAC,kBAAkB,MAAM,QAAQ;;;;;;;;AAS7D,SAAgB,SACd,QACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,SAAS,QAAQ,aAAa,QAAQ;;;;;;;;AASnE,SAAgB,aACd,MACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,aAAa,MAAM,aAAa,QAAQ;;;;;AAMrE,SAAgB,WAAW,SAAoD;AAC7E,QAAO,mBAAmB,CAAC,WAAW,QAAQ;;;;;;AAOhD,SAAgB,kBACd,MACA,SACQ;CAER,MAAM,2BAAW,IAAI,KAAa;CAElC,MAAM,eAAe,OAAgB;EACnC,MAAM,MAAM,GAAG,aAAa,QAAQ;AACpC,MAAI,CAAC,IAAK;AACV,OAAK,MAAM,SAAS,IAAI,MAAM,MAAM,CAClC,KAAI,SAAS,KAAK,MAAM,CAAE,UAAS,IAAI,MAAM;;AAKjD,KAAK,KAAiB,aACpB,aAAY,KAAgB;CAG9B,MAAM,WAAY,KAAoB,mBACjC,KAAoB,iBAAiB,UAAU,GAC/C,EAAE;AACP,KAAI,SAAU,UAAS,QAAQ,YAAY;AAE3C,QAAO,mBAAmB,CAAC,qBAAqB,UAAU,QAAQ;;;;;AAMpE,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,uBAAgC;AAC9C,QAAO,mBAAmB;;;;;AAM5B,MAAa,WAAW,EACtB,IAAI,WAAW;AACb,QAAO,mBAAmB;GAE7B;;;;AAKD,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,eACd,SAAuC,EAAE,EAC1B;AAUf,QAAO,IAAI,cAP6B;EACtC,GAHoB,WAAW;EAK/B,oBAAoB,OAAO,sBAAsB,mBAAmB;EACpE,GAAG;EACJ,CAEmC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/injector/index.ts"],"sourcesContent":["import {\n getConfig,\n getGlobalInjector,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n GCOptions,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n): InjectResult {\n const injector = getGlobalInjector();\n\n markStylesGenerated();\n\n return injector.inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\nexport interface PropertyOptions {\n /**\n * CSS syntax string for the property (e.g., '<color>', '<length>', '<angle>')\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@property/syntax\n */\n syntax?: string;\n /**\n * Whether the property inherits from parent elements\n * @default true\n */\n inherits?: boolean;\n /**\n * Initial value for the property\n */\n initialValue?: string | number;\n /**\n * Shadow root or document to inject into\n */\n root?: Document | ShadowRoot;\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by name (first definition wins).\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCssText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCssText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCssTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names (t<number>) from the subtree\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (/^t[a-z0-9]+$/.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCssTextForClasses(classSet, options);\n}\n\n/**\n * Force cleanup of unused rules\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Record a render-time usage hit for one or more classNames.\n * Used internally by computeStyles and tasty() to track usage for GC.\n * When the global touch counter reaches `touchInterval`, schedules GC.\n */\nexport function touch(\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n if (!getConfig().gc) return;\n getGlobalInjector().touch(className, options);\n}\n\n/**\n * Synchronous garbage collection of unused styles.\n * Evicts the oldest unused styles when usageMap exceeds capacity.\n * With `{ force: true }`, removes ALL unused styles regardless of capacity.\n *\n * @returns Number of styles evicted.\n */\nexport function gc(options?: GCOptions): number {\n return getGlobalInjector().gc(options);\n}\n\n/**\n * Check if we're currently running in a test environment\n */\nexport function getIsTestEnvironment(): boolean {\n return isTestEnvironment();\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n StyleUsage,\n GCConfig,\n GCOptions,\n} from './types';\n\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\n"],"mappings":";;;;;;;AAuBA,SAAgB,OACd,OACA,SACc;CACd,MAAM,WAAW,mBAAmB;AAEpC,sBAAqB;AAErB,QAAO,SAAS,OAAO,OAAO,QAAQ;;;;;AAMxC,SAAgB,aACd,OACA,SACoB;AACpB,QAAO,mBAAmB,CAAC,aAAa,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;AAoBzD,SAAgB,aACd,KACA,SACyB;AACzB,QAAO,mBAAmB,CAAC,aAAa,KAAK,QAAQ;;;;;AAMvD,SAAgB,cAAc,SAEnB;AACT,QAAO,mBAAmB,CAAC,cAAc,QAAQ;;;;;AAMnD,SAAgB,UACd,OACA,eACiB;AACjB,QAAO,mBAAmB,CAAC,UAAU,OAAO,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,SAAgB,SAAS,MAAc,SAAiC;AACtE,QAAO,mBAAmB,CAAC,SAAS,MAAM,QAAQ;;;;;;;;AASpD,SAAgB,kBACd,MACA,SACS;AACT,QAAO,mBAAmB,CAAC,kBAAkB,MAAM,QAAQ;;;;;;;;AAS7D,SAAgB,SACd,QACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,SAAS,QAAQ,aAAa,QAAQ;;;;;;;;AASnE,SAAgB,aACd,MACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,aAAa,MAAM,aAAa,QAAQ;;;;;AAMrE,SAAgB,WAAW,SAAoD;AAC7E,QAAO,mBAAmB,CAAC,WAAW,QAAQ;;;;;;AAOhD,SAAgB,kBACd,MACA,SACQ;CAER,MAAM,2BAAW,IAAI,KAAa;CAElC,MAAM,eAAe,OAAgB;EACnC,MAAM,MAAM,GAAG,aAAa,QAAQ;AACpC,MAAI,CAAC,IAAK;AACV,OAAK,MAAM,SAAS,IAAI,MAAM,MAAM,CAClC,KAAI,eAAe,KAAK,MAAM,CAAE,UAAS,IAAI,MAAM;;AAKvD,KAAK,KAAiB,aACpB,aAAY,KAAgB;CAG9B,MAAM,WAAY,KAAoB,mBACjC,KAAoB,iBAAiB,UAAU,GAC/C,EAAE;AACP,KAAI,SAAU,UAAS,QAAQ,YAAY;AAE3C,QAAO,mBAAmB,CAAC,qBAAqB,UAAU,QAAQ;;;;;AAMpE,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;;;AAQ1C,SAAgB,MACd,WACA,SACM;AACN,KAAI,CAAC,WAAW,CAAC,GAAI;AACrB,oBAAmB,CAAC,MAAM,WAAW,QAAQ;;;;;;;;;AAU/C,SAAgB,GAAG,SAA6B;AAC9C,QAAO,mBAAmB,CAAC,GAAG,QAAQ;;;;;AAMxC,SAAgB,uBAAgC;AAC9C,QAAO,mBAAmB;;;;;AAM5B,MAAa,WAAW,EACtB,IAAI,WAAW;AACb,QAAO,mBAAmB;GAE7B;;;;AAKD,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,eACd,SAAuC,EAAE,EAC1B;AAUf,QAAO,IAAI,cAP6B;EACtC,GAHoB,WAAW;EAK/B,oBAAoB,OAAO,sBAAsB,mBAAmB;EACpE,GAAG;EACJ,CAEmC"}
@@ -1,4 +1,4 @@
1
- import { CacheMetrics, CounterStyleDescriptors, FontFaceDescriptors, GlobalInjectResult, InjectResult, KeyframesResult, KeyframesSteps, PropertyDefinition, RawCSSResult, StyleInjectorConfig } from "./types.js";
1
+ import { CacheMetrics, CounterStyleDescriptors, FontFaceDescriptors, GCOptions, GlobalInjectResult, InjectResult, KeyframesResult, KeyframesSteps, PropertyDefinition, RawCSSResult, StyleInjectorConfig } from "./types.js";
2
2
  import { StyleResult } from "../pipeline/index.js";
3
3
  import { SheetManager } from "./sheet-manager.js";
4
4
 
@@ -6,11 +6,16 @@ import { SheetManager } from "./sheet-manager.js";
6
6
  declare class StyleInjector {
7
7
  private sheetManager;
8
8
  private config;
9
- private cleanupScheduled;
10
9
  private globalRuleCounter;
10
+ private pendingGCHandle;
11
11
  /** @internal — exposed for debug utilities only */
12
12
  get _sheetManager(): SheetManager;
13
13
  constructor(config?: StyleInjectorConfig);
14
+ /**
15
+ * Check if `className` was hydrated from server-rendered styles and,
16
+ * if so, wire the cacheKey mapping. Returns true on hit.
17
+ */
18
+ private tryHydratedHit;
14
19
  /**
15
20
  * Allocate a className for a cacheKey without injecting styles yet.
16
21
  * This allows separating className allocation (render phase) from style injection (insertion phase).
@@ -60,7 +65,7 @@ declare class StyleInjector {
60
65
  root?: Document | ShadowRoot;
61
66
  }): InjectResult | null;
62
67
  /**
63
- * Dispose of a className
68
+ * Dispose of a className (decrements refCount only).
64
69
  */
65
70
  private dispose;
66
71
  /**
@@ -156,6 +161,33 @@ declare class StyleInjector {
156
161
  * Dispose keyframes
157
162
  */
158
163
  private disposeKeyframes;
164
+ private static readonly TASTY_CLASS_RE;
165
+ /**
166
+ * Record a render-time usage hit for one or more classNames.
167
+ * Handles space-separated multi-chunk classNames.
168
+ * When the global touch counter reaches `touchInterval`, schedules a GC
169
+ * via `requestIdleCallback`.
170
+ * No-op on the server.
171
+ */
172
+ touch(className: string, options?: {
173
+ root?: Document | ShadowRoot;
174
+ }): void;
175
+ /**
176
+ * Schedule a GC via `requestIdleCallback` (or synchronously as fallback).
177
+ * Runs GC on all active roots. Avoids double-scheduling via `pendingGCHandle`.
178
+ */
179
+ private scheduleGC;
180
+ /**
181
+ * Synchronous garbage collection.
182
+ *
183
+ * 1. Quick upper-bound check: skip if unused count can't exceed capacity.
184
+ * 2. Scans the DOM for live tasty classNames (safety guard).
185
+ * 3. With `force: true`: deletes all unused entries inline.
186
+ * Without `force`: collects unused, sorts oldest-first, evicts over capacity.
187
+ *
188
+ * @returns Number of styles evicted.
189
+ */
190
+ gc(options?: GCOptions): number;
159
191
  /**
160
192
  * Destroy all resources for a root
161
193
  */
@@ -1,22 +1,73 @@
1
1
  import { getEffectiveDefinition, normalizePropertyDefinition } from "../properties/index.js";
2
+ import { hashString } from "../utils/hash.js";
2
3
  import { isDevEnv } from "../utils/is-dev-env.js";
3
4
  import { parseStyle } from "../utils/styles.js";
4
5
  import { SheetManager } from "./sheet-manager.js";
5
6
  import { fontFaceContentHash, formatFontFaceDeclarations } from "../font-face/index.js";
6
7
  import { formatCounterStyleDeclarations } from "../counter-style/index.js";
7
-
8
8
  //#region src/injector/injector.ts
9
9
  /**
10
- * Generate sequential class name with format t{number}
10
+ * Generate a deterministic class name from a cache key using content hash.
11
+ * The same cache key always produces the same class name across environments.
12
+ */
13
+ function generateClassName(cacheKey) {
14
+ return `t${hashString(cacheKey)}`;
15
+ }
16
+ const RSC_CLASS_RE = /\.(t[a-z0-9]+)\.\1/g;
17
+ /**
18
+ * Extract class names from `<style data-tasty-rsc>` tags.
19
+ * The doubled-specificity pattern `.tXXX.tXXX` makes extraction reliable.
11
20
  */
12
- function generateClassName(counter) {
13
- return `t${counter}`;
21
+ function extractRSCClassNames() {
22
+ if (typeof document === "undefined") return [];
23
+ const styles = document.querySelectorAll("style[data-tasty-rsc]");
24
+ if (styles.length === 0) return [];
25
+ const classSet = /* @__PURE__ */ new Set();
26
+ for (const style of styles) {
27
+ const text = style.textContent;
28
+ if (!text) continue;
29
+ let match;
30
+ RSC_CLASS_RE.lastIndex = 0;
31
+ while ((match = RSC_CLASS_RE.exec(text)) !== null) classSet.add(match[1]);
32
+ }
33
+ return Array.from(classSet);
14
34
  }
15
- var StyleInjector = class {
35
+ /**
36
+ * Lazily sync server-rendered class names into the client registry.
37
+ *
38
+ * Sources:
39
+ * 1. `window.__TASTY__` — pushed by SSR/RSC streaming scripts
40
+ * 2. `<style data-tasty-rsc>` tags — inline CSS emitted by RSC components
41
+ *
42
+ * Called inside `inject()` / `allocateClassName()` to pick up
43
+ * class names rendered on the server (including during SPA navigation).
44
+ */
45
+ function syncServerClasses(registry) {
46
+ if (typeof window === "undefined") return;
47
+ const classes = window.__TASTY__;
48
+ if (classes && classes.length > registry.serverClassSyncIndex) {
49
+ for (let i = registry.serverClassSyncIndex; i < classes.length; i++) registerHydratedClass(registry, classes[i]);
50
+ registry.serverClassSyncIndex = classes.length;
51
+ }
52
+ if (!registry.rscStylesScanned) {
53
+ registry.rscStylesScanned = true;
54
+ for (const cls of extractRSCClassNames()) registerHydratedClass(registry, cls);
55
+ }
56
+ }
57
+ function registerHydratedClass(registry, className) {
58
+ if (registry.rules.has(className)) return;
59
+ registry.rules.set(className, {
60
+ className,
61
+ ruleIndex: -2,
62
+ sheetIndex: -2
63
+ });
64
+ registry.refCounts.set(className, 0);
65
+ }
66
+ var StyleInjector = class StyleInjector {
16
67
  sheetManager;
17
68
  config;
18
- cleanupScheduled = false;
19
69
  globalRuleCounter = 0;
70
+ pendingGCHandle = null;
20
71
  /** @internal — exposed for debug utilities only */
21
72
  get _sheetManager() {
22
73
  return this.sheetManager;
@@ -26,6 +77,19 @@ var StyleInjector = class {
26
77
  this.sheetManager = new SheetManager(config);
27
78
  }
28
79
  /**
80
+ * Check if `className` was hydrated from server-rendered styles and,
81
+ * if so, wire the cacheKey mapping. Returns true on hit.
82
+ */
83
+ tryHydratedHit(registry, cacheKey, className) {
84
+ syncServerClasses(registry);
85
+ const rule = registry.rules.get(className);
86
+ if (rule && rule.ruleIndex === -2 && rule.sheetIndex === -2) {
87
+ registry.cacheKeyToClassName.set(cacheKey, className);
88
+ return true;
89
+ }
90
+ return false;
91
+ }
92
+ /**
29
93
  * Allocate a className for a cacheKey without injecting styles yet.
30
94
  * This allows separating className allocation (render phase) from style injection (insertion phase).
31
95
  */
@@ -36,7 +100,19 @@ var StyleInjector = class {
36
100
  className: registry.cacheKeyToClassName.get(cacheKey),
37
101
  isNewAllocation: false
38
102
  };
39
- const className = generateClassName(registry.classCounter++);
103
+ const className = generateClassName(cacheKey);
104
+ if (this.tryHydratedHit(registry, cacheKey, className)) return {
105
+ className,
106
+ isNewAllocation: false
107
+ };
108
+ if (registry.rules.get(className)) {
109
+ if (isDevEnv()) console.warn(`[tasty] Hash collision: cache keys produce the same class "${className}". Styles may be incorrect.`);
110
+ registry.cacheKeyToClassName.set(cacheKey, className);
111
+ return {
112
+ className,
113
+ isNewAllocation: false
114
+ };
115
+ }
40
116
  const placeholderRuleInfo = {
41
117
  className,
42
118
  ruleIndex: -1,
@@ -75,7 +151,17 @@ var StyleInjector = class {
75
151
  dispose: () => this.dispose(className, registry)
76
152
  };
77
153
  }
78
- } else className = generateClassName(registry.classCounter++);
154
+ } else if (cacheKey) {
155
+ className = generateClassName(cacheKey);
156
+ if (this.tryHydratedHit(registry, cacheKey, className)) {
157
+ registry.refCounts.set(className, (registry.refCounts.get(className) || 0) + 1);
158
+ if (registry.metrics) registry.metrics.hits++;
159
+ return {
160
+ className,
161
+ dispose: () => this.dispose(className, registry)
162
+ };
163
+ }
164
+ } else className = `t${hashString(rules.map((r) => `${r.selector}\0${r.declarations}`).join("\n"))}`;
79
165
  const rulesToInsert = rules.map((rule) => {
80
166
  let newSelector = rule.selector;
81
167
  if (rule.needsClassName) {
@@ -199,17 +285,14 @@ var StyleInjector = class {
199
285
  };
200
286
  }
201
287
  /**
202
- * Dispose of a className
288
+ * Dispose of a className (decrements refCount only).
203
289
  */
204
290
  dispose(className, registry) {
205
291
  const currentRefCount = registry.refCounts.get(className);
206
292
  if (currentRefCount == null || currentRefCount <= 0) return;
207
293
  const newRefCount = currentRefCount - 1;
208
294
  registry.refCounts.set(className, newRefCount);
209
- if (newRefCount === 0) {
210
- if (registry.metrics) registry.metrics.totalUnused++;
211
- this.sheetManager.checkCleanupNeeded(registry);
212
- }
295
+ if (newRefCount === 0 && registry.metrics) registry.metrics.totalUnused++;
213
296
  }
214
297
  /**
215
298
  * Force bulk cleanup of unused styles
@@ -451,15 +534,118 @@ var StyleInjector = class {
451
534
  }
452
535
  }
453
536
  }
537
+ static TASTY_CLASS_RE = /^t[a-z0-9]+$/;
538
+ /**
539
+ * Record a render-time usage hit for one or more classNames.
540
+ * Handles space-separated multi-chunk classNames.
541
+ * When the global touch counter reaches `touchInterval`, schedules a GC
542
+ * via `requestIdleCallback`.
543
+ * No-op on the server.
544
+ */
545
+ touch(className, options) {
546
+ if (typeof document === "undefined") return;
547
+ if (!this.config.gc) return;
548
+ const root = options?.root || document;
549
+ const registry = this.sheetManager.getRegistry(root);
550
+ const now = Date.now();
551
+ const parts = className.indexOf(" ") === -1 ? [className] : className.split(" ");
552
+ for (const cls of parts) {
553
+ if (!StyleInjector.TASTY_CLASS_RE.test(cls)) continue;
554
+ if (!registry.rules.has(cls)) continue;
555
+ const entry = registry.usageMap.get(cls);
556
+ if (entry) entry.lastTouchedAt = now;
557
+ else registry.usageMap.set(cls, { lastTouchedAt: now });
558
+ registry.touchCount++;
559
+ }
560
+ const touchInterval = this.config.gc.touchInterval ?? 1e3;
561
+ if (registry.touchCount >= touchInterval) {
562
+ registry.touchCount = 0;
563
+ this.scheduleGC();
564
+ }
565
+ }
566
+ /**
567
+ * Schedule a GC via `requestIdleCallback` (or synchronously as fallback).
568
+ * Runs GC on all active roots. Avoids double-scheduling via `pendingGCHandle`.
569
+ */
570
+ scheduleGC() {
571
+ if (this.pendingGCHandle != null) return;
572
+ const runGC = () => {
573
+ this.pendingGCHandle = null;
574
+ this.sheetManager.pruneDisconnectedRoots();
575
+ for (const root of this.sheetManager.getActiveRoots()) this.gc({ root });
576
+ };
577
+ if (typeof requestIdleCallback !== "undefined") this.pendingGCHandle = requestIdleCallback(() => runGC());
578
+ else runGC();
579
+ }
580
+ /**
581
+ * Synchronous garbage collection.
582
+ *
583
+ * 1. Quick upper-bound check: skip if unused count can't exceed capacity.
584
+ * 2. Scans the DOM for live tasty classNames (safety guard).
585
+ * 3. With `force: true`: deletes all unused entries inline.
586
+ * Without `force`: collects unused, sorts oldest-first, evicts over capacity.
587
+ *
588
+ * @returns Number of styles evicted.
589
+ */
590
+ gc(options) {
591
+ if (typeof document === "undefined") return 0;
592
+ if (this.pendingGCHandle != null) {
593
+ if (typeof cancelIdleCallback !== "undefined") cancelIdleCallback(this.pendingGCHandle);
594
+ this.pendingGCHandle = null;
595
+ }
596
+ const root = options?.root || document;
597
+ const force = options?.force ?? false;
598
+ const registry = this.sheetManager.getRegistry(root);
599
+ const capacity = this.config.gc?.capacity ?? 1e3;
600
+ if (!force) {
601
+ let activeCount = 0;
602
+ for (const refCount of registry.refCounts.values()) if (refCount > 0) activeCount++;
603
+ if (registry.usageMap.size - activeCount <= capacity) return 0;
604
+ }
605
+ const liveClasses = /* @__PURE__ */ new Set();
606
+ for (const el of root.querySelectorAll("[class]")) for (const token of el.classList) if (StyleInjector.TASTY_CLASS_RE.test(token)) liveClasses.add(token);
607
+ let swept = 0;
608
+ if (force) for (const [className] of registry.usageMap) {
609
+ if (liveClasses.has(className)) continue;
610
+ if ((registry.refCounts.get(className) ?? 0) > 0) continue;
611
+ registry.usageMap.delete(className);
612
+ swept++;
613
+ }
614
+ else {
615
+ const unused = [];
616
+ for (const [className, usage] of registry.usageMap) {
617
+ if (liveClasses.has(className)) continue;
618
+ if ((registry.refCounts.get(className) ?? 0) > 0) continue;
619
+ unused.push({
620
+ className,
621
+ lastTouchedAt: usage.lastTouchedAt
622
+ });
623
+ }
624
+ if (unused.length > capacity) {
625
+ unused.sort((a, b) => a.lastTouchedAt - b.lastTouchedAt);
626
+ const toEvict = unused.length - capacity;
627
+ for (let i = 0; i < toEvict; i++) {
628
+ registry.usageMap.delete(unused[i].className);
629
+ swept++;
630
+ }
631
+ }
632
+ }
633
+ if (swept > 0) this.sheetManager.forceCleanup(registry);
634
+ return swept;
635
+ }
454
636
  /**
455
637
  * Destroy all resources for a root
456
638
  */
457
639
  destroy(root) {
458
640
  const targetRoot = root || document;
459
641
  this.sheetManager.cleanup(targetRoot);
642
+ if (this.pendingGCHandle != null && !this.sheetManager.hasActiveRoots()) {
643
+ if (typeof cancelIdleCallback !== "undefined") cancelIdleCallback(this.pendingGCHandle);
644
+ this.pendingGCHandle = null;
645
+ }
460
646
  }
461
647
  };
462
-
463
648
  //#endregion
464
649
  export { StyleInjector };
650
+
465
651
  //# sourceMappingURL=injector.js.map