@tenphi/tasty 3.8.0 → 3.9.1

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 (102) hide show
  1. package/README.md +6 -6
  2. package/dist/{babel-Cp_dRhuS.d.ts → babel-Zs1Q03qt.d.ts} +2 -2
  3. package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
  4. package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
  5. package/dist/chunks/build-config-CUQVwdWF.js +42 -0
  6. package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
  7. package/dist/{collector-C7YBiY7D.js → chunks/collector-B0LTHw6Z.js} +6 -125
  8. package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
  9. package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
  10. package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
  11. package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
  12. package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
  13. package/dist/{css-resources-Cyl_axbI.js → chunks/css-resources-BN8apgxt.js} +1 -8
  14. package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
  15. package/dist/chunks/debug-C9LeNVoJ.js +501 -0
  16. package/dist/chunks/debug-C9LeNVoJ.js.map +1 -0
  17. package/dist/chunks/dsl-C5yuAn41.js +1373 -0
  18. package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
  19. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  20. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  21. package/dist/chunks/react-runtime-O-OUrKLH.js +557 -0
  22. package/dist/chunks/react-runtime-O-OUrKLH.js.map +1 -0
  23. package/dist/chunks/runtime-engine-DvnE2g-E.js +2437 -0
  24. package/dist/chunks/runtime-engine-DvnE2g-E.js.map +1 -0
  25. package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
  26. package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
  27. package/dist/{merge-styles-ChW1k-ZM.js → chunks/shared-utils-DWA4LjIa.js} +55 -54
  28. package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
  29. package/dist/chunks/style-engine-C1ECBZxR.js +5131 -0
  30. package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
  31. package/dist/{css-writer-BiumPvq-.js → chunks/zero-engine-B6EnYcXY.js} +3 -120
  32. package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
  33. package/dist/{collector-CUtAFyIb.d.ts → collector-hl5KNH7k.d.ts} +6 -4
  34. package/dist/{config-BY1e5y7V.d.ts → config-DWL1ZYue.d.ts} +20 -25
  35. package/dist/core/index.d.ts +5 -5
  36. package/dist/core/index.js +9 -6
  37. package/dist/{index-uX74k5jG.d.ts → index-D9N9GV24.d.ts} +17 -50
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.js +11 -922
  40. package/dist/{merge-styles-pf6iPs82.d.ts → merge-styles-C_oMoJVd.d.ts} +2 -2
  41. package/dist/ssr/astro-client.js +1 -14
  42. package/dist/ssr/astro-client.js.map +1 -1
  43. package/dist/ssr/astro-middleware-extract-static.js +1 -1
  44. package/dist/ssr/astro-middleware-extract.js +1 -1
  45. package/dist/ssr/astro-middleware-static.js +1 -12
  46. package/dist/ssr/astro-middleware-static.js.map +1 -1
  47. package/dist/ssr/astro-middleware.js +1 -13
  48. package/dist/ssr/astro-middleware.js.map +1 -1
  49. package/dist/ssr/astro.js +219 -1
  50. package/dist/ssr/astro.js.map +1 -0
  51. package/dist/ssr/index.d.ts +6 -6
  52. package/dist/ssr/index.js +4 -4
  53. package/dist/ssr/next-config.d.ts +1 -1
  54. package/dist/ssr/next-config.js +29 -20
  55. package/dist/ssr/next-config.js.map +1 -1
  56. package/dist/ssr/next.d.ts +1 -1
  57. package/dist/ssr/next.js +5 -37
  58. package/dist/ssr/next.js.map +1 -1
  59. package/dist/static/index.d.ts +2 -2
  60. package/dist/static/index.js +1 -19
  61. package/dist/static/index.js.map +1 -1
  62. package/dist/{index-DBjd4MAb.d.ts → types-jKZNpias.d.ts} +800 -800
  63. package/dist/zero/babel.d.ts +1 -1
  64. package/dist/zero/babel.js +25 -96
  65. package/dist/zero/babel.js.map +1 -1
  66. package/dist/zero/index.d.ts +1 -1
  67. package/dist/zero/index.js +1 -1
  68. package/dist/zero/next.d.ts +1 -1
  69. package/dist/zero/next.js +0 -31
  70. package/dist/zero/next.js.map +1 -1
  71. package/docs/debug.md +2 -5
  72. package/docs/pipeline.md +3 -0
  73. package/docs/runtime-benchmarks.md +105 -68
  74. package/docs/ssr.md +1 -1
  75. package/package.json +49 -6
  76. package/dist/astro-w8r-u4qo.js +0 -301
  77. package/dist/astro-w8r-u4qo.js.map +0 -1
  78. package/dist/async-storage-DKK-wTD4.js +0 -44
  79. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  80. package/dist/collector-C7YBiY7D.js.map +0 -1
  81. package/dist/config-yXpe2jAV.js +0 -12668
  82. package/dist/config-yXpe2jAV.js.map +0 -1
  83. package/dist/context-CA8YKeMn.js +0 -24
  84. package/dist/context-CA8YKeMn.js.map +0 -1
  85. package/dist/core-DoEZAHJq.js +0 -1732
  86. package/dist/core-DoEZAHJq.js.map +0 -1
  87. package/dist/css-resources-Cyl_axbI.js.map +0 -1
  88. package/dist/css-writer-BiumPvq-.js.map +0 -1
  89. package/dist/format-global-rules-DklyaXv-.js +0 -22
  90. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  91. package/dist/format-rules-DHuG25KU.js +0 -104
  92. package/dist/format-rules-DHuG25KU.js.map +0 -1
  93. package/dist/hydrate-BvRP6QEC.js +0 -37
  94. package/dist/hydrate-BvRP6QEC.js.map +0 -1
  95. package/dist/index.js.map +0 -1
  96. package/dist/keyframes-B8uPLZwx.js +0 -535
  97. package/dist/keyframes-B8uPLZwx.js.map +0 -1
  98. package/dist/merge-styles-ChW1k-ZM.js.map +0 -1
  99. package/dist/resolve-recipes-BNmjANzT.js +0 -144
  100. package/dist/resolve-recipes-BNmjANzT.js.map +0 -1
  101. package/dist/ssr-collector-ref-COs_ioWl.js +0 -29
  102. package/dist/ssr-collector-ref-COs_ioWl.js.map +0 -1
@@ -1,1732 +0,0 @@
1
- import { Bt as getGlobalParseFunctions, G as StyleInjector, Gt as parseStyle, It as registerLocalFunctionPolyfills, J as hasLocalCounterStyle, K as extractLocalCounterStyle, Mt as formatFunctionRule, Nt as hasLocalFunctions, Pt as parseFunctionName, Q as hasLocalFontFace, Qt as isDevEnv, Ut as normalizeColorTokenValue, Vt as getGlobalParser, X as fontFaceContentHash, Y as extractLocalFontFace, Z as formatFontFaceRule, _ as isFunctionsPolyfillEnabled, _t as hashString, bt as hasLocalProperties, c as getGlobalInjector, en as Lru, et as STYLE_HANDLER_MAP, f as getNamePrefix, ft as makeClassName, ht as tastyClassRegex, it as PropertyTypeResolver, jt as extractLocalFunctions, l as getGlobalKeyframes, n as getConfig, ot as flushStyles, p as hasGlobalKeyframes, q as formatCounterStyleRule, rt as createStyle, sn as normalizeDslName, tn as overrideColorAlpha, v as isTestEnvironment, vt as extractLocalProperties, wt as CHUNK_NAMES, xt as parsePropertyToken, y as markStylesGenerated, z as camelToKebab } from "./config-yXpe2jAV.js";
2
- import { a as mergeKeyframes, c as resolveKeyframesNames, d as categorizeStyleKeys, i as hasLocalKeyframes, l as renderStylesForChunk, n as extractLocalKeyframes, o as referencesAnimation, r as filterUsedKeyframes, s as replaceAnimationNames, t as extractAnimationNamesFromStyles, u as generateChunkCacheKey } from "./keyframes-B8uPLZwx.js";
3
- import { t as getRegisteredSSRCollector } from "./ssr-collector-ref-COs_ioWl.js";
4
- import { n as formatPropertyCSS, t as formatRules } from "./format-rules-DHuG25KU.js";
5
- import { t as resolveRecipes } from "./resolve-recipes-BNmjANzT.js";
6
- import { cache } from "react";
7
- //#region src/utils/function-color.ts
8
- const RE_FUNC_NAME = /^([a-z][a-z0-9-]*)\s*\(/i;
9
- const RE_COLOR_OUT = /^(?:rgb|hsl|hwb|lab|lch|oklab|oklch|color)\(|^#|^var\(--/i;
10
- /**
11
- * Resolve a `name(...)` value produced by a registered custom parse function
12
- * into its concrete color output.
13
- *
14
- * A color function is just a `functions` entry whose output is an already
15
- * supported color (`rgb`, `hsl`, `#…`, `oklch`, …). This helper delegates the
16
- * value to the global parser (which already runs the registered parse function)
17
- * and returns the result only when it looks like a color. Returns `null` when
18
- * `str` is not a registered custom function or its output is not a color.
19
- *
20
- * This is the generic replacement for the previously hardcoded okhsl/okhst
21
- * conversion branches scattered across `strToRgb`, `resolveToRgbaValues`, and
22
- * the `#token.alpha` injection path.
23
- */
24
- function resolveFunctionColor(str) {
25
- const m = RE_FUNC_NAME.exec(str);
26
- if (!m) return null;
27
- const name = m[1].toLowerCase();
28
- getGlobalParser();
29
- if (!(name in getGlobalParseFunctions())) return null;
30
- const out = getGlobalParser().process(str).output;
31
- if (!out || !RE_COLOR_OUT.test(out)) return null;
32
- return out;
33
- }
34
- //#endregion
35
- //#region src/injector/chunk-sheet-registry.ts
36
- /**
37
- * Global registry mapping CSS content hashes to shared constructable
38
- * CSSStyleSheet objects with reference counting.
39
- *
40
- * Multiple shadow roots adopting the same chunk share a single underlying
41
- * stylesheet object — parse once, adopt everywhere.
42
- */
43
- var ChunkSheetRegistry = class {
44
- sheets = /* @__PURE__ */ new Map();
45
- sheetToHash = /* @__PURE__ */ new WeakMap();
46
- /**
47
- * Get or create a CSSStyleSheet for the given CSS text.
48
- * Increments refCount. Uses content hash as the dedup key.
49
- */
50
- acquire(cssText) {
51
- const hash = hashString(cssText);
52
- const existing = this.sheets.get(hash);
53
- if (existing) {
54
- existing.refCount++;
55
- return existing.sheet;
56
- }
57
- const sheet = new CSSStyleSheet();
58
- sheet.replaceSync(cssText);
59
- const entry = {
60
- sheet,
61
- cssText,
62
- refCount: 1
63
- };
64
- this.sheets.set(hash, entry);
65
- this.sheetToHash.set(sheet, hash);
66
- return sheet;
67
- }
68
- /**
69
- * Decrement refCount for a sheet. When refCount reaches 0,
70
- * the sheet is removed from the registry.
71
- */
72
- release(sheet) {
73
- const hash = this.sheetToHash.get(sheet);
74
- if (!hash) return;
75
- const entry = this.sheets.get(hash);
76
- if (!entry) return;
77
- entry.refCount--;
78
- if (entry.refCount <= 0) {
79
- this.sheets.delete(hash);
80
- this.sheetToHash.delete(sheet);
81
- }
82
- }
83
- /**
84
- * Bulk acquire — returns an array of CSSStyleSheet in the same order.
85
- */
86
- acquireAll(cssTexts) {
87
- return cssTexts.map((text) => this.acquire(text));
88
- }
89
- /**
90
- * Bulk release — decrements refCount for each sheet.
91
- */
92
- releaseAll(sheets) {
93
- for (const sheet of sheets) this.release(sheet);
94
- }
95
- /** Number of unique sheets currently held. */
96
- get size() {
97
- return this.sheets.size;
98
- }
99
- };
100
- /** Module-level singleton shared across the entire application. */
101
- const chunkSheetRegistry = new ChunkSheetRegistry();
102
- //#endregion
103
- //#region src/injector/index.ts
104
- /**
105
- * Inject styles and return className with dispose function
106
- */
107
- function inject(rules, options) {
108
- const injector = getGlobalInjector();
109
- markStylesGenerated();
110
- return injector.inject(rules, options);
111
- }
112
- /**
113
- * Inject global rules that should not reserve tasty class names
114
- */
115
- function injectGlobal(rules, options) {
116
- return getGlobalInjector().injectGlobal(rules, options);
117
- }
118
- /**
119
- * Inject raw CSS text directly without parsing
120
- * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.
121
- * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.
122
- *
123
- * @example
124
- * ```tsx
125
- * // Inject raw CSS
126
- * const { dispose } = injectRawCSS(`
127
- * body { margin: 0; padding: 0; }
128
- * .my-class { color: red; }
129
- * `);
130
- *
131
- * // Later, remove the injected CSS
132
- * dispose();
133
- * ```
134
- */
135
- function injectRawCSS(css, options) {
136
- return getGlobalInjector().injectRawCSS(css, options);
137
- }
138
- /**
139
- * Get raw CSS text for SSR
140
- */
141
- function getRawCSSText(options) {
142
- return getGlobalInjector().getRawCSSText(options);
143
- }
144
- /**
145
- * Inject keyframes and return object with toString() and dispose()
146
- */
147
- function keyframes(steps, nameOrOptions) {
148
- return getGlobalInjector().keyframes(steps, nameOrOptions);
149
- }
150
- /**
151
- * Define a CSS @property custom property.
152
- * This enables advanced features like animating custom properties.
153
- *
154
- * Note: @property rules are global and persistent once defined.
155
- * Re-registering the same property name is a no-op.
156
- *
157
- * @param name - The custom property name (must start with --)
158
- * @param options - Property configuration
159
- *
160
- * @example
161
- * ```ts
162
- * // Define a color property that can be animated
163
- * property('--my-color', {
164
- * syntax: '<color>',
165
- * initialValue: 'red',
166
- * });
167
- *
168
- * // Define an angle property
169
- * property('--rotation', {
170
- * syntax: '<angle>',
171
- * inherits: false,
172
- * initialValue: '0deg',
173
- * });
174
- * ```
175
- */
176
- function property(name, options) {
177
- return getGlobalInjector().property(name, options);
178
- }
179
- /**
180
- * Check if a CSS @property has already been defined
181
- *
182
- * @param name - The custom property name to check
183
- * @param options - Options including root
184
- */
185
- function isPropertyDefined(name, options) {
186
- return getGlobalInjector().isPropertyDefined(name, options);
187
- }
188
- /**
189
- * Inject a CSS @font-face rule.
190
- *
191
- * Permanent and global — no dispose or ref-counting.
192
- * Deduplicates by content hash (family + descriptors).
193
- */
194
- function fontFace(family, descriptors, options) {
195
- return getGlobalInjector().fontFace(family, descriptors, options);
196
- }
197
- /**
198
- * Inject a CSS @counter-style rule.
199
- *
200
- * Permanent and global — no dispose or ref-counting. Deduplicates by name and
201
- * overrides an existing rule by default. Pass `weak: true` for global
202
- * `configure()` definitions, which never clobber an existing rule.
203
- */
204
- function counterStyle(name, descriptors, options) {
205
- return getGlobalInjector().counterStyle(name, descriptors, options);
206
- }
207
- /**
208
- * Inject a CSS @function rule (custom function).
209
- *
210
- * Permanent and global — no dispose or ref-counting. Deduplicates by function
211
- * name and overrides an existing rule by default. Pass `weak: true` for global
212
- * `configure()` definitions, which never clobber an existing rule.
213
- *
214
- * @param name - The function name (`$$name`, `$name`, or `--name`)
215
- * @param definition - Function definition (args, returns, result, local vars)
216
- *
217
- * @example
218
- * ```ts
219
- * func('$$negative', { args: ['$value'], result: '(-1 * $value)' });
220
- * ```
221
- */
222
- function func(name, definition, options) {
223
- return getGlobalInjector().func(name, definition, options);
224
- }
225
- /**
226
- * Get CSS text from all sheets (for SSR)
227
- */
228
- function getCSSText(options) {
229
- return getGlobalInjector().getCSSText(options);
230
- }
231
- /**
232
- * Collect only CSS used by a rendered subtree (like jest-styled-components).
233
- * Pass the container returned by render(...).
234
- */
235
- function getCSSTextForNode(node, options) {
236
- const classRegex = tastyClassRegex(getNamePrefix());
237
- const classSet = /* @__PURE__ */ new Set();
238
- const readClasses = (el) => {
239
- const cls = el.getAttribute("class");
240
- if (!cls) return;
241
- for (const token of cls.split(/\s+/)) if (classRegex.test(token)) classSet.add(token);
242
- };
243
- if (node.getAttribute) readClasses(node);
244
- const elements = node.querySelectorAll ? node.querySelectorAll("[class]") : [];
245
- if (elements) elements.forEach(readClasses);
246
- return getGlobalInjector().getCSSTextForClasses(classSet, options);
247
- }
248
- /**
249
- * Take a reference on local `@keyframes` under the deterministic names the
250
- * caller resolved, and report which entry holds each. Pair with
251
- * `ownKeyframes()` once the rules exist to inspect.
252
- */
253
- function holdKeyframes(steps, names, options) {
254
- return getGlobalInjector().holdKeyframes(steps, names, options);
255
- }
256
- /**
257
- * Record that a class animates these keyframes, so the reference is released
258
- * when the last such class is collected.
259
- */
260
- function ownKeyframes(key, className, options) {
261
- getGlobalInjector().ownKeyframes(key, className, options);
262
- }
263
- /**
264
- * Remove every injected rule that is neither in the DOM nor held by an
265
- * outstanding `inject()` handle. Equivalent to `gc({ force: true })`.
266
- */
267
- function cleanup(root) {
268
- return getGlobalInjector().cleanup(root);
269
- }
270
- /**
271
- * Count a render, so that a collection pass is scheduled every
272
- * `gc.touchInterval` of them. Used internally by computeStyles and tasty().
273
- *
274
- * @deprecated The class name is ignored — collection asks the DOM what is
275
- * rendered rather than recording usage per class. The argument is kept so
276
- * existing calls still compile.
277
- */
278
- function touch(className, options) {
279
- if (!getConfig().gc) return;
280
- getGlobalInjector().touch(className, options);
281
- }
282
- /**
283
- * Synchronous garbage collection of unused styles — those no element carries
284
- * and no `inject()` handle references. Evicts the oldest ones once they exceed
285
- * capacity. With `{ force: true }`, removes all of them regardless of capacity.
286
- *
287
- * @returns Number of styles evicted.
288
- */
289
- function gc(options) {
290
- return getGlobalInjector().gc(options);
291
- }
292
- /**
293
- * Get the global injector instance for debugging
294
- */
295
- const injector = { get instance() {
296
- return getGlobalInjector();
297
- } };
298
- /**
299
- * Destroy all resources and clean up
300
- */
301
- function destroy(root) {
302
- return getGlobalInjector().destroy(root);
303
- }
304
- /**
305
- * Create a new isolated injector instance
306
- */
307
- function createInjector(config = {}) {
308
- return new StyleInjector({
309
- ...getConfig(),
310
- forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),
311
- ...config
312
- });
313
- }
314
- //#endregion
315
- //#region src/rsc-cache.ts
316
- /**
317
- * Shared RSC (React Server Components) inline style cache.
318
- *
319
- * Uses React.cache for per-request memoization in Server Components.
320
- * Both computeStyles() and standalone style functions (useGlobalStyles,
321
- * useRawCSS, useKeyframes, useProperty, useFontFace, useCounterStyle)
322
- * share this cache so that CSS accumulated by standalone functions is
323
- * flushed into inline <style> tags by the next tasty() component.
324
- */
325
- /**
326
- * Per-request RSC style cache using React.cache.
327
- * React.cache provides per-request memoization in Server Components,
328
- * so each request gets its own isolated cache.
329
- */
330
- const getRSCCache = cache(() => ({
331
- cacheKeyToClassName: /* @__PURE__ */ new Map(),
332
- emittedKeys: /* @__PURE__ */ new Set(),
333
- internalsEmitted: false,
334
- pendingCSS: [],
335
- keyToIndex: /* @__PURE__ */ new Map(),
336
- generatedNames: /* @__PURE__ */ new Map()
337
- }));
338
- function rscAllocateClassName(rscCache, cacheKey) {
339
- const existing = rscCache.cacheKeyToClassName.get(cacheKey);
340
- if (existing) return {
341
- className: existing,
342
- isNew: false
343
- };
344
- const className = makeClassName(getNamePrefix(), hashString(cacheKey));
345
- rscCache.cacheKeyToClassName.set(cacheKey, className);
346
- return {
347
- className,
348
- isNew: true
349
- };
350
- }
351
- /**
352
- * Flush any pending CSS accumulated by standalone functions.
353
- * Returns the CSS string and clears the buffer.
354
- */
355
- function flushPendingCSS(rscCache) {
356
- if (rscCache.pendingCSS.length === 0) return "";
357
- const css = rscCache.pendingCSS.join("\n");
358
- rscCache.pendingCSS.length = 0;
359
- rscCache.keyToIndex.clear();
360
- return css;
361
- }
362
- /**
363
- * Push CSS into the RSC pending buffer with dedup via emittedKeys.
364
- * Returns true if the CSS was added, false if it was already emitted.
365
- *
366
- * Pass `replace` for slot-keyed entries (an explicit `id`), where the last write
367
- * must win to match the client's update-tracking behavior. If the slot has
368
- * already been flushed into a `<style>` tag the new CSS is appended instead,
369
- * which still wins by cascade order.
370
- */
371
- function pushRSCCSS(rscCache, key, css, replace) {
372
- if (replace) {
373
- const pendingIndex = rscCache.keyToIndex.get(key);
374
- if (pendingIndex !== void 0) {
375
- rscCache.pendingCSS[pendingIndex] = css;
376
- return true;
377
- }
378
- } else if (rscCache.emittedKeys.has(key)) return false;
379
- rscCache.emittedKeys.add(key);
380
- rscCache.keyToIndex.set(key, rscCache.pendingCSS.length);
381
- rscCache.pendingCSS.push(css);
382
- return true;
383
- }
384
- /**
385
- * Determine the current style injection target.
386
- * Centralizes the three-way detection (SSR collector / RSC cache / client DOM)
387
- * used by all style functions.
388
- */
389
- function getStyleTarget() {
390
- const collector = getRegisteredSSRCollector();
391
- if (collector) return {
392
- mode: "ssr",
393
- collector
394
- };
395
- if (typeof document === "undefined") return {
396
- mode: "rsc",
397
- cache: getRSCCache()
398
- };
399
- return { mode: "client" };
400
- }
401
- //#endregion
402
- //#region src/ssr/collect-auto-properties.ts
403
- /**
404
- * Scan rendered rules for auto-inferable custom properties and emit
405
- * @property CSS via the provided callback.
406
- */
407
- function scanAndEmitAutoProperties(rules, styles, emit) {
408
- const registered = /* @__PURE__ */ new Set();
409
- if (styles) {
410
- const localProps = styles["@property"];
411
- if (localProps && typeof localProps === "object") for (const token of Object.keys(localProps)) {
412
- const parsed = parsePropertyToken(token);
413
- if (parsed.isValid) registered.add(parsed.cssName);
414
- }
415
- }
416
- const resolver = new PropertyTypeResolver();
417
- for (const rule of rules) {
418
- if (!rule.declarations) continue;
419
- resolver.scanDeclarations(rule.declarations, (name) => registered.has(name), (name, syntax, initialValue) => {
420
- registered.add(name);
421
- const css = formatPropertyCSS(name, {
422
- syntax,
423
- inherits: true,
424
- initialValue
425
- });
426
- if (css) emit(name, css);
427
- });
428
- }
429
- }
430
- /**
431
- * Scan rendered rules for custom property declarations and collect
432
- * auto-inferred @property rules via the SSR collector.
433
- *
434
- * @param rules - Rendered style rules containing CSS declarations
435
- * @param collector - SSR collector to emit @property CSS into
436
- * @param styles - Original styles object (used to skip explicit @property)
437
- */
438
- function collectAutoInferredProperties(rules, collector, styles) {
439
- scanAndEmitAutoProperties(rules, styles, (name, css) => {
440
- collector.collectProperty(`__auto:${name}`, css);
441
- });
442
- }
443
- /**
444
- * RSC variant: scan rendered rules and push auto-inferred @property CSS
445
- * into the RSC pending buffer.
446
- */
447
- function collectAutoInferredPropertiesRSC(rules, rscCache, styles) {
448
- scanAndEmitAutoProperties(rules, styles, (name, css) => {
449
- pushRSCCSS(rscCache, `__auto:${name}`, css);
450
- });
451
- }
452
- //#endregion
453
- //#region src/ssr/format-keyframes.ts
454
- /**
455
- * Convert keyframes steps to a CSS string.
456
- * Replicates SheetManager.stepsToCSS() without the class instance.
457
- */
458
- function stepsToCSS(steps) {
459
- const rules = [];
460
- for (const [key, value] of Object.entries(steps)) {
461
- if (typeof value === "string") {
462
- rules.push(`${key} { ${value.trim()} }`);
463
- continue;
464
- }
465
- const styleMap = value || {};
466
- const styleNames = Object.keys(styleMap).sort();
467
- const handlerQueue = [];
468
- const seenHandlers = /* @__PURE__ */ new Set();
469
- styleNames.forEach((styleName) => {
470
- let handlers = STYLE_HANDLER_MAP[styleName];
471
- if (!handlers) handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];
472
- handlers.forEach((handler) => {
473
- if (!seenHandlers.has(handler)) {
474
- seenHandlers.add(handler);
475
- handlerQueue.push(handler);
476
- }
477
- });
478
- });
479
- const declarationPairs = [];
480
- handlerQueue.forEach((handler) => {
481
- const result = handler(handler.__lookupStyles.reduce((acc, name) => {
482
- const v = styleMap[name];
483
- if (v !== void 0) acc[name] = v;
484
- return acc;
485
- }, {}));
486
- if (!result) return;
487
- (Array.isArray(result) ? result : [result]).forEach((cssMap) => {
488
- if (!cssMap || typeof cssMap !== "object") return;
489
- const { $: _$, ...props } = cssMap;
490
- Object.entries(props).forEach(([prop, val]) => {
491
- if (val == null || val === "") return;
492
- if (Array.isArray(val)) val.forEach((v) => {
493
- if (v != null && v !== "") declarationPairs.push({
494
- prop,
495
- value: String(v)
496
- });
497
- });
498
- else declarationPairs.push({
499
- prop,
500
- value: String(val)
501
- });
502
- });
503
- });
504
- });
505
- const declarations = declarationPairs.map((d) => `${d.prop}: ${d.value}`).join("; ");
506
- rules.push(`${key} { ${declarations.trim()} }`);
507
- }
508
- return rules.join(" ");
509
- }
510
- /**
511
- * Format a @keyframes rule as a CSS string.
512
- */
513
- function formatKeyframesCSS(name, steps) {
514
- return `@keyframes ${name} { ${stepsToCSS(steps)} }`;
515
- }
516
- //#endregion
517
- //#region src/utils/has-keys.ts
518
- /**
519
- * Check if an object has any own enumerable keys.
520
- * Avoids the array allocation of Object.keys(obj).length > 0.
521
- */
522
- function hasKeys(obj) {
523
- for (const _ in obj) return true;
524
- return false;
525
- }
526
- //#endregion
527
- //#region src/compute-styles.ts
528
- /**
529
- * Hook-free, synchronous style computation.
530
- *
531
- * Extracts the core logic from useStyles() into a plain function that can
532
- * be called during React render without any hooks. Three code paths:
533
- *
534
- * 1. SSR collector — styles collected via ServerStyleCollector
535
- * 2. Client inject — styles injected synchronously into the DOM
536
- * 3. RSC inline — styles returned as CSS strings for inline <style> emission
537
- *
538
- * This enables tasty() components to work as React Server Components.
539
- */
540
- const EMPTY_RESULT = { className: "" };
541
- /**
542
- * Mark internals as emitted for this RSC request.
543
- *
544
- * Internals (tokens, @property, @font-face, @counter-style) are emitted
545
- * exclusively by the SSR collector via ServerStyleCollector.collectInternals().
546
- * The SSR path is reliable because TastyRegistry is always present as a
547
- * client component in the root layout, guaranteeing SSR runs for every page.
548
- *
549
- * Previously this function also emitted internals and coordinated with SSR
550
- * via a globalThis flag, but that flag leaked across requests in the same
551
- * Node.js process, causing pages without RSC-rendered tasty components
552
- * (e.g. the playground route) to lose all token CSS.
553
- */
554
- function collectInternalsRSC(rscCache) {
555
- if (rscCache.internalsEmitted) return "";
556
- rscCache.internalsEmitted = true;
557
- return "";
558
- }
559
- /**
560
- * Collect per-component ancillary CSS (keyframes, @property, font-face,
561
- * counter-style) for RSC mode.
562
- */
563
- function collectAncillaryRSC(rscCache, styles) {
564
- const parts = [];
565
- const usedKf = getUsedKeyframes(styles);
566
- const rscKeyframeNames = usedKf ? resolveKeyframesNames(usedKf) : null;
567
- if (usedKf && rscKeyframeNames) for (const [authored, steps] of Object.entries(usedKf)) {
568
- const name = rscKeyframeNames.get(authored);
569
- const key = `__kf:${name}`;
570
- if (!rscCache.emittedKeys.has(key)) {
571
- rscCache.emittedKeys.add(key);
572
- parts.push(formatKeyframesCSS(name, steps));
573
- }
574
- }
575
- if (hasLocalProperties(styles)) {
576
- const localProperties = extractLocalProperties(styles);
577
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) {
578
- const key = `__prop:${token}`;
579
- if (!rscCache.emittedKeys.has(key)) {
580
- rscCache.emittedKeys.add(key);
581
- const css = formatPropertyCSS(token, definition);
582
- if (css) parts.push(css);
583
- }
584
- }
585
- }
586
- if (hasLocalFontFace(styles)) {
587
- const localFontFace = extractLocalFontFace(styles);
588
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
589
- const descriptors = Array.isArray(input) ? input : [input];
590
- for (const desc of descriptors) {
591
- const key = `__ff:${fontFaceContentHash(family, desc)}`;
592
- if (!rscCache.emittedKeys.has(key)) {
593
- rscCache.emittedKeys.add(key);
594
- parts.push(formatFontFaceRule(family, desc));
595
- }
596
- }
597
- }
598
- }
599
- if (hasLocalCounterStyle(styles)) {
600
- const localCounterStyle = extractLocalCounterStyle(styles);
601
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) {
602
- const key = `__cs:${name}:${JSON.stringify(descriptors)}`;
603
- if (!rscCache.emittedKeys.has(key)) {
604
- rscCache.emittedKeys.add(key);
605
- parts.push(formatCounterStyleRule(name, descriptors));
606
- }
607
- }
608
- }
609
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
610
- const localFunctions = extractLocalFunctions(styles);
611
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) {
612
- const key = `__func:${parseFunctionName(name)}`;
613
- if (!rscCache.emittedKeys.has(key)) {
614
- rscCache.emittedKeys.add(key);
615
- parts.push(formatFunctionRule(name, definition));
616
- }
617
- }
618
- }
619
- return parts.join("\n");
620
- }
621
- /**
622
- * Process all chunks in RSC mode: render CSS to strings, allocate classNames,
623
- * and return combined { className, css }.
624
- */
625
- function computeStylesRSC(styles, chunkMap, stableStyles) {
626
- const rscCache = getRSCCache();
627
- const cssParts = [];
628
- const classNames = [];
629
- const rscUsedKf = getUsedKeyframes(styles);
630
- const rscKeyframeNames = rscUsedKf ? resolveKeyframesNames(rscUsedKf) : null;
631
- const pendingCSS = flushPendingCSS(rscCache);
632
- if (pendingCSS) cssParts.push(pendingCSS);
633
- const internalsCSS = collectInternalsRSC(rscCache);
634
- if (internalsCSS) cssParts.push(internalsCSS);
635
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
636
- if (chunkStyleKeys.length === 0) continue;
637
- const baseKey = generateChunkCacheKey(styles, chunkName, chunkStyleKeys, stableStyles);
638
- const renderResult = renderStylesForChunk(styles, chunkName, chunkStyleKeys);
639
- if (renderResult.rules.length === 0) continue;
640
- const { rules, cacheKey } = applyKeyframeNames(renderResult.rules, baseKey, rscKeyframeNames);
641
- const { className, isNew } = rscAllocateClassName(rscCache, cacheKey);
642
- classNames.push(className);
643
- if (isNew) {
644
- const css = formatRules(rules, className);
645
- if (css) cssParts.push(css);
646
- }
647
- }
648
- const ancillaryCSS = collectAncillaryRSC(rscCache, styles);
649
- if (ancillaryCSS) cssParts.push(ancillaryCSS);
650
- if (classNames.length === 0) return EMPTY_RESULT;
651
- const css = cssParts.join("\n");
652
- return {
653
- className: classNames.join(" "),
654
- css: css || void 0
655
- };
656
- }
657
- /**
658
- * Get keyframes that are actually used in styles.
659
- * Returns null if no keyframes are used (fast path for zero overhead).
660
- */
661
- function getUsedKeyframes(styles) {
662
- const hasLocal = hasLocalKeyframes(styles);
663
- const hasGlobal = hasGlobalKeyframes();
664
- if (!hasLocal && !hasGlobal) return null;
665
- const usedNames = extractAnimationNamesFromStyles(styles);
666
- if (usedNames.size === 0) return null;
667
- return filterUsedKeyframes(mergeKeyframes(hasLocal ? extractLocalKeyframes(styles) : null, hasGlobal ? getGlobalKeyframes() : null), usedNames);
668
- }
669
- /**
670
- * Process a chunk on the SSR path: allocate via collector, render, collect CSS.
671
- */
672
- function processChunkSSR(collector, styles, chunkName, styleKeys, stableStyles, keyframeNames) {
673
- if (styleKeys.length === 0) return null;
674
- const baseKey = generateChunkCacheKey(styles, chunkName, styleKeys, stableStyles);
675
- const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);
676
- if (renderResult.rules.length === 0) return null;
677
- const { animations, rules, cacheKey } = applyKeyframeNames(renderResult.rules, baseKey, keyframeNames);
678
- const { className, isNewAllocation } = collector.allocateClassName(cacheKey);
679
- if (isNewAllocation) {
680
- collector.collectChunk(cacheKey, className, rules);
681
- return {
682
- name: chunkName,
683
- styleKeys,
684
- cacheKey,
685
- renderResult: {
686
- ...renderResult,
687
- rules
688
- },
689
- className,
690
- animations
691
- };
692
- }
693
- return {
694
- name: chunkName,
695
- styleKeys,
696
- cacheKey,
697
- renderResult: { rules: [] },
698
- className
699
- };
700
- }
701
- /**
702
- * Point a chunk's rules at the resolved keyframe names, and fold those names
703
- * into its cache key.
704
- *
705
- * Both halves matter, and both have to happen before the rules are written
706
- * anywhere: the declarations have to name the animation that will exist, and
707
- * the key has to distinguish two components that authored the same shorthand
708
- * over different definitions. Shared by the client and the server so they
709
- * cannot disagree about either.
710
- */
711
- function applyKeyframeNames(ruleset, baseKey, keyframeNames) {
712
- if (!keyframeNames || keyframeNames.size === 0) return {
713
- animations: [],
714
- rules: ruleset,
715
- cacheKey: baseKey
716
- };
717
- const animations = [...keyframeNames.keys()].filter((authored) => ruleset.some((rule) => referencesAnimation(rule.declarations, authored)));
718
- if (animations.length === 0) return {
719
- animations,
720
- rules: ruleset,
721
- cacheKey: baseKey
722
- };
723
- return {
724
- animations,
725
- rules: ruleset.map((rule) => ({
726
- ...rule,
727
- declarations: replaceAnimationNames(rule.declarations, keyframeNames)
728
- })),
729
- cacheKey: `${baseKey}\u0000kf:${animations.map((authored) => `${authored}=${keyframeNames.get(authored)}`).sort().join(",")}`
730
- };
731
- }
732
- /**
733
- * Process a chunk on the client: render, allocate className, and inject
734
- * CSS synchronously. The injector's cache makes this idempotent.
735
- */
736
- function processChunkSync(styles, chunkName, styleKeys, stableStyles, root, keyframeNames) {
737
- if (styleKeys.length === 0) return null;
738
- const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys, stableStyles);
739
- const renderResult = renderStylesForChunk(styles, chunkName, styleKeys, cacheKey);
740
- if (renderResult.rules.length === 0) return null;
741
- const { animations, rules, cacheKey: injectKey } = applyKeyframeNames(renderResult.rules, cacheKey, keyframeNames);
742
- const { className } = inject(rules, {
743
- cacheKey: injectKey,
744
- root,
745
- pin: false
746
- });
747
- return {
748
- name: chunkName,
749
- styleKeys,
750
- cacheKey: injectKey,
751
- renderResult: {
752
- ...renderResult,
753
- rules
754
- },
755
- className,
756
- animations
757
- };
758
- }
759
- /**
760
- * Inject all ancillary rules (properties, font-faces, counter-styles) synchronously.
761
- */
762
- function injectAncillarySync(styles, root) {
763
- if (hasLocalProperties(styles)) {
764
- const localProperties = extractLocalProperties(styles);
765
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) property(token, {
766
- ...definition,
767
- root
768
- });
769
- }
770
- if (hasLocalFontFace(styles)) {
771
- const localFontFace = extractLocalFontFace(styles);
772
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
773
- const descriptors = Array.isArray(input) ? input : [input];
774
- for (const desc of descriptors) fontFace(family, desc, { root });
775
- }
776
- }
777
- if (hasLocalCounterStyle(styles)) {
778
- const localCounterStyle = extractLocalCounterStyle(styles);
779
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) counterStyle(name, descriptors, { root });
780
- }
781
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
782
- const localFunctions = extractLocalFunctions(styles);
783
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) func(name, definition, { root });
784
- }
785
- }
786
- /**
787
- * Collect all ancillary rules into the SSR collector.
788
- */
789
- function collectAncillarySSR(collector, styles, chunks) {
790
- const usedKf = getUsedKeyframes(styles);
791
- if (usedKf) {
792
- const names = resolveKeyframesNames(usedKf);
793
- for (const [authored, steps] of Object.entries(usedKf)) {
794
- const name = names.get(authored);
795
- collector.collectKeyframes(name, formatKeyframesCSS(name, steps));
796
- }
797
- }
798
- if (hasLocalProperties(styles)) {
799
- const localProperties = extractLocalProperties(styles);
800
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) {
801
- const css = formatPropertyCSS(token, definition);
802
- if (css) collector.collectProperty(token, css);
803
- }
804
- }
805
- if (hasLocalFontFace(styles)) {
806
- const localFontFace = extractLocalFontFace(styles);
807
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
808
- const descriptors = Array.isArray(input) ? input : [input];
809
- for (const desc of descriptors) {
810
- const hash = fontFaceContentHash(family, desc);
811
- const css = formatFontFaceRule(family, desc);
812
- collector.collectFontFace(hash, css);
813
- }
814
- }
815
- }
816
- if (hasLocalCounterStyle(styles)) {
817
- const localCounterStyle = extractLocalCounterStyle(styles);
818
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) {
819
- const css = formatCounterStyleRule(name, descriptors);
820
- collector.collectCounterStyle(name, css);
821
- }
822
- }
823
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
824
- const localFunctions = extractLocalFunctions(styles);
825
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) {
826
- const css = formatFunctionRule(name, definition);
827
- collector.collectFunction(parseFunctionName(name), css);
828
- }
829
- }
830
- if (getConfig().autoPropertyTypes !== false) {
831
- const allRules = chunks.flatMap((c) => c.renderResult.rules);
832
- if (allRules.length > 0) collectAutoInferredProperties(allRules, collector, styles);
833
- }
834
- }
835
- /**
836
- * Synchronous, hook-free style computation.
837
- *
838
- * Resolves recipes, categorizes style keys into chunks, renders CSS rules,
839
- * allocates class names, and injects / collects / returns the CSS.
840
- *
841
- * Three code paths:
842
- * 1. SSR collector — discovered via ALS or passed explicitly; CSS collected
843
- * 2. RSC inline — no collector and no `document`; CSS returned as `result.css`
844
- * for the caller to emit as an inline `<style>` tag
845
- * 3. Client inject — CSS injected synchronously into the DOM (idempotent)
846
- *
847
- * @param styles - Tasty styles object (or undefined for no styles)
848
- * @param options - Optional SSR collector override
849
- */
850
- function computeStyles(styles, options) {
851
- if (!styles || !hasKeys(styles)) return EMPTY_RESULT;
852
- const resolved = resolveRecipes(styles);
853
- const stableStyles = options?.stableStyles === true && resolved === styles;
854
- if (isFunctionsPolyfillEnabled() && hasLocalFunctions(resolved)) registerLocalFunctionPolyfills(resolved);
855
- const chunkMap = categorizeStyleKeys(resolved);
856
- const collector = options?.ssrCollector !== void 0 ? options.ssrCollector : getRegisteredSSRCollector();
857
- const chunks = [];
858
- if (collector) {
859
- collector.collectInternals();
860
- const ssrKf = getUsedKeyframes(resolved);
861
- const ssrKeyframeNames = ssrKf ? resolveKeyframesNames(ssrKf) : null;
862
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
863
- const chunk = processChunkSSR(collector, resolved, chunkName, chunkStyleKeys, stableStyles, ssrKeyframeNames);
864
- if (chunk) chunks.push(chunk);
865
- }
866
- collectAncillarySSR(collector, resolved, chunks);
867
- } else if (typeof document === "undefined") return computeStylesRSC(resolved, chunkMap, stableStyles);
868
- else {
869
- const root = options?.root;
870
- injectAncillarySync(resolved, root);
871
- const usedKf = getUsedKeyframes(resolved);
872
- const keyframeNames = usedKf ? resolveKeyframesNames(usedKf) : null;
873
- const keyframeKeys = usedKf && keyframeNames ? holdKeyframes(usedKf, keyframeNames, { root }) : null;
874
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
875
- const chunk = processChunkSync(resolved, chunkName, chunkStyleKeys, stableStyles, root, keyframeNames);
876
- if (chunk) chunks.push(chunk);
877
- }
878
- if (keyframeKeys) for (const chunk of chunks) for (const authored of chunk.animations ?? []) {
879
- const key = keyframeKeys.get(authored);
880
- if (key) ownKeyframes(key, chunk.className, { root });
881
- }
882
- for (const chunk of chunks) touch(chunk.className, { root });
883
- }
884
- if (chunks.length === 0) return EMPTY_RESULT;
885
- if (chunks.length === 1) return { className: chunks[0].className };
886
- return { className: chunks.map((c) => c.className).join(" ") };
887
- }
888
- //#endregion
889
- //#region src/utils/filter-base-props.ts
890
- const DOMPropNames = new Set(["id"]);
891
- const BasePropNames = new Set([
892
- "role",
893
- "as",
894
- "element",
895
- "css",
896
- "qa",
897
- "mods",
898
- "qaVal",
899
- "hidden",
900
- "isHidden",
901
- "disabled",
902
- "isDisabled",
903
- "children",
904
- "style",
905
- "className",
906
- "href",
907
- "target",
908
- "tabIndex"
909
- ]);
910
- const ignoreEventPropsNames = new Set([
911
- "onPress",
912
- "onHoverStart",
913
- "onHoverEnd",
914
- "onPressStart",
915
- "onPressEnd"
916
- ]);
917
- const propRe = /^((data-).*)$/;
918
- const eventRe = /^on[A-Z].+$/;
919
- /**
920
- * Filters out all props that aren't valid DOM props or defined via override prop obj.
921
- * @param props - The component props to be filtered.
922
- * @param opts - Props to override.
923
- */
924
- function filterBaseProps(props, opts = {}) {
925
- const { propNames, eventProps } = opts;
926
- const filteredProps = {};
927
- for (const prop in props) if (Object.prototype.hasOwnProperty.call(props, prop) && (DOMPropNames.has(prop) || BasePropNames.has(prop) || prop.startsWith("aria-") || eventProps && eventRe.test(prop) && !ignoreEventPropsNames.has(prop) || propNames?.has(prop) || propRe.test(prop))) filteredProps[prop] = props[prop];
928
- return filteredProps;
929
- }
930
- //#endregion
931
- //#region src/utils/colors.ts
932
- function color(name, opacity = 1) {
933
- if (opacity !== 1) return overrideColorAlpha(`var(--${name}-color)`, String(opacity));
934
- return `var(--${name}-color)`;
935
- }
936
- //#endregion
937
- //#region src/utils/cache-wrapper.ts
938
- /**
939
- * Create a function that caches the result with LRU eviction.
940
- */
941
- function cacheWrapper(handler, limit = 1e3) {
942
- const cache = new Lru(limit);
943
- return (firstArg, secondArg) => {
944
- const key = typeof firstArg === "string" && secondArg == null ? firstArg : JSON.stringify([firstArg, secondArg]);
945
- let result = cache.get(key);
946
- if (result === void 0) {
947
- result = secondArg == null ? handler(firstArg) : handler(firstArg, secondArg);
948
- cache.set(key, result);
949
- }
950
- return result;
951
- };
952
- }
953
- //#endregion
954
- //#region src/utils/mod-attrs.ts
955
- function modAttrs(map) {
956
- return map ? Object.keys(map).reduce((attrs, key) => {
957
- const value = map[key];
958
- if (value == null || value === false) return attrs;
959
- const attrName = `data-${camelToKebab(key)}`;
960
- if (value === true) attrs[attrName] = "";
961
- else if (typeof value === "string") attrs[attrName] = value;
962
- else if (typeof value === "number") attrs[attrName] = String(value);
963
- else console.warn(`[Tasty] Invalid mod value for "${key}". Expected boolean, string, or number, got ${typeof value}`);
964
- return attrs;
965
- }, {}) : null;
966
- }
967
- const _modAttrs = cacheWrapper(modAttrs);
968
- //#endregion
969
- //#region src/utils/dotize.ts
970
- const dotize = {
971
- valTypes: {
972
- none: "NONE",
973
- primitive: "PRIM",
974
- object: "OBJECT",
975
- array: "ARRAY"
976
- },
977
- getValType: function(val) {
978
- if (!val || typeof val != "object" || Array.isArray(val)) return dotize.valTypes.primitive;
979
- if (typeof val == "object") return dotize.valTypes.object;
980
- },
981
- getPathType: function(arrPath) {
982
- const arrPathTypes = [];
983
- for (const path in arrPath) {
984
- const pathVal = arrPath[path];
985
- if (!pathVal) arrPathTypes.push(dotize.valTypes.none);
986
- else if (dotize.isNumber(pathVal)) arrPathTypes.push(dotize.valTypes.array);
987
- else arrPathTypes.push(dotize.valTypes.object);
988
- }
989
- return arrPathTypes;
990
- },
991
- isUndefined: function(obj) {
992
- return typeof obj == "undefined";
993
- },
994
- isNumber: function(f) {
995
- return !isNaN(parseInt(f));
996
- },
997
- isEmptyObj: function(obj) {
998
- for (const prop in obj) if (Object.hasOwnProperty.call(obj, prop)) return false;
999
- return JSON.stringify(obj) === JSON.stringify({});
1000
- },
1001
- isPlainObject: function(obj) {
1002
- if (typeof obj !== "object" || obj === null) return false;
1003
- return Object.getPrototypeOf(obj) === Object.prototype;
1004
- },
1005
- isNotObject: function(obj) {
1006
- return !obj || !this.isPlainObject(obj);
1007
- },
1008
- isEmptyArray: function(arr) {
1009
- return Array.isArray(arr) && arr.length == 0;
1010
- },
1011
- isNotArray: function(arr) {
1012
- return Array.isArray(arr) == false;
1013
- },
1014
- removeEmptyArrayItem: function(arr) {
1015
- return arr.filter(function(el) {
1016
- return el != null && el != "";
1017
- });
1018
- },
1019
- getFieldName: function(field, prefix, isRoot, isArrayItem, isArray) {
1020
- if (isArray) return (prefix ? prefix : "") + (dotize.isNumber(field) ? "[" + field + "]" : (isRoot && !prefix ? "" : ".") + field);
1021
- else if (isArrayItem) return (prefix ? prefix : "") + "[" + field + "]";
1022
- else return (prefix ? prefix + "." : "") + field;
1023
- },
1024
- startsWith: function(val, valToSearch) {
1025
- return val.indexOf(valToSearch) == 0;
1026
- },
1027
- convert: function(obj, prefix = "") {
1028
- let newObj = {};
1029
- if (dotize.isNotObject(obj)) if (prefix) {
1030
- newObj[prefix] = obj;
1031
- return newObj;
1032
- } else return obj;
1033
- return (function recurse(o, p, isRoot) {
1034
- const isArrayItem = Array.isArray(o);
1035
- for (const f in o) {
1036
- const currentProp = o[f];
1037
- if (currentProp && typeof currentProp === "object" && !Array.isArray(currentProp) && dotize.isPlainObject(currentProp)) {
1038
- if (isArrayItem && dotize.isEmptyObj(currentProp) == false) newObj = recurse(currentProp, dotize.getFieldName(f, p, isRoot, true));
1039
- else if (dotize.isEmptyObj(currentProp) == false) newObj = recurse(currentProp, dotize.getFieldName(f, p, isRoot));
1040
- else if (dotize.isEmptyObj(currentProp)) newObj[dotize.getFieldName(f, p, isRoot, isArrayItem)] = currentProp;
1041
- } else if (isArrayItem || dotize.isNumber(f)) newObj[dotize.getFieldName(f, p, isRoot, true)] = currentProp;
1042
- else newObj[dotize.getFieldName(f, p, isRoot)] = currentProp;
1043
- }
1044
- return newObj;
1045
- })(obj, prefix, true);
1046
- },
1047
- backward: function(obj, prefix) {
1048
- let newObj = {};
1049
- const arStartRegex = /\[(\d+)\]/g;
1050
- if (dotize.isNotObject(obj) && dotize.isNotArray(obj)) if (prefix) return obj[prefix];
1051
- else return obj;
1052
- for (let tProp in obj) {
1053
- const tPropVal = obj[tProp];
1054
- if (prefix) {
1055
- const prefixRegex = new RegExp("^" + prefix);
1056
- tProp = tProp.replace(prefixRegex, "");
1057
- }
1058
- tProp = tProp.replace(arStartRegex, ".$1");
1059
- if (dotize.startsWith(tProp, ".")) tProp = tProp.replace(/^\./, "");
1060
- const arrPath = tProp.split(".");
1061
- const arrPathTypes = dotize.getPathType(arrPath);
1062
- if (!dotize.isUndefined(arrPathTypes) && arrPathTypes[0] == dotize.valTypes.array && Array.isArray(newObj) == false) newObj = [];
1063
- (function recurse(rPropVal, rObj, rPropValPrev, rObjPrev) {
1064
- let currentPath = arrPath.shift();
1065
- const currentPathType = arrPathTypes.shift();
1066
- if (typeof currentPath == "undefined" || currentPath == "") {
1067
- newObj = rPropVal;
1068
- return;
1069
- }
1070
- const isArray = currentPathType == dotize.valTypes.array;
1071
- if (dotize.isNumber(currentPath)) currentPath = parseInt(currentPath);
1072
- if (arrPath.length > 0) {
1073
- if (typeof rObj[currentPath] == "undefined") if (isArray) rObj[currentPath] = [];
1074
- else rObj[currentPath] = {};
1075
- recurse(rPropVal, rObj[currentPath], currentPath, rObj);
1076
- return;
1077
- }
1078
- if (currentPathType == dotize.valTypes.array && rPropValPrev && rObjPrev) {
1079
- if (Array.isArray(rObjPrev[rPropValPrev]) == false) rObjPrev[rPropValPrev] = [];
1080
- rObjPrev[rPropValPrev].push(rPropVal);
1081
- } else rObj[currentPath] = rPropVal;
1082
- })(tPropVal, newObj);
1083
- }
1084
- return newObj;
1085
- }
1086
- };
1087
- //#endregion
1088
- //#region src/utils/process-tokens.ts
1089
- /**
1090
- * Check if a value is a valid token value (string, number, or boolean - not object).
1091
- * Returns false for `false` values (they mean "skip this token").
1092
- */
1093
- function isValidTokenValue(value) {
1094
- if (value === void 0 || value === null || value === false) return false;
1095
- if (typeof value === "object") {
1096
- console.warn("[Tasty] Object values are not allowed in tokens prop. Tokens do not support state-based styling. Use a primitive value instead.");
1097
- return false;
1098
- }
1099
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1100
- }
1101
- /**
1102
- * Process a single token value through the tasty parser.
1103
- * Numbers are converted to strings; 0 stays as "0".
1104
- */
1105
- function processTokenValue(value) {
1106
- if (typeof value === "number") {
1107
- if (value === 0) return "0";
1108
- return parseStyle(String(value)).output;
1109
- }
1110
- return parseStyle(value).output;
1111
- }
1112
- /**
1113
- * Resolve one `$name` / `#name` entry to the custom property it declares and
1114
- * the value to declare, or `null` when the entry declares nothing.
1115
- *
1116
- * The two sigils differ only in the property name they build and in how `true`
1117
- * is read: for a custom property it is the empty value, for a color it is
1118
- * `transparent`.
1119
- */
1120
- function resolveTokenEntry(key, value) {
1121
- const name = `--${normalizeDslName(key.slice(1))}`;
1122
- if (key[0] === "$") return [name, processTokenValue(value === true ? "" : value)];
1123
- const colorValue = normalizeColorTokenValue(value);
1124
- if (colorValue === null) return null;
1125
- return [`${name}-color`, processTokenValue(colorValue)];
1126
- }
1127
- /**
1128
- * Process tokens object into inline style properties.
1129
- * - `$name` -> `--name` with the parsed value
1130
- * - `#name` -> `--name-color` with the parsed value
1131
- *
1132
- * @param tokens - The tokens object to process
1133
- * @returns CSSProperties object or undefined if no tokens to process
1134
- */
1135
- function processTokens(tokens) {
1136
- if (!tokens) return;
1137
- const keys = Object.keys(tokens);
1138
- if (keys.length === 0) return;
1139
- let result;
1140
- for (const key of keys) {
1141
- const value = tokens[key];
1142
- if (!isValidTokenValue(value)) continue;
1143
- if (key[0] !== "$" && key[0] !== "#") continue;
1144
- const entry = resolveTokenEntry(key, value);
1145
- if (!entry) continue;
1146
- if (!result) result = {};
1147
- result[entry[0]] = entry[1];
1148
- }
1149
- return result;
1150
- }
1151
- //#endregion
1152
- //#region src/debug.ts
1153
- function fmtSize(bytes) {
1154
- return bytes > 1024 ? `${(bytes / 1024).toFixed(1)}KB` : `${bytes}B`;
1155
- }
1156
- function countRules(css) {
1157
- return (css.match(/\{[^}]*\}/g) || []).length;
1158
- }
1159
- function sortTastyClasses(classes) {
1160
- return Array.from(classes).sort((a, b) => a.localeCompare(b));
1161
- }
1162
- /**
1163
- * The root these helpers read, or `null` where there is no DOM.
1164
- *
1165
- * `document` used to be a default parameter value, and a default is evaluated
1166
- * at the call site — so every read below threw a bare `ReferenceError` under
1167
- * Node, taking out five of the eight public methods. A debug utility must not
1168
- * be able to fail an SSR render because a call was left in, so the DOM-less
1169
- * case reports an empty result and says why.
1170
- */
1171
- function defaultRoot() {
1172
- return typeof document === "undefined" ? null : document;
1173
- }
1174
- let warnedNoDom = false;
1175
- /** Say once why the numbers are empty. Silent under `{ raw: true }`. */
1176
- function warnNoDom(raw) {
1177
- if (raw || warnedNoDom) return;
1178
- warnedNoDom = true;
1179
- console.warn("[Tasty] tastyDebug reads the DOM and this environment has none, so the result is empty. During SSR, read the ServerStyleCollector instead.");
1180
- }
1181
- /**
1182
- * The registry for `root`, with every queued write landed first.
1183
- *
1184
- * Every injector read API is a flush point, and the reads below reach past
1185
- * those APIs straight into the registry and the sheet manager. Without this
1186
- * they would report a batch window's contents as absent — a rule that is
1187
- * enqueued but not yet in a sheet is missing from `globalRules`, from the
1188
- * sheets, and from anything counting either.
1189
- */
1190
- function getRegistry(root = defaultRoot()) {
1191
- if (!root) return void 0;
1192
- flushStyles();
1193
- return injector.instance._sheetManager?.getRegistry(root);
1194
- }
1195
- function findDomTastyClasses(root = defaultRoot()) {
1196
- if (!root) return [];
1197
- const classes = /* @__PURE__ */ new Set();
1198
- const elements = root.querySelectorAll?.("[class]") || [];
1199
- const classRegex = tastyClassRegex(getNamePrefix());
1200
- elements.forEach((el) => {
1201
- const attr = el.getAttribute("class");
1202
- if (attr) {
1203
- for (const cls of attr.split(/\s+/)) if (classRegex.test(cls)) classes.add(cls);
1204
- }
1205
- });
1206
- return sortTastyClasses(classes);
1207
- }
1208
- /**
1209
- * Everything this injector holds in `root`, in the order the engine applies it,
1210
- * with the sources kept byte-for-byte — trimming would report a total smaller
1211
- * than one of its own parts whenever raw CSS has edge whitespace.
1212
- */
1213
- function getAllCSS(root = defaultRoot()) {
1214
- const registry = getRegistry(root);
1215
- const sheetManager = injector.instance._sheetManager;
1216
- if (!root || !registry || !sheetManager) return "";
1217
- return sheetManager.getOwnedCSSInOrder(registry, root).join("\n");
1218
- }
1219
- /**
1220
- * The injector's own readers fall back to `document` when `root` is omitted, so
1221
- * they have to be reached with a real root or not at all.
1222
- */
1223
- function cssTextForClasses(classNames, root) {
1224
- if (!root) return "";
1225
- return injector.instance.getCSSTextForClasses(classNames, { root });
1226
- }
1227
- function getInjectorMetrics(root) {
1228
- if (!root) return null;
1229
- return injector.instance.getMetrics({ root });
1230
- }
1231
- /**
1232
- * Injected classes that no element carries and nobody pinned — the exact set
1233
- * `gc({ force: true })` would delete.
1234
- *
1235
- * Deliberately borrowed from the injector rather than recomputed here: the two
1236
- * drifted apart once before, when this file still read "unused" off the pin
1237
- * counts the render path had stopped maintaining.
1238
- */
1239
- function getUnusedClasses(root = defaultRoot()) {
1240
- if (!root) return [];
1241
- return sortTastyClasses(injector.instance.getUnusedClasses({ root }));
1242
- }
1243
- /** Every class this injector holds CSS for in `root`. */
1244
- function getOwnedClasses(root = defaultRoot()) {
1245
- const registry = getRegistry(root);
1246
- if (!registry) return [];
1247
- const owned = [];
1248
- for (const [className, info] of registry.rules) if (info.sheetIndex >= 0) owned.push(className);
1249
- return sortTastyClasses(owned);
1250
- }
1251
- function prettifyCSS(css) {
1252
- if (!css || !css.trim()) return "";
1253
- const out = [];
1254
- let depth = 0;
1255
- const indent = () => " ".repeat(depth);
1256
- let normalized = css.replace(/\s+/g, " ").trim();
1257
- normalized = normalized.replace(/\s*\{\s*/g, " { ");
1258
- normalized = normalized.replace(/\s*\}\s*/g, " } ");
1259
- normalized = normalized.replace(/;\s*/g, "; ");
1260
- const tokens = normalized.split(/\s+/);
1261
- let buf = "";
1262
- for (const t of tokens) if (t === "{") {
1263
- const header = buf.trim();
1264
- if (header) {
1265
- const parts = splitOutsideParens(header, ",");
1266
- if (parts.length > 1) out.push(parts.map((p, idx) => idx === 0 ? `${indent()}${p.trim()},` : `${indent()}${p.trim()}${idx < parts.length - 1 ? "," : ""}`).join("\n") + " {");
1267
- else out.push(`${indent()}${header} {`);
1268
- } else out.push(`${indent()}{`);
1269
- depth++;
1270
- buf = "";
1271
- } else if (t === "}") {
1272
- if (buf.trim()) {
1273
- for (const decl of buf.split(";").filter((s) => s.trim())) out.push(`${indent()}${decl.trim()};`);
1274
- buf = "";
1275
- }
1276
- depth = Math.max(0, depth - 1);
1277
- out.push(`${indent()}}`);
1278
- } else if (t.endsWith(";")) {
1279
- buf += ` ${t}`;
1280
- const full = buf.trim();
1281
- if (full) out.push(`${indent()}${full}`);
1282
- buf = "";
1283
- } else buf += ` ${t}`;
1284
- if (buf.trim()) out.push(buf.trim());
1285
- return out.filter((l) => l.trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
1286
- }
1287
- /** Split `str` by `sep` only when not inside parentheses */
1288
- function splitOutsideParens(str, sep) {
1289
- const parts = [];
1290
- let depth = 0;
1291
- let start = 0;
1292
- for (let i = 0; i < str.length; i++) {
1293
- const ch = str[i];
1294
- if (ch === "(") depth++;
1295
- else if (ch === ")") depth--;
1296
- else if (depth === 0 && str.startsWith(sep, i)) {
1297
- parts.push(str.slice(start, i));
1298
- start = i + sep.length;
1299
- }
1300
- }
1301
- parts.push(str.slice(start));
1302
- return parts;
1303
- }
1304
- function extractChunkName(cacheKey) {
1305
- for (const part of cacheKey.split("\0")) {
1306
- if (part.startsWith("[states:")) continue;
1307
- if (!part.includes(":") && part.length > 0) return part;
1308
- }
1309
- return null;
1310
- }
1311
- function getChunkForClass(className, root = defaultRoot()) {
1312
- const registry = getRegistry(root);
1313
- if (!registry) return null;
1314
- for (const [key, cn] of registry.cacheKeyToClassName) if (cn === className) return extractChunkName(key);
1315
- return null;
1316
- }
1317
- function buildChunkBreakdown(root = defaultRoot()) {
1318
- const registry = getRegistry(root);
1319
- if (!root || !registry) return {
1320
- byChunk: {},
1321
- totalChunkTypes: 0,
1322
- totalClasses: 0
1323
- };
1324
- const byChunk = {};
1325
- for (const [cacheKey, className] of registry.cacheKeyToClassName) {
1326
- const chunk = extractChunkName(cacheKey) || "unknown";
1327
- if (!byChunk[chunk]) byChunk[chunk] = {
1328
- classes: [],
1329
- cssSize: 0,
1330
- ruleCount: 0
1331
- };
1332
- byChunk[chunk].classes.push(className);
1333
- const css = injector.instance.getCSSTextForClasses([className], { root });
1334
- byChunk[chunk].cssSize += css.length;
1335
- byChunk[chunk].ruleCount += countRules(css);
1336
- }
1337
- for (const entry of Object.values(byChunk)) entry.classes = sortTastyClasses(entry.classes);
1338
- const totalClasses = Object.values(byChunk).reduce((s, e) => s + e.classes.length, 0);
1339
- return {
1340
- byChunk,
1341
- totalChunkTypes: Object.keys(byChunk).length,
1342
- totalClasses
1343
- };
1344
- }
1345
- /**
1346
- * Every prefix `registry.globalRules` is keyed by. Anything missing here is a
1347
- * rule the summary would hold but never count, which is how the totals stopped
1348
- * adding up the first time.
1349
- */
1350
- const GLOBAL_RULE_PREFIXES = {
1351
- global: "global:",
1352
- property: "property:",
1353
- fontFace: "fontface:",
1354
- counterStyle: "counterstyle:",
1355
- function: "function:"
1356
- };
1357
- function getGlobalTypeCSS(type, root = defaultRoot()) {
1358
- const registry = getRegistry(root);
1359
- if (!root || !registry) return {
1360
- css: "",
1361
- ruleCount: 0,
1362
- size: 0
1363
- };
1364
- const chunks = [];
1365
- let rc = 0;
1366
- if (type === "raw") {
1367
- const css = injector.instance.getRawCSSText({ root });
1368
- const sheetManager = injector.instance._sheetManager;
1369
- return {
1370
- css: prettifyCSS(css),
1371
- ruleCount: sheetManager?.getRawRuleCount(root) ?? 0,
1372
- size: css.length
1373
- };
1374
- }
1375
- if (type === "keyframes") for (const [, entry] of registry.keyframesCache) {
1376
- const info = entry.info;
1377
- const sheetInfo = registry.sheets[info.sheetIndex];
1378
- const sm = injector.instance._sheetManager;
1379
- const ss = sheetInfo && sm ? sm.getCSSSheet(sheetInfo) : null;
1380
- if (ss && info.ruleIndex < ss.cssRules.length) {
1381
- const rule = ss.cssRules[info.ruleIndex];
1382
- if (rule) {
1383
- chunks.push(rule.cssText);
1384
- rc++;
1385
- }
1386
- } else if (info.cssText) {
1387
- chunks.push(info.cssText);
1388
- rc++;
1389
- }
1390
- }
1391
- else {
1392
- const prefix = GLOBAL_RULE_PREFIXES[type];
1393
- for (const [key, ri] of registry.globalRules) {
1394
- if (!key.startsWith(prefix)) continue;
1395
- const sheetInfo = registry.sheets[ri.sheetIndex];
1396
- const sm = injector.instance._sheetManager;
1397
- const ss = sheetInfo && sm ? sm.getCSSSheet(sheetInfo) : null;
1398
- if (ss) {
1399
- const start = Math.max(0, ri.ruleIndex);
1400
- const end = Math.min(ss.cssRules.length - 1, ri.endRuleIndex ?? ri.ruleIndex);
1401
- if (start >= 0 && end >= start && start < ss.cssRules.length) for (let i = start; i <= end; i++) {
1402
- const rule = ss.cssRules[i];
1403
- if (rule) {
1404
- chunks.push(rule.cssText);
1405
- rc++;
1406
- }
1407
- }
1408
- } else if (ri.cssText?.length) {
1409
- chunks.push(...ri.cssText);
1410
- rc += ri.cssText.length;
1411
- }
1412
- }
1413
- }
1414
- const raw = chunks.join("\n");
1415
- return {
1416
- css: prettifyCSS(raw),
1417
- ruleCount: rc,
1418
- size: raw.length
1419
- };
1420
- }
1421
- function getSourceCssForClasses(classNames, root = defaultRoot()) {
1422
- const registry = getRegistry(root);
1423
- if (!registry) return null;
1424
- const chunks = [];
1425
- let found = false;
1426
- for (const cls of classNames) {
1427
- const info = registry.rules.get(cls);
1428
- if (info?.cssText?.length) {
1429
- chunks.push(...info.cssText);
1430
- found = true;
1431
- }
1432
- }
1433
- return found ? chunks.join("\n") : null;
1434
- }
1435
- function getDefs(root = defaultRoot()) {
1436
- const registry = getRegistry(root);
1437
- let properties = [];
1438
- if (registry?.injectedProperties) properties = Array.from(registry.injectedProperties.keys()).sort();
1439
- const keyframes = [];
1440
- if (registry) {
1441
- for (const entry of registry.keyframesCache.values()) keyframes.push({
1442
- name: entry.name,
1443
- refCount: entry.refCount
1444
- });
1445
- keyframes.sort((a, b) => a.name.localeCompare(b.name));
1446
- }
1447
- return {
1448
- properties,
1449
- keyframes
1450
- };
1451
- }
1452
- const CHUNK_ORDER = [
1453
- CHUNK_NAMES.COMBINED,
1454
- CHUNK_NAMES.APPEARANCE,
1455
- CHUNK_NAMES.FONT,
1456
- CHUNK_NAMES.DIMENSION,
1457
- CHUNK_NAMES.DISPLAY,
1458
- CHUNK_NAMES.LAYOUT,
1459
- CHUNK_NAMES.POSITION,
1460
- CHUNK_NAMES.MISC,
1461
- CHUNK_NAMES.SUBCOMPONENTS
1462
- ];
1463
- const tastyDebug = {
1464
- css(target, opts) {
1465
- const { root = defaultRoot(), prettify = true, raw = false, source = false } = opts || {};
1466
- if (!root) {
1467
- warnNoDom(raw);
1468
- return "";
1469
- }
1470
- let css = "";
1471
- const classRegex = tastyClassRegex(getNamePrefix());
1472
- if (source && typeof target === "string" && classRegex.test(target)) {
1473
- const src = getSourceCssForClasses([target], root);
1474
- if (src) css = src;
1475
- else {
1476
- if (!raw) console.warn("[Tasty] source CSS not available (requires dev mode or TASTY_DEBUG=true). Falling back to live CSSOM.");
1477
- css = injector.instance.getCSSTextForClasses([target], { root });
1478
- }
1479
- } else if (source && Array.isArray(target)) {
1480
- const src = getSourceCssForClasses(target, root);
1481
- if (src) css = src;
1482
- else {
1483
- if (!raw) console.warn("[Tasty] source CSS not available. Falling back to live CSSOM.");
1484
- css = injector.instance.getCSSTextForClasses(target, { root });
1485
- }
1486
- } else if (typeof target === "string") if (target === "all") css = getAllCSS(root);
1487
- else if (target === "global") {
1488
- css = getGlobalTypeCSS("global", root).css;
1489
- return css;
1490
- } else if (target === "active") {
1491
- const active = findDomTastyClasses(root);
1492
- css = injector.instance.getCSSTextForClasses(active, { root });
1493
- } else if (target === "unused") {
1494
- const unused = getUnusedClasses(root);
1495
- css = injector.instance.getCSSTextForClasses(unused, { root });
1496
- } else if (target === "page") css = getPageCSS(root);
1497
- else if (classRegex.test(target)) css = injector.instance.getCSSTextForClasses([target], { root });
1498
- else {
1499
- const el = root.querySelector?.(target);
1500
- if (el) css = getCSSTextForNode(el, { root });
1501
- }
1502
- else if (Array.isArray(target)) css = injector.instance.getCSSTextForClasses(target, { root });
1503
- else if (target instanceof Element) css = getCSSTextForNode(target, { root });
1504
- const result = prettify ? prettifyCSS(css) : css;
1505
- if (!raw) {
1506
- const label = Array.isArray(target) ? `[${target.join(", ")}]` : target;
1507
- const rc = countRules(css);
1508
- console.group(`CSS for ${label} (${rc} rules, ${fmtSize(css.length)})`);
1509
- console.log(result || "(empty)");
1510
- console.groupEnd();
1511
- }
1512
- return result;
1513
- },
1514
- inspect(target, opts) {
1515
- const { root = defaultRoot(), raw = false } = opts || {};
1516
- const element = !root ? null : typeof target === "string" ? root.querySelector?.(target) : target;
1517
- if (!root) warnNoDom(raw);
1518
- if (!element) {
1519
- const empty = {
1520
- element: null,
1521
- classes: [],
1522
- chunks: [],
1523
- css: "",
1524
- size: 0,
1525
- rules: 0
1526
- };
1527
- if (!raw && root) console.warn("[Tasty] debug.inspect: element not found");
1528
- return empty;
1529
- }
1530
- const classList = element.getAttribute("class") || "";
1531
- const classRegex = tastyClassRegex(getNamePrefix());
1532
- const tastyClasses = classList.split(/\s+/).filter((cls) => classRegex.test(cls));
1533
- const chunks = tastyClasses.map((className) => ({
1534
- className,
1535
- chunkName: getChunkForClass(className, root)
1536
- }));
1537
- const css = getCSSTextForNode(element, { root: root ?? void 0 });
1538
- const rules = countRules(css);
1539
- const result = {
1540
- element,
1541
- classes: tastyClasses,
1542
- chunks,
1543
- css: prettifyCSS(css),
1544
- size: css.length,
1545
- rules
1546
- };
1547
- if (!raw) {
1548
- const tag = element.tagName.toLowerCase();
1549
- const id = element.id ? `#${element.id}` : "";
1550
- console.group(`inspect ${tag}${id} — ${tastyClasses.length} classes, ${rules} rules, ${fmtSize(css.length)}`);
1551
- if (chunks.length) console.log("Chunks:", chunks.map((c) => `${c.className}→${c.chunkName || "?"}`).join(", "));
1552
- console.groupCollapsed("CSS");
1553
- console.log(result.css || "(empty)");
1554
- console.groupEnd();
1555
- console.groupEnd();
1556
- }
1557
- return result;
1558
- },
1559
- summary(opts) {
1560
- const { root = defaultRoot(), raw = false } = opts || {};
1561
- if (!root) warnNoDom(raw);
1562
- const activeClasses = findDomTastyClasses(root);
1563
- const unusedClasses = getUnusedClasses(root);
1564
- const ownedClasses = getOwnedClasses(root);
1565
- const totalStyledClasses = sortTastyClasses(new Set([...activeClasses, ...ownedClasses]));
1566
- const unusedSet = new Set(unusedClasses);
1567
- const activeSet = new Set(activeClasses);
1568
- const hotClasses = ownedClasses.filter((className) => !activeSet.has(className) && !unusedSet.has(className));
1569
- const hotCSS = cssTextForClasses(hotClasses, root);
1570
- const activeCSS = cssTextForClasses(activeClasses, root);
1571
- const unusedCSS = cssTextForClasses(unusedClasses, root);
1572
- const allCSS = getAllCSS(root);
1573
- const activeRuleCount = countRules(activeCSS);
1574
- const unusedRuleCount = countRules(unusedCSS);
1575
- const globalData = getGlobalTypeCSS("global", root);
1576
- const rawData = getGlobalTypeCSS("raw", root);
1577
- const kfData = getGlobalTypeCSS("keyframes", root);
1578
- const propData = getGlobalTypeCSS("property", root);
1579
- const atRuleData = [
1580
- "fontFace",
1581
- "counterStyle",
1582
- "function"
1583
- ].reduce((all, type) => {
1584
- const data = getGlobalTypeCSS(type, root);
1585
- return {
1586
- css: data.css ? `${all.css}\n${data.css}`.trim() : all.css,
1587
- ruleCount: all.ruleCount + data.ruleCount,
1588
- size: all.size + data.size
1589
- };
1590
- }, {
1591
- css: "",
1592
- ruleCount: 0,
1593
- size: 0
1594
- });
1595
- const totalRuleCount = activeRuleCount + unusedRuleCount + countRules(hotCSS) + globalData.ruleCount + atRuleData.ruleCount + rawData.ruleCount + kfData.ruleCount + propData.ruleCount;
1596
- const metrics = getInjectorMetrics(root);
1597
- const defs = getDefs(root);
1598
- const chunkBreakdown = buildChunkBreakdown(root);
1599
- const summary = {
1600
- activeClasses,
1601
- unusedClasses,
1602
- hotClasses,
1603
- totalStyledClasses,
1604
- activeCSSSize: activeCSS.length,
1605
- unusedCSSSize: unusedCSS.length,
1606
- globalCSSSize: globalData.size + atRuleData.size,
1607
- rawCSSSize: rawData.size,
1608
- keyframesCSSSize: kfData.size,
1609
- propertyCSSSize: propData.size,
1610
- totalCSSSize: allCSS.length,
1611
- activeRuleCount,
1612
- unusedRuleCount,
1613
- globalRuleCount: globalData.ruleCount + atRuleData.ruleCount,
1614
- rawRuleCount: rawData.ruleCount,
1615
- keyframesRuleCount: kfData.ruleCount,
1616
- propertyRuleCount: propData.ruleCount,
1617
- totalRuleCount,
1618
- metrics,
1619
- definedProperties: defs.properties,
1620
- definedKeyframes: defs.keyframes,
1621
- chunkBreakdown
1622
- };
1623
- if (!raw) {
1624
- console.group("Tasty Summary");
1625
- console.log(`Active: ${activeClasses.length} classes, ${activeRuleCount} rules, ${fmtSize(activeCSS.length)}`);
1626
- console.log(`Unused: ${unusedClasses.length} classes, ${unusedRuleCount} rules, ${fmtSize(unusedCSS.length)}`);
1627
- if (hotClasses.length) console.log(`Held: ${hotClasses.length} classes, ${countRules(hotCSS)} rules, ${fmtSize(hotCSS.length)} (not rendered, not yet collectable)`);
1628
- console.log(`Global: ${globalData.ruleCount + atRuleData.ruleCount} rules, ${fmtSize(globalData.size + atRuleData.size)}`);
1629
- if (rawData.ruleCount) console.log(`Raw: ${rawData.ruleCount} rules, ${fmtSize(rawData.size)}`);
1630
- if (kfData.ruleCount) console.log(`Keyframes: ${kfData.ruleCount} rules, ${fmtSize(kfData.size)}`);
1631
- if (propData.ruleCount) console.log(`@property: ${propData.ruleCount} rules, ${fmtSize(propData.size)}`);
1632
- console.log(`Total: ${totalStyledClasses.length} classes, ${totalRuleCount} rules, ${fmtSize(allCSS.length)}`);
1633
- if (metrics) {
1634
- const total = metrics.hits + metrics.misses;
1635
- const rate = total > 0 ? (metrics.hits / total * 100).toFixed(1) : 0;
1636
- console.log(`Cache: ${rate}% hit rate (${total} lookups)`);
1637
- }
1638
- if (chunkBreakdown.totalChunkTypes > 0) {
1639
- console.groupCollapsed(`Chunks (${chunkBreakdown.totalChunkTypes} types, ${chunkBreakdown.totalClasses} classes)`);
1640
- for (const name of CHUNK_ORDER) {
1641
- const d = chunkBreakdown.byChunk[name];
1642
- if (d) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1643
- }
1644
- for (const [name, d] of Object.entries(chunkBreakdown.byChunk)) if (!CHUNK_ORDER.includes(name)) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1645
- console.groupEnd();
1646
- }
1647
- if (defs.properties.length || defs.keyframes.length) console.log(`Defs: ${defs.properties.length} @property, ${defs.keyframes.length} @keyframes`);
1648
- console.groupEnd();
1649
- }
1650
- return summary;
1651
- },
1652
- chunks(opts) {
1653
- const { root = defaultRoot(), raw = false } = opts || {};
1654
- if (!root) warnNoDom(raw);
1655
- const breakdown = buildChunkBreakdown(root);
1656
- if (!raw) {
1657
- console.group(`Chunks (${breakdown.totalChunkTypes} types, ${breakdown.totalClasses} classes)`);
1658
- for (const name of CHUNK_ORDER) {
1659
- const d = breakdown.byChunk[name];
1660
- if (d) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1661
- }
1662
- for (const [name, d] of Object.entries(breakdown.byChunk)) if (!CHUNK_ORDER.includes(name)) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1663
- console.groupEnd();
1664
- }
1665
- return breakdown;
1666
- },
1667
- cache(opts) {
1668
- const { root = defaultRoot(), raw = false } = opts || {};
1669
- if (!root) warnNoDom(raw);
1670
- const active = findDomTastyClasses(root);
1671
- const unused = getUnusedClasses(root);
1672
- const metrics = getInjectorMetrics(root);
1673
- const status = {
1674
- classes: {
1675
- active,
1676
- unused,
1677
- all: sortTastyClasses(new Set([...active, ...getOwnedClasses(root)]))
1678
- },
1679
- metrics
1680
- };
1681
- if (!raw) {
1682
- console.group("Cache");
1683
- console.log(`Active: ${active.length}, Unused: ${unused.length}`);
1684
- if (metrics) {
1685
- const total = metrics.hits + metrics.misses;
1686
- const rate = total > 0 ? (metrics.hits / total * 100).toFixed(1) : 0;
1687
- console.log(`Hits: ${metrics.hits}, Misses: ${metrics.misses}, Rate: ${rate}%`);
1688
- }
1689
- console.groupEnd();
1690
- }
1691
- return status;
1692
- },
1693
- cleanup(opts) {
1694
- const root = opts?.root ?? defaultRoot();
1695
- if (!root) return;
1696
- injector.instance.cleanup(root);
1697
- },
1698
- help() {
1699
- console.log(`tastyDebug API:
1700
- .summary() — overview (classes, rules, sizes)
1701
- .css("active") — CSS for classes in DOM
1702
- .css("t42") — CSS for a specific class
1703
- .css("t42",{source:1})— original CSS before browser parsing (dev only)
1704
- .css(".selector") — CSS for a DOM element
1705
- .inspect(".selector") — element details (classes, chunks, rules)
1706
- .chunks() — style chunk breakdown
1707
- .cache() — cache status and metrics
1708
- .cleanup() — force unused style cleanup
1709
- Options: { raw: true } suppresses logging, { root: shadowRoot } targets Shadow DOM`);
1710
- },
1711
- install() {
1712
- if (typeof window !== "undefined" && window.tastyDebug !== tastyDebug) {
1713
- window.tastyDebug = tastyDebug;
1714
- console.log("tastyDebug installed. Run tastyDebug.help() for commands.");
1715
- }
1716
- }
1717
- };
1718
- function getPageCSS(root = defaultRoot()) {
1719
- if (!root) return "";
1720
- const chunks = [];
1721
- try {
1722
- if ("styleSheets" in root) for (const sheet of Array.from(root.styleSheets)) try {
1723
- if (sheet.cssRules) chunks.push(Array.from(sheet.cssRules).map((r) => r.cssText).join("\n"));
1724
- } catch {}
1725
- } catch {}
1726
- return chunks.join("\n");
1727
- }
1728
- if (typeof window !== "undefined" && isDevEnv()) tastyDebug.install();
1729
- //#endregion
1730
- export { keyframes as A, getRawCSSText as C, injectRawCSS as D, injectGlobal as E, chunkSheetRegistry as F, resolveFunctionColor as I, property as M, touch as N, injector as O, ChunkSheetRegistry as P, getCSSTextForNode as S, inject as T, destroy as _, color as a, gc as b, hasKeys as c, collectAutoInferredPropertiesRSC as d, getStyleTarget as f, createInjector as g, counterStyle as h, _modAttrs as i, ownKeyframes as j, isPropertyDefined as k, formatKeyframesCSS as l, cleanup as m, processTokens as n, filterBaseProps as o, pushRSCCSS as p, dotize as r, computeStyles as s, tastyDebug as t, collectAutoInferredProperties as u, fontFace as v, holdKeyframes as w, getCSSText as x, func as y };
1731
-
1732
- //# sourceMappingURL=core-DoEZAHJq.js.map