@tenphi/tasty 3.7.0 → 3.9.0

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 (103) hide show
  1. package/dist/{babel-DWCsafYw.d.ts → babel-Zs1Q03qt.d.ts} +2 -2
  2. package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
  3. package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
  4. package/dist/chunks/build-config-CUQVwdWF.js +42 -0
  5. package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
  6. package/dist/{collector-B3OsM252.js → chunks/collector-B0LTHw6Z.js} +6 -125
  7. package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
  8. package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
  9. package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
  10. package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
  11. package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
  12. package/dist/{css-resources-Cyl_axbI.js → chunks/css-resources-BN8apgxt.js} +1 -8
  13. package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
  14. package/dist/chunks/debug-C9LeNVoJ.js +501 -0
  15. package/dist/chunks/debug-C9LeNVoJ.js.map +1 -0
  16. package/dist/chunks/dsl-C5yuAn41.js +1373 -0
  17. package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
  18. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  19. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  20. package/dist/chunks/react-runtime-O-OUrKLH.js +557 -0
  21. package/dist/chunks/react-runtime-O-OUrKLH.js.map +1 -0
  22. package/dist/chunks/runtime-engine-DvnE2g-E.js +2437 -0
  23. package/dist/chunks/runtime-engine-DvnE2g-E.js.map +1 -0
  24. package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
  25. package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
  26. package/dist/{merge-styles-DuoZEsm9.js → chunks/shared-utils-DWA4LjIa.js} +55 -54
  27. package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
  28. package/dist/chunks/style-engine-C1ECBZxR.js +5131 -0
  29. package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
  30. package/dist/{css-writer-Bgowobbx.js → chunks/zero-engine-B6EnYcXY.js} +3 -120
  31. package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
  32. package/dist/{collector-BTVXj2hS.d.ts → collector-hl5KNH7k.d.ts} +6 -4
  33. package/dist/{config-LfIDmVHx.d.ts → config-DWL1ZYue.d.ts} +20 -25
  34. package/dist/core/index.d.ts +5 -5
  35. package/dist/core/index.js +9 -6
  36. package/dist/{index-Bm9ltvdH.d.ts → index-D9N9GV24.d.ts} +96 -82
  37. package/dist/index.d.ts +5 -5
  38. package/dist/index.js +11 -922
  39. package/dist/{merge-styles-BcLl1u_d.d.ts → merge-styles-C_oMoJVd.d.ts} +2 -2
  40. package/dist/ssr/astro-client.js +1 -14
  41. package/dist/ssr/astro-client.js.map +1 -1
  42. package/dist/ssr/astro-middleware-extract-static.js +1 -1
  43. package/dist/ssr/astro-middleware-extract.js +1 -1
  44. package/dist/ssr/astro-middleware-static.js +1 -12
  45. package/dist/ssr/astro-middleware-static.js.map +1 -1
  46. package/dist/ssr/astro-middleware.js +1 -13
  47. package/dist/ssr/astro-middleware.js.map +1 -1
  48. package/dist/ssr/astro.js +219 -1
  49. package/dist/ssr/astro.js.map +1 -0
  50. package/dist/ssr/index.d.ts +6 -6
  51. package/dist/ssr/index.js +4 -4
  52. package/dist/ssr/next-config.d.ts +1 -1
  53. package/dist/ssr/next-config.js +29 -20
  54. package/dist/ssr/next-config.js.map +1 -1
  55. package/dist/ssr/next.d.ts +1 -1
  56. package/dist/ssr/next.js +5 -37
  57. package/dist/ssr/next.js.map +1 -1
  58. package/dist/static/index.d.ts +2 -2
  59. package/dist/static/index.js +1 -19
  60. package/dist/static/index.js.map +1 -1
  61. package/dist/{index-BmogEzTo.d.ts → types-jKZNpias.d.ts} +845 -804
  62. package/dist/zero/babel.d.ts +1 -1
  63. package/dist/zero/babel.js +25 -96
  64. package/dist/zero/babel.js.map +1 -1
  65. package/dist/zero/index.d.ts +1 -1
  66. package/dist/zero/index.js +1 -1
  67. package/dist/zero/next.d.ts +1 -1
  68. package/dist/zero/next.js +0 -31
  69. package/dist/zero/next.js.map +1 -1
  70. package/docs/ai-agents.md +8 -3
  71. package/docs/debug.md +2 -5
  72. package/docs/methodology.md +3 -3
  73. package/docs/pipeline.md +3 -0
  74. package/docs/runtime-benchmarks.md +105 -68
  75. package/docs/styles.md +43 -11
  76. package/package.json +48 -5
  77. package/dist/astro-CeYENy2x.js +0 -301
  78. package/dist/astro-CeYENy2x.js.map +0 -1
  79. package/dist/async-storage-DKK-wTD4.js +0 -44
  80. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  81. package/dist/collector-B3OsM252.js.map +0 -1
  82. package/dist/config-B3gPdCqd.js +0 -12421
  83. package/dist/config-B3gPdCqd.js.map +0 -1
  84. package/dist/context-CA8YKeMn.js +0 -24
  85. package/dist/context-CA8YKeMn.js.map +0 -1
  86. package/dist/core-DGm0CFHP.js +0 -1732
  87. package/dist/core-DGm0CFHP.js.map +0 -1
  88. package/dist/css-resources-Cyl_axbI.js.map +0 -1
  89. package/dist/css-writer-Bgowobbx.js.map +0 -1
  90. package/dist/format-global-rules-DklyaXv-.js +0 -22
  91. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  92. package/dist/format-rules-XRw9u7d4.js +0 -104
  93. package/dist/format-rules-XRw9u7d4.js.map +0 -1
  94. package/dist/hydrate-CNOmZprz.js +0 -37
  95. package/dist/hydrate-CNOmZprz.js.map +0 -1
  96. package/dist/index.js.map +0 -1
  97. package/dist/keyframes-DE-OE76F.js +0 -535
  98. package/dist/keyframes-DE-OE76F.js.map +0 -1
  99. package/dist/merge-styles-DuoZEsm9.js.map +0 -1
  100. package/dist/resolve-recipes-H9NqOQuP.js +0 -144
  101. package/dist/resolve-recipes-H9NqOQuP.js.map +0 -1
  102. package/dist/ssr-collector-ref-COs_ioWl.js +0 -29
  103. package/dist/ssr-collector-ref-COs_ioWl.js.map +0 -1
@@ -1,535 +0,0 @@
1
- import { At as STYLE_TO_CHUNK, F as hasPipelineCacheEntry, H as extractPredefinedStateRefs, I as isSelector, L as renderStyles, V as extractLocalPredefinedStates, _t as hashString, wt as CHUNK_NAMES } from "./config-B3gPdCqd.js";
2
- //#region src/chunks/definitions.ts
3
- /**
4
- * Style chunk definitions for CSS chunking optimization.
5
- *
6
- * Styles are grouped into chunks based on:
7
- * 1. Handler dependencies - styles that share a handler MUST be in the same chunk
8
- * 2. Logical grouping - related styles grouped for better cache reuse
9
- *
10
- * See STYLE_CHUNKING_SPEC.md for detailed rationale.
11
- *
12
- * ============================================================================
13
- * ⚠️ CRITICAL ARCHITECTURAL CONSTRAINT: NO CROSS-CHUNK HANDLER DEPENDENCIES
14
- * ============================================================================
15
- *
16
- * Style handlers declare their dependencies via `__lookupStyles` array.
17
- * This creates a dependency graph where handlers read multiple style props.
18
- *
19
- * **ALL styles in a handler's `__lookupStyles` MUST be in the SAME chunk.**
20
- *
21
- * Why this matters:
22
- * 1. Each chunk computes a cache key from ONLY its own style values
23
- * 2. If a handler reads a style from another chunk, that value isn't in the cache key
24
- * 3. Changing the cross-chunk style won't invalidate this chunk's cache
25
- * 4. Result: stale CSS output or incorrect cache hits
26
- *
27
- * Example of a violation:
28
- * ```
29
- * // flowStyle.__lookupStyles = ['display', 'flow']
30
- * // If 'display' is in DISPLAY chunk and 'flow' is in LAYOUT chunk:
31
- * // - User sets { display: 'grid', flow: 'column' }
32
- * // - LAYOUT chunk caches CSS with flow=column, display=grid
33
- * // - User changes to { display: 'flex', flow: 'column' }
34
- * // - LAYOUT chunk cache key unchanged (only has 'flow')
35
- * // - Returns stale CSS computed with display=grid!
36
- * ```
37
- *
38
- * Before adding/moving styles, verify:
39
- * 1. Find all handlers that use this style (grep for the style name in __lookupStyles)
40
- * 2. Ensure ALL styles from each handler's __lookupStyles are in the same chunk
41
- *
42
- * For **custom** handlers registered through `configure({ handlers })` this is no
43
- * longer only a convention: `alignHandlerChunks()` in `styles/predefined.ts` pulls
44
- * any style name the lists below don't know into its handler's existing chunk, and
45
- * warns when a handler bridges two chunks defined here. The lists below are still
46
- * hand-maintained, so the constraint must be checked by hand when editing them.
47
- * ============================================================================
48
- */
49
- /**
50
- * Chunk processing order. This ensures deterministic className allocation
51
- * regardless of style key order in the input.
52
- */
53
- const CHUNK_ORDER = [
54
- CHUNK_NAMES.APPEARANCE,
55
- CHUNK_NAMES.FONT,
56
- CHUNK_NAMES.DIMENSION,
57
- CHUNK_NAMES.DISPLAY,
58
- CHUNK_NAMES.LAYOUT,
59
- CHUNK_NAMES.POSITION,
60
- CHUNK_NAMES.MISC,
61
- CHUNK_NAMES.SUBCOMPONENTS
62
- ];
63
- new Map(CHUNK_ORDER.map((name, index) => [name, index]));
64
- /**
65
- * Categorize style keys into chunks.
66
- *
67
- * Returns chunks in a deterministic order (by CHUNK_ORDER) regardless
68
- * of the order of keys in the input styles object.
69
- *
70
- * @param styles - The styles object to categorize
71
- * @returns Map of chunk name to array of style keys in that chunk (in priority order)
72
- */
73
- function categorizeStyleKeys(styles) {
74
- const chunkData = {};
75
- const keys = Object.keys(styles);
76
- for (const key of keys) {
77
- if (key === "$" || key === "@keyframes" || key === "@property" || key === "@font-face" || key === "@counter-style" || key === "@function" || key === "recipe") continue;
78
- if (isSelector(key)) {
79
- if (!chunkData[CHUNK_NAMES.SUBCOMPONENTS]) chunkData[CHUNK_NAMES.SUBCOMPONENTS] = [];
80
- chunkData[CHUNK_NAMES.SUBCOMPONENTS].push(key);
81
- } else {
82
- const chunkName = STYLE_TO_CHUNK.get(key) ?? CHUNK_NAMES.MISC;
83
- if (!chunkData[chunkName]) chunkData[chunkName] = [];
84
- chunkData[chunkName].push(key);
85
- }
86
- }
87
- const orderedChunks = /* @__PURE__ */ new Map();
88
- for (const chunkName of CHUNK_ORDER) if (chunkData[chunkName] && chunkData[chunkName].length > 0) orderedChunks.set(chunkName, chunkData[chunkName].sort());
89
- for (const chunkName of Object.keys(chunkData)) if (!orderedChunks.has(chunkName)) orderedChunks.set(chunkName, chunkData[chunkName].sort());
90
- return orderedChunks;
91
- }
92
- //#endregion
93
- //#region src/chunks/cacheKey.ts
94
- /**
95
- * Chunk-specific cache key generation.
96
- *
97
- * Generates cache keys that only include styles relevant to a specific chunk,
98
- * enabling more granular caching and reuse.
99
- *
100
- * Enhanced to support predefined states:
101
- * - Global predefined states don't affect cache keys (constant across app)
102
- * - Local predefined states only affect cache keys if referenced in the chunk
103
- */
104
- const _stableStringifyCache = /* @__PURE__ */ new WeakMap();
105
- /**
106
- * Per-styles-object memo of generated keys, keyed by chunk name.
107
- *
108
- * Reading from this is free, so every call checks it. Writing to it is not:
109
- * the `WeakMap.set` plus the snapshot allocation measured ~35% of the cost of
110
- * generating a key from scratch, and it is pure waste for a styles object that
111
- * is never seen again. Callers therefore have to opt in via `reusable`, and
112
- * only for an object they know outlives the render that produced it.
113
- *
114
- * `Styles` is a plain mutable object, and nothing in the public
115
- * `computeStyles` / `useStyles` contract asks callers to freeze it, so a hit is
116
- * only returned after re-reading every value the key was built from and
117
- * confirming none of them changed. That check is deliberately shallow: it
118
- * compares the same references `stableStringify` would have looked up in
119
- * `_stableStringifyCache`, so a memoized key is stale in exactly the cases the
120
- * un-memoized function was already stale in — an object-valued style mutated
121
- * in place — and in no others.
122
- */
123
- const _chunkKeyCache = /* @__PURE__ */ new WeakMap();
124
- /**
125
- * Is `entry` still a valid key for this chunk of `styles`?
126
- *
127
- * True only when the chunk asks for the same style keys, in the same order,
128
- * and every one of them still reads back the value the key was built from.
129
- */
130
- function isEntryFresh(styles, entry, styleKeys) {
131
- const snapshot = entry.snapshot;
132
- const length = styleKeys.length;
133
- if (snapshot.length !== length * 2) return false;
134
- for (let i = 0, at = 0; i < length; i++, at += 2) {
135
- const key = styleKeys[i];
136
- if (snapshot[at] !== key) return false;
137
- if (styles[key] !== snapshot[at + 1]) return false;
138
- }
139
- return true;
140
- }
141
- /**
142
- * Recursively serialize a value with sorted keys for stable output.
143
- * This ensures that {a: 1, b: 2} and {b: 2, a: 1} produce the same string.
144
- * Uses a WeakMap cache for object values to avoid re-serializing the same references.
145
- */
146
- function stableStringify(value) {
147
- if (value === null) return "null";
148
- if (value === void 0) return "undefined";
149
- if (typeof value !== "object") return JSON.stringify(value);
150
- const cached = _stableStringifyCache.get(value);
151
- if (cached !== void 0) return cached;
152
- let result;
153
- if (Array.isArray(value)) result = "[" + value.map(stableStringify).join(",") + "]";
154
- else {
155
- const obj = value;
156
- const sortedKeys = Object.keys(obj).sort();
157
- const parts = [];
158
- for (const key of sortedKeys) if (obj[key] !== void 0) parts.push(`${JSON.stringify(key)}:${stableStringify(obj[key])}`);
159
- result = "{" + parts.join(",") + "}";
160
- }
161
- _stableStringifyCache.set(value, result);
162
- return result;
163
- }
164
- function computeChunkCacheKey(styles, chunkName, snapshot) {
165
- const parts = [chunkName];
166
- let chunkStylesStr = "";
167
- for (let at = 0; at < snapshot.length; at += 2) {
168
- const value = snapshot[at + 1];
169
- if (value !== void 0) {
170
- const serialized = stableStringify(value);
171
- parts.push(`${snapshot[at]}:${serialized}`);
172
- chunkStylesStr += serialized;
173
- }
174
- }
175
- const localStates = extractLocalPredefinedStates(styles);
176
- if (Object.keys(localStates).length > 0) {
177
- const referencedStates = extractPredefinedStateRefs(chunkStylesStr);
178
- const relevantLocalStates = [];
179
- for (const stateName of referencedStates) if (localStates[stateName]) relevantLocalStates.push(`${stateName}=${localStates[stateName]}`);
180
- if (relevantLocalStates.length > 0) {
181
- relevantLocalStates.sort();
182
- parts.unshift(`[states:${relevantLocalStates.join("|")}]`);
183
- }
184
- }
185
- return parts.join("\0");
186
- }
187
- /**
188
- * Generate a cache key for a specific chunk.
189
- *
190
- * Only includes the styles that belong to this chunk, allowing
191
- * chunks to be cached independently.
192
- *
193
- * Also includes relevant local predefined states that are referenced
194
- * by this chunk's styles.
195
- *
196
- * @param styles - The full styles object
197
- * @param chunkName - Name of the chunk
198
- * @param styleKeys - Keys of styles belonging to this chunk
199
- * @param reusable - Pass `true` only when `styles` outlives this render and
200
- * will be keyed again — a `tasty()` factory's own styles object, for
201
- * instance. It stores the result so the next render can skip serializing
202
- * every value again, which is worth doing only if there is a next render for
203
- * this exact object. Freshly merged per-render objects must leave it `false`:
204
- * storing them costs more than the key they would never reuse. Reading an
205
- * existing entry does not require it.
206
- * @returns A stable cache key string
207
- */
208
- function generateChunkCacheKey(styles, chunkName, styleKeys, reusable = false) {
209
- let perStyles = _chunkKeyCache.get(styles);
210
- if (perStyles !== void 0) {
211
- const entry = perStyles.get(chunkName);
212
- if (entry !== void 0 && isEntryFresh(styles, entry, styleKeys)) return entry.key;
213
- }
214
- const length = styleKeys.length;
215
- const snapshot = new Array(length * 2);
216
- for (let i = 0, at = 0; i < length; i++, at += 2) {
217
- const styleKey = styleKeys[i];
218
- snapshot[at] = styleKey;
219
- snapshot[at + 1] = styles[styleKey];
220
- }
221
- const key = computeChunkCacheKey(styles, chunkName, snapshot);
222
- if (reusable) {
223
- if (perStyles === void 0) {
224
- perStyles = /* @__PURE__ */ new Map();
225
- _chunkKeyCache.set(styles, perStyles);
226
- }
227
- perStyles.set(chunkName, {
228
- snapshot,
229
- key
230
- });
231
- }
232
- return key;
233
- }
234
- //#endregion
235
- //#region src/chunks/renderChunk.ts
236
- /**
237
- * Build a filtered styles object for a regular chunk.
238
- */
239
- function buildFilteredStyles(styles, styleKeys) {
240
- const localPredefinedStates = extractLocalPredefinedStates(styles);
241
- const filteredStyles = {};
242
- for (const [key, value] of Object.entries(localPredefinedStates)) filteredStyles[key] = value;
243
- for (const key of styleKeys) {
244
- const value = styles[key];
245
- if (value !== void 0) filteredStyles[key] = value;
246
- }
247
- return filteredStyles;
248
- }
249
- /**
250
- * Build a filtered styles object for the subcomponents chunk.
251
- */
252
- function buildSubcomponentFilteredStyles(styles, selectorKeys) {
253
- const localPredefinedStates = extractLocalPredefinedStates(styles);
254
- const filteredStyles = {};
255
- for (const [key, value] of Object.entries(localPredefinedStates)) filteredStyles[key] = value;
256
- for (const key of selectorKeys) {
257
- const value = styles[key];
258
- if (value !== void 0) filteredStyles[key] = value;
259
- }
260
- if (styles.$ !== void 0) filteredStyles.$ = styles.$;
261
- return filteredStyles;
262
- }
263
- /**
264
- * Render styles for a specific chunk.
265
- *
266
- * On pipeline cache hit, avoids building the filtered styles object entirely.
267
- * Only constructs it on cache miss when the pipeline actually needs the styles.
268
- *
269
- * IMPORTANT: Local predefined states (e.g., '@mobile': '@media(w < 600px)')
270
- * are always included in the filtered styles, regardless of which chunk is
271
- * being rendered. This ensures that state references like '@mobile' in any
272
- * chunk can be properly resolved by the pipeline.
273
- *
274
- * @param styles - The full styles object
275
- * @param chunkName - Name of the chunk being rendered
276
- * @param styleKeys - Keys of styles belonging to this chunk
277
- * @returns RenderResult with rules for this chunk
278
- */
279
- function renderStylesForChunk(styles, chunkName, styleKeys, pipelineCacheKey) {
280
- if (styleKeys.length === 0) return {
281
- rules: [],
282
- className: ""
283
- };
284
- if (pipelineCacheKey && hasPipelineCacheEntry(pipelineCacheKey)) return renderStyles(void 0, void 0, void 0, pipelineCacheKey);
285
- return renderStyles(chunkName === CHUNK_NAMES.SUBCOMPONENTS ? buildSubcomponentFilteredStyles(styles, styleKeys) : buildFilteredStyles(styles, styleKeys), void 0, void 0, pipelineCacheKey);
286
- }
287
- //#endregion
288
- //#region src/keyframes/index.ts
289
- const KEYFRAMES_KEY = "@keyframes";
290
- /**
291
- * Pattern to extract animation names from CSS animation property values.
292
- * Animation name is typically the first identifier in the shorthand.
293
- * Handles: "fadeIn 300ms ease-in", "pulse 1s infinite", etc.
294
- *
295
- * CSS animation shorthand order (all optional except name):
296
- * animation: name | duration | timing | delay | iteration | direction | fill-mode | play-state
297
- *
298
- * Animation names must:
299
- * - Start with a letter, underscore, or hyphen (but not a digit or CSS keyword)
300
- * - Not be CSS keywords: none, initial, inherit, unset, revert
301
- */
302
- const CSS_KEYWORDS = new Set([
303
- "none",
304
- "initial",
305
- "inherit",
306
- "unset",
307
- "revert",
308
- "auto",
309
- "normal",
310
- "running",
311
- "paused"
312
- ]);
313
- /**
314
- * Pattern to match animation name at the start of an animation value.
315
- * Must start with letter, underscore, or hyphen (not digit).
316
- */
317
- const ANIMATION_NAME_PATTERN = /^([a-zA-Z_-][a-zA-Z0-9_-]*)/;
318
- /**
319
- * Check if styles object has local @keyframes definition.
320
- * Fast path: single property lookup.
321
- */
322
- function hasLocalKeyframes(styles) {
323
- return KEYFRAMES_KEY in styles;
324
- }
325
- /**
326
- * Extract local @keyframes from styles object.
327
- * Returns null if no local keyframes (fast path).
328
- */
329
- function extractLocalKeyframes(styles) {
330
- const keyframes = styles[KEYFRAMES_KEY];
331
- if (!keyframes || typeof keyframes !== "object") return null;
332
- return keyframes;
333
- }
334
- /**
335
- * Merge local and global keyframes.
336
- * Local keyframes take priority over global.
337
- * Returns null if no keyframes exist (fast path).
338
- */
339
- function mergeKeyframes(local, global) {
340
- if (!local && !global) return null;
341
- if (!local) return global;
342
- if (!global) return local;
343
- return {
344
- ...global,
345
- ...local
346
- };
347
- }
348
- /**
349
- * Extract animation name from a single animation value.
350
- * Returns null if no valid name found.
351
- *
352
- * Examples:
353
- * - "fadeIn 300ms ease-in" → "fadeIn"
354
- * - "1s pulse infinite" → "pulse" (name can be anywhere)
355
- * - "none" → null (CSS keyword)
356
- * - "300ms ease-in" → null (no name, just duration/timing)
357
- */
358
- function extractAnimationNameFromValue(value) {
359
- const trimmed = value.trim();
360
- if (!trimmed) return null;
361
- const parts = trimmed.split(/\s+/);
362
- for (const part of parts) {
363
- if (CSS_KEYWORDS.has(part.toLowerCase())) continue;
364
- if (/^-?[\d.]+m?s$/i.test(part)) continue;
365
- if (part === "infinite" || /^\d+$/.test(part)) continue;
366
- if ([
367
- "normal",
368
- "reverse",
369
- "alternate",
370
- "alternate-reverse"
371
- ].includes(part.toLowerCase())) continue;
372
- if ([
373
- "forwards",
374
- "backwards",
375
- "both"
376
- ].includes(part.toLowerCase())) continue;
377
- if (["running", "paused"].includes(part.toLowerCase())) continue;
378
- if (/^(ease|linear|ease-in|ease-out|ease-in-out|step-start|step-end)$/i.test(part)) continue;
379
- if (/^(cubic-bezier|steps)\(/i.test(part)) continue;
380
- const match = ANIMATION_NAME_PATTERN.exec(part);
381
- if (match) return match[1];
382
- }
383
- return null;
384
- }
385
- /**
386
- * Extract all animation names from an animation property value.
387
- * Handles multiple animations separated by commas.
388
- *
389
- * Example: "fadeIn 300ms, slideIn 500ms ease-out" → ["fadeIn", "slideIn"]
390
- */
391
- function extractAnimationNamesFromAnimationValue(value) {
392
- const names = [];
393
- const animations = value.split(",");
394
- for (const animation of animations) {
395
- const name = extractAnimationNameFromValue(animation);
396
- if (name && !names.includes(name)) names.push(name);
397
- }
398
- return names;
399
- }
400
- /**
401
- * Extract animation names from a style value (handles mappings and arrays).
402
- */
403
- function extractAnimationNamesFromStyleValue(value, names) {
404
- if (typeof value === "string") for (const name of extractAnimationNamesFromAnimationValue(value)) names.add(name);
405
- else if (Array.isArray(value)) for (const v of value) extractAnimationNamesFromStyleValue(v, names);
406
- else if (value && typeof value === "object") for (const v of Object.values(value)) extractAnimationNamesFromStyleValue(v, names);
407
- }
408
- /**
409
- * Extract all animation names referenced in styles.
410
- * Scans 'animation' and 'animationName' properties including in state mappings.
411
- * Returns empty set if no animation properties found (fast path).
412
- */
413
- function extractAnimationNamesFromStyles(styles) {
414
- const names = /* @__PURE__ */ new Set();
415
- if ("animation" in styles) extractAnimationNamesFromStyleValue(styles.animation, names);
416
- if ("animationName" in styles) extractAnimationNamesFromStyleValue(styles.animationName, names);
417
- for (const [key, value] of Object.entries(styles)) {
418
- if (key === "$" || key === KEYFRAMES_KEY) continue;
419
- if ((key.startsWith("&") || key.startsWith(".") || /^[A-Z]/.test(key)) && value && typeof value === "object") {
420
- const nestedNames = extractAnimationNamesFromStyles(value);
421
- for (const name of nestedNames) names.add(name);
422
- }
423
- }
424
- return names;
425
- }
426
- /**
427
- * Replace animation names in CSS declarations with injected names.
428
- * Optimized to avoid regex creation - uses simple string replacement.
429
- *
430
- * @param declarations CSS declarations string
431
- * @param nameMap Map from original name to injected name (only contains names that differ)
432
- * @returns Updated declarations string
433
- */
434
- /**
435
- * The name a local `@keyframes` block is emitted under.
436
- *
437
- * Content-addressed, and a pure function of what was authored: the same steps
438
- * always produce the same name, and different steps under the same authored
439
- * name cannot collide. That is what lets the server and the client agree —
440
- * a name handed out by whichever injector happened to see the definition first
441
- * depends on run order, so the two would disagree on both the animation name
442
- * and the class that references it.
443
- */
444
- function resolveKeyframesName(authored, steps) {
445
- return `${authored}-${hashString(JSON.stringify(steps))}`;
446
- }
447
- /**
448
- * The emitted name for every local `@keyframes` in `styles`, by authored name.
449
- * Pure — the server, the RSC pass and the client all reach the same answer.
450
- */
451
- function resolveKeyframesNames(used) {
452
- const names = /* @__PURE__ */ new Map();
453
- for (const [authored, steps] of Object.entries(used)) names.set(authored, resolveKeyframesName(authored, steps));
454
- return names;
455
- }
456
- /**
457
- * Whether `declarations` names `animation` as an animation to run.
458
- *
459
- * Only `animation` and `animation-name` values count, and only whole tokens
460
- * within them: an animation called `crossfade` does not use keyframes called
461
- * `fade`. Same parsing as `replaceAnimationNames`, so the two agree on what
462
- * counts as a reference.
463
- */
464
- function referencesAnimation(declarations, animation) {
465
- if (!declarations.includes("animation")) return false;
466
- for (const part of declarations.split(";")) {
467
- const colonIdx = part.indexOf(":");
468
- if (colonIdx === -1) continue;
469
- const prop = part.slice(0, colonIdx).trim().toLowerCase();
470
- if (prop !== "animation" && prop !== "animation-name") continue;
471
- const value = part.slice(colonIdx + 1);
472
- if (replaceWord(value, animation, "\0") !== value) return true;
473
- }
474
- return false;
475
- }
476
- function replaceAnimationNames(declarations, nameMap) {
477
- if (!declarations.includes("animation")) return declarations;
478
- const parts = declarations.split(";");
479
- let modified = false;
480
- for (let i = 0; i < parts.length; i++) {
481
- const part = parts[i];
482
- const colonIdx = part.indexOf(":");
483
- if (colonIdx === -1) continue;
484
- const prop = part.slice(0, colonIdx).trim().toLowerCase();
485
- if (prop === "animation" || prop === "animation-name") {
486
- const prefix = part.slice(0, colonIdx + 1);
487
- let value = part.slice(colonIdx + 1);
488
- for (const [original, injected] of nameMap) {
489
- const newValue = replaceWord(value, original, injected);
490
- if (newValue !== value) {
491
- value = newValue;
492
- modified = true;
493
- }
494
- }
495
- parts[i] = prefix + value;
496
- }
497
- }
498
- return modified ? parts.join(";") : declarations;
499
- }
500
- /**
501
- * Replace a word in a string (word boundary aware, no regex).
502
- */
503
- function replaceWord(str, word, replacement) {
504
- let result = str;
505
- let idx = 0;
506
- while ((idx = result.indexOf(word, idx)) !== -1) {
507
- const before = idx === 0 ? " " : result[idx - 1];
508
- const after = idx + word.length >= result.length ? " " : result[idx + word.length];
509
- const isWordBoundaryBefore = !/[a-zA-Z0-9_-]/.test(before);
510
- const isWordBoundaryAfter = !/[a-zA-Z0-9_-]/.test(after);
511
- if (isWordBoundaryBefore && isWordBoundaryAfter) {
512
- result = result.slice(0, idx) + replacement + result.slice(idx + word.length);
513
- idx += replacement.length;
514
- } else idx += word.length;
515
- }
516
- return result;
517
- }
518
- /**
519
- * Filter keyframes to only those that are actually used.
520
- * Returns null if no keyframes are used (fast path).
521
- */
522
- function filterUsedKeyframes(keyframes, usedNames) {
523
- if (!keyframes || usedNames.size === 0) return null;
524
- const used = {};
525
- let hasAny = false;
526
- for (const name of usedNames) if (keyframes[name]) {
527
- used[name] = keyframes[name];
528
- hasAny = true;
529
- }
530
- return hasAny ? used : null;
531
- }
532
- //#endregion
533
- export { mergeKeyframes as a, resolveKeyframesNames as c, categorizeStyleKeys as d, hasLocalKeyframes as i, renderStylesForChunk as l, extractLocalKeyframes as n, referencesAnimation as o, filterUsedKeyframes as r, replaceAnimationNames as s, extractAnimationNamesFromStyles as t, generateChunkCacheKey as u };
534
-
535
- //# sourceMappingURL=keyframes-DE-OE76F.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"keyframes-DE-OE76F.js","names":[],"sources":["../src/chunks/definitions.ts","../src/chunks/cacheKey.ts","../src/chunks/renderChunk.ts","../src/keyframes/index.ts"],"sourcesContent":["/**\n * Style chunk definitions for CSS chunking optimization.\n *\n * Styles are grouped into chunks based on:\n * 1. Handler dependencies - styles that share a handler MUST be in the same chunk\n * 2. Logical grouping - related styles grouped for better cache reuse\n *\n * See STYLE_CHUNKING_SPEC.md for detailed rationale.\n *\n * ============================================================================\n * ⚠️ CRITICAL ARCHITECTURAL CONSTRAINT: NO CROSS-CHUNK HANDLER DEPENDENCIES\n * ============================================================================\n *\n * Style handlers declare their dependencies via `__lookupStyles` array.\n * This creates a dependency graph where handlers read multiple style props.\n *\n * **ALL styles in a handler's `__lookupStyles` MUST be in the SAME chunk.**\n *\n * Why this matters:\n * 1. Each chunk computes a cache key from ONLY its own style values\n * 2. If a handler reads a style from another chunk, that value isn't in the cache key\n * 3. Changing the cross-chunk style won't invalidate this chunk's cache\n * 4. Result: stale CSS output or incorrect cache hits\n *\n * Example of a violation:\n * ```\n * // flowStyle.__lookupStyles = ['display', 'flow']\n * // If 'display' is in DISPLAY chunk and 'flow' is in LAYOUT chunk:\n * // - User sets { display: 'grid', flow: 'column' }\n * // - LAYOUT chunk caches CSS with flow=column, display=grid\n * // - User changes to { display: 'flex', flow: 'column' }\n * // - LAYOUT chunk cache key unchanged (only has 'flow')\n * // - Returns stale CSS computed with display=grid!\n * ```\n *\n * Before adding/moving styles, verify:\n * 1. Find all handlers that use this style (grep for the style name in __lookupStyles)\n * 2. Ensure ALL styles from each handler's __lookupStyles are in the same chunk\n *\n * For **custom** handlers registered through `configure({ handlers })` this is no\n * longer only a convention: `alignHandlerChunks()` in `styles/predefined.ts` pulls\n * any style name the lists below don't know into its handler's existing chunk, and\n * warns when a handler bridges two chunks defined here. The lists below are still\n * hand-maintained, so the constraint must be checked by hand when editing them.\n * ============================================================================\n */\n\nimport { isSelector } from '../pipeline';\n\nimport { CHUNK_NAMES, STYLE_TO_CHUNK } from './style-chunk-map';\nimport type { ChunkName } from './style-chunk-map';\n\n// ============================================================================\n// Chunk Style Lists\n// ============================================================================\n\n// The chunk style lists and the style→chunk map live in `style-chunk-map.ts` so\n// that the map is populated by importing *that* module, independent of whether\n// this one has been loaded. Re-exported here for the original import paths.\nexport {\n APPEARANCE_CHUNK_STYLES,\n DIMENSION_CHUNK_STYLES,\n DISPLAY_CHUNK_STYLES,\n FONT_CHUNK_STYLES,\n LAYOUT_CHUNK_STYLES,\n POSITION_CHUNK_STYLES,\n} from './style-chunk-map';\nexport { CHUNK_NAMES, STYLE_TO_CHUNK } from './style-chunk-map';\nexport type { ChunkName } from './style-chunk-map';\n\n// ============================================================================\n// Chunk Priority Order\n// ============================================================================\n\n/**\n * Chunk processing order. This ensures deterministic className allocation\n * regardless of style key order in the input.\n */\nconst CHUNK_ORDER: readonly string[] = [\n CHUNK_NAMES.APPEARANCE,\n CHUNK_NAMES.FONT,\n CHUNK_NAMES.DIMENSION,\n CHUNK_NAMES.DISPLAY,\n CHUNK_NAMES.LAYOUT,\n CHUNK_NAMES.POSITION,\n CHUNK_NAMES.MISC,\n CHUNK_NAMES.SUBCOMPONENTS,\n] as const;\n\n/**\n * Map from chunk name to its priority index for sorting.\n */\nconst _CHUNK_PRIORITY = new Map<string, number>(\n CHUNK_ORDER.map((name, index) => [name, index]),\n);\n\n// ============================================================================\n// Chunk Info Interface\n// ============================================================================\n\nexport interface ChunkInfo {\n /** Name of the chunk */\n name: ChunkName | string;\n /** Style keys belonging to this chunk */\n styleKeys: string[];\n}\n\n// ============================================================================\n// Style Categorization\n// ============================================================================\n\n/**\n * Categorize style keys into chunks.\n *\n * Returns chunks in a deterministic order (by CHUNK_ORDER) regardless\n * of the order of keys in the input styles object.\n *\n * @param styles - The styles object to categorize\n * @returns Map of chunk name to array of style keys in that chunk (in priority order)\n */\nexport function categorizeStyleKeys(\n styles: Record<string, unknown>,\n): Map<string, string[]> {\n // First pass: collect keys into chunks (unordered)\n const chunkData: Record<string, string[]> = {};\n const keys = Object.keys(styles);\n\n for (const key of keys) {\n // Skip the $ helper key (used for selector combinators)\n // Skip @keyframes and @property (processed separately in useStyles)\n // Skip recipe (resolved before pipeline by resolveRecipes)\n if (\n key === '$' ||\n key === '@keyframes' ||\n key === '@property' ||\n key === '@font-face' ||\n key === '@counter-style' ||\n key === '@function' ||\n key === 'recipe'\n ) {\n continue;\n }\n\n if (isSelector(key)) {\n // All selectors go into the subcomponents chunk\n if (!chunkData[CHUNK_NAMES.SUBCOMPONENTS]) {\n chunkData[CHUNK_NAMES.SUBCOMPONENTS] = [];\n }\n chunkData[CHUNK_NAMES.SUBCOMPONENTS].push(key);\n } else {\n // Look up the chunk for this style, default to misc\n const chunkName = STYLE_TO_CHUNK.get(key) ?? CHUNK_NAMES.MISC;\n if (!chunkData[chunkName]) {\n chunkData[chunkName] = [];\n }\n chunkData[chunkName].push(key);\n }\n }\n\n // Second pass: build ordered Map based on CHUNK_ORDER\n const orderedChunks = new Map<string, string[]>();\n\n // Add chunks in priority order\n for (const chunkName of CHUNK_ORDER) {\n if (chunkData[chunkName] && chunkData[chunkName].length > 0) {\n // Sort keys within chunk for consistent cache key generation\n orderedChunks.set(chunkName, chunkData[chunkName].sort());\n }\n }\n\n // Handle any unknown chunks (shouldn't happen, but be defensive)\n for (const chunkName of Object.keys(chunkData)) {\n if (!orderedChunks.has(chunkName)) {\n orderedChunks.set(chunkName, chunkData[chunkName].sort());\n }\n }\n\n return orderedChunks;\n}\n","/**\n * Chunk-specific cache key generation.\n *\n * Generates cache keys that only include styles relevant to a specific chunk,\n * enabling more granular caching and reuse.\n *\n * Enhanced to support predefined states:\n * - Global predefined states don't affect cache keys (constant across app)\n * - Local predefined states only affect cache keys if referenced in the chunk\n */\n\nimport {\n extractLocalPredefinedStates,\n extractPredefinedStateRefs,\n} from '../states';\nimport type { Styles } from '../styles/types';\n\nconst _stableStringifyCache = new WeakMap<object, string>();\n\ninterface ChunkKeyEntry {\n /**\n * Flat `[key0, value0, key1, value1, …]` record of exactly what the key was\n * built from. Interleaving keeps an entry to one allocation.\n */\n snapshot: unknown[];\n key: string;\n}\n\n/**\n * Per-styles-object memo of generated keys, keyed by chunk name.\n *\n * Reading from this is free, so every call checks it. Writing to it is not:\n * the `WeakMap.set` plus the snapshot allocation measured ~35% of the cost of\n * generating a key from scratch, and it is pure waste for a styles object that\n * is never seen again. Callers therefore have to opt in via `reusable`, and\n * only for an object they know outlives the render that produced it.\n *\n * `Styles` is a plain mutable object, and nothing in the public\n * `computeStyles` / `useStyles` contract asks callers to freeze it, so a hit is\n * only returned after re-reading every value the key was built from and\n * confirming none of them changed. That check is deliberately shallow: it\n * compares the same references `stableStringify` would have looked up in\n * `_stableStringifyCache`, so a memoized key is stale in exactly the cases the\n * un-memoized function was already stale in — an object-valued style mutated\n * in place — and in no others.\n */\nconst _chunkKeyCache = new WeakMap<object, Map<string, ChunkKeyEntry>>();\n\n/**\n * Is `entry` still a valid key for this chunk of `styles`?\n *\n * True only when the chunk asks for the same style keys, in the same order,\n * and every one of them still reads back the value the key was built from.\n */\nfunction isEntryFresh(\n styles: Styles,\n entry: ChunkKeyEntry,\n styleKeys: string[],\n): boolean {\n const snapshot = entry.snapshot;\n const length = styleKeys.length;\n\n if (snapshot.length !== length * 2) return false;\n\n for (let i = 0, at = 0; i < length; i++, at += 2) {\n const key = styleKeys[i];\n if (snapshot[at] !== key) return false;\n if (styles[key] !== snapshot[at + 1]) return false;\n }\n\n return true;\n}\n\n/**\n * Recursively serialize a value with sorted keys for stable output.\n * This ensures that {a: 1, b: 2} and {b: 2, a: 1} produce the same string.\n * Uses a WeakMap cache for object values to avoid re-serializing the same references.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return 'undefined';\n }\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n const cached = _stableStringifyCache.get(value as object);\n if (cached !== undefined) return cached;\n\n let result: string;\n if (Array.isArray(value)) {\n result = '[' + value.map(stableStringify).join(',') + ']';\n } else {\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of sortedKeys) {\n if (obj[key] !== undefined) {\n parts.push(`${JSON.stringify(key)}:${stableStringify(obj[key])}`);\n }\n }\n result = '{' + parts.join(',') + '}';\n }\n\n _stableStringifyCache.set(value as object, result);\n return result;\n}\n\nfunction computeChunkCacheKey(\n styles: Styles,\n chunkName: string,\n snapshot: unknown[],\n): string {\n // Start with chunk name for namespace separation\n const parts: string[] = [chunkName];\n\n // styleKeys are already sorted by categorizeStyleKeys\n let chunkStylesStr = '';\n\n // Reading from the snapshot rather than from `styles` guarantees the key and\n // the values a memo entry validates against are the same values.\n for (let at = 0; at < snapshot.length; at += 2) {\n const value = snapshot[at + 1];\n if (value !== undefined) {\n // Use stable stringify for consistent serialization regardless of key order\n const serialized = stableStringify(value);\n parts.push(`${snapshot[at] as string}:${serialized}`);\n chunkStylesStr += serialized;\n }\n }\n\n // Extract local predefined states from the full styles object\n const localStates = extractLocalPredefinedStates(styles);\n\n // Only include local predefined states that are actually referenced in this chunk\n if (Object.keys(localStates).length > 0) {\n const referencedStates = extractPredefinedStateRefs(chunkStylesStr);\n const relevantLocalStates: string[] = [];\n\n for (const stateName of referencedStates) {\n if (localStates[stateName]) {\n relevantLocalStates.push(`${stateName}=${localStates[stateName]}`);\n }\n }\n\n // Add relevant local states to the cache key (sorted for stability)\n if (relevantLocalStates.length > 0) {\n relevantLocalStates.sort();\n parts.unshift(`[states:${relevantLocalStates.join('|')}]`);\n }\n }\n\n // Use null character as separator (safe, not in JSON output)\n return parts.join('\\0');\n}\n\n/**\n * Generate a cache key for a specific chunk.\n *\n * Only includes the styles that belong to this chunk, allowing\n * chunks to be cached independently.\n *\n * Also includes relevant local predefined states that are referenced\n * by this chunk's styles.\n *\n * @param styles - The full styles object\n * @param chunkName - Name of the chunk\n * @param styleKeys - Keys of styles belonging to this chunk\n * @param reusable - Pass `true` only when `styles` outlives this render and\n * will be keyed again — a `tasty()` factory's own styles object, for\n * instance. It stores the result so the next render can skip serializing\n * every value again, which is worth doing only if there is a next render for\n * this exact object. Freshly merged per-render objects must leave it `false`:\n * storing them costs more than the key they would never reuse. Reading an\n * existing entry does not require it.\n * @returns A stable cache key string\n */\nexport function generateChunkCacheKey(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n reusable = false,\n): string {\n let perStyles = _chunkKeyCache.get(styles as object);\n\n if (perStyles !== undefined) {\n const entry = perStyles.get(chunkName);\n if (entry !== undefined && isEntryFresh(styles, entry, styleKeys)) {\n return entry.key;\n }\n }\n\n const length = styleKeys.length;\n const snapshot: unknown[] = new Array(length * 2);\n\n for (let i = 0, at = 0; i < length; i++, at += 2) {\n const styleKey = styleKeys[i];\n snapshot[at] = styleKey;\n snapshot[at + 1] = styles[styleKey];\n }\n\n const key = computeChunkCacheKey(styles, chunkName, snapshot);\n\n if (reusable) {\n if (perStyles === undefined) {\n perStyles = new Map();\n _chunkKeyCache.set(styles as object, perStyles);\n }\n perStyles.set(chunkName, { snapshot, key });\n }\n\n return key;\n}\n","/**\n * Chunk-specific style rendering.\n *\n * Renders styles for a specific chunk by filtering the styles object\n * to only include relevant keys before passing to renderStyles.\n */\n\nimport type { RenderResult } from '../pipeline';\nimport { hasPipelineCacheEntry, renderStyles } from '../pipeline';\nimport { extractLocalPredefinedStates } from '../states';\nimport type { Styles } from '../styles/types';\n\nimport { CHUNK_NAMES } from './definitions';\n\n/**\n * Build a filtered styles object for a regular chunk.\n */\nfunction buildFilteredStyles(styles: Styles, styleKeys: string[]): Styles {\n const localPredefinedStates = extractLocalPredefinedStates(styles);\n const filteredStyles: Styles = {};\n\n for (const [key, value] of Object.entries(localPredefinedStates)) {\n filteredStyles[key] = value;\n }\n\n for (const key of styleKeys) {\n const value = styles[key];\n if (value !== undefined) {\n filteredStyles[key] = value;\n }\n }\n\n return filteredStyles;\n}\n\n/**\n * Build a filtered styles object for the subcomponents chunk.\n */\nfunction buildSubcomponentFilteredStyles(\n styles: Styles,\n selectorKeys: string[],\n): Styles {\n const localPredefinedStates = extractLocalPredefinedStates(styles);\n const filteredStyles: Styles = {};\n\n for (const [key, value] of Object.entries(localPredefinedStates)) {\n filteredStyles[key] = value;\n }\n\n for (const key of selectorKeys) {\n const value = styles[key];\n if (value !== undefined) {\n filteredStyles[key] = value;\n }\n }\n\n if (styles.$ !== undefined) {\n filteredStyles.$ = styles.$;\n }\n\n return filteredStyles;\n}\n\n/**\n * Render styles for a specific chunk.\n *\n * On pipeline cache hit, avoids building the filtered styles object entirely.\n * Only constructs it on cache miss when the pipeline actually needs the styles.\n *\n * IMPORTANT: Local predefined states (e.g., '@mobile': '@media(w < 600px)')\n * are always included in the filtered styles, regardless of which chunk is\n * being rendered. This ensures that state references like '@mobile' in any\n * chunk can be properly resolved by the pipeline.\n *\n * @param styles - The full styles object\n * @param chunkName - Name of the chunk being rendered\n * @param styleKeys - Keys of styles belonging to this chunk\n * @returns RenderResult with rules for this chunk\n */\nexport function renderStylesForChunk(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n pipelineCacheKey?: string,\n): RenderResult {\n if (styleKeys.length === 0) {\n return { rules: [], className: '' };\n }\n\n // Fast path: skip building filteredStyles when pipeline has a cached result\n if (pipelineCacheKey && hasPipelineCacheEntry(pipelineCacheKey)) {\n return renderStyles(undefined, undefined, undefined, pipelineCacheKey);\n }\n\n // Cache miss: build filtered styles and run pipeline\n const filteredStyles =\n chunkName === CHUNK_NAMES.SUBCOMPONENTS\n ? buildSubcomponentFilteredStyles(styles, styleKeys)\n : buildFilteredStyles(styles, styleKeys);\n\n return renderStyles(filteredStyles, undefined, undefined, pipelineCacheKey);\n}\n","/**\n * Keyframes Utilities\n *\n * Optimized utilities for extracting and processing keyframes in styles.\n * Designed for zero overhead when no keyframes are used.\n */\n\nimport type { KeyframesSteps } from '../injector/types';\nimport type { Styles } from '../styles/types';\nimport { hashString } from '../utils/hash';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst KEYFRAMES_KEY = '@keyframes';\n\n/**\n * Pattern to extract animation names from CSS animation property values.\n * Animation name is typically the first identifier in the shorthand.\n * Handles: \"fadeIn 300ms ease-in\", \"pulse 1s infinite\", etc.\n *\n * CSS animation shorthand order (all optional except name):\n * animation: name | duration | timing | delay | iteration | direction | fill-mode | play-state\n *\n * Animation names must:\n * - Start with a letter, underscore, or hyphen (but not a digit or CSS keyword)\n * - Not be CSS keywords: none, initial, inherit, unset, revert\n */\nconst CSS_KEYWORDS = new Set([\n 'none',\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'auto',\n 'normal',\n 'running',\n 'paused',\n]);\n\n/**\n * Pattern to match animation name at the start of an animation value.\n * Must start with letter, underscore, or hyphen (not digit).\n */\nconst ANIMATION_NAME_PATTERN = /^([a-zA-Z_-][a-zA-Z0-9_-]*)/;\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @keyframes definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalKeyframes(styles: Styles): boolean {\n return KEYFRAMES_KEY in styles;\n}\n\n/**\n * Extract local @keyframes from styles object.\n * Returns null if no local keyframes (fast path).\n */\nexport function extractLocalKeyframes(\n styles: Styles,\n): Record<string, KeyframesSteps> | null {\n const keyframes = styles[KEYFRAMES_KEY];\n if (!keyframes || typeof keyframes !== 'object') {\n return null;\n }\n return keyframes as Record<string, KeyframesSteps>;\n}\n\n/**\n * Merge local and global keyframes.\n * Local keyframes take priority over global.\n * Returns null if no keyframes exist (fast path).\n */\nexport function mergeKeyframes(\n local: Record<string, KeyframesSteps> | null,\n global: Record<string, KeyframesSteps> | null,\n): Record<string, KeyframesSteps> | null {\n if (!local && !global) return null;\n if (!local) return global;\n if (!global) return local;\n // Local overrides global\n return { ...global, ...local };\n}\n\n// ============================================================================\n// Animation Name Extraction\n// ============================================================================\n\n/**\n * Extract animation name from a single animation value.\n * Returns null if no valid name found.\n *\n * Examples:\n * - \"fadeIn 300ms ease-in\" → \"fadeIn\"\n * - \"1s pulse infinite\" → \"pulse\" (name can be anywhere)\n * - \"none\" → null (CSS keyword)\n * - \"300ms ease-in\" → null (no name, just duration/timing)\n */\nfunction extractAnimationNameFromValue(value: string): string | null {\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n // Split by whitespace and find the first valid animation name\n const parts = trimmed.split(/\\s+/);\n\n for (const part of parts) {\n // Skip CSS keywords\n if (CSS_KEYWORDS.has(part.toLowerCase())) continue;\n\n // Skip time values (e.g., 300ms, 1s, 0.5s)\n if (/^-?[\\d.]+m?s$/i.test(part)) continue;\n\n // Skip iteration counts (e.g., infinite, 3)\n if (part === 'infinite' || /^\\d+$/.test(part)) continue;\n\n // Skip direction values\n if (\n ['normal', 'reverse', 'alternate', 'alternate-reverse'].includes(\n part.toLowerCase(),\n )\n )\n continue;\n\n // Skip fill-mode values\n if (['forwards', 'backwards', 'both'].includes(part.toLowerCase()))\n continue;\n\n // Skip play-state values\n if (['running', 'paused'].includes(part.toLowerCase())) continue;\n\n // Skip timing functions (ease, linear, ease-in, etc., or cubic-bezier/steps)\n if (\n /^(ease|linear|ease-in|ease-out|ease-in-out|step-start|step-end)$/i.test(\n part,\n )\n )\n continue;\n if (/^(cubic-bezier|steps)\\(/i.test(part)) continue;\n\n // Check if it looks like a valid animation name\n const match = ANIMATION_NAME_PATTERN.exec(part);\n if (match) {\n return match[1];\n }\n }\n\n return null;\n}\n\n/**\n * Extract all animation names from an animation property value.\n * Handles multiple animations separated by commas.\n *\n * Example: \"fadeIn 300ms, slideIn 500ms ease-out\" → [\"fadeIn\", \"slideIn\"]\n */\nfunction extractAnimationNamesFromAnimationValue(value: string): string[] {\n const names: string[] = [];\n\n // Split by comma for multiple animations\n const animations = value.split(',');\n\n for (const animation of animations) {\n const name = extractAnimationNameFromValue(animation);\n if (name && !names.includes(name)) {\n names.push(name);\n }\n }\n\n return names;\n}\n\n/**\n * Extract animation names from a style value (handles mappings and arrays).\n */\nfunction extractAnimationNamesFromStyleValue(\n value: unknown,\n names: Set<string>,\n): void {\n if (typeof value === 'string') {\n for (const name of extractAnimationNamesFromAnimationValue(value)) {\n names.add(name);\n }\n } else if (Array.isArray(value)) {\n // Responsive array\n for (const v of value) {\n extractAnimationNamesFromStyleValue(v, names);\n }\n } else if (value && typeof value === 'object') {\n // State mapping\n for (const v of Object.values(value)) {\n extractAnimationNamesFromStyleValue(v, names);\n }\n }\n}\n\n/**\n * Extract all animation names referenced in styles.\n * Scans 'animation' and 'animationName' properties including in state mappings.\n * Returns empty set if no animation properties found (fast path).\n */\nexport function extractAnimationNamesFromStyles(styles: Styles): Set<string> {\n const names = new Set<string>();\n\n // Check animation property\n if ('animation' in styles) {\n extractAnimationNamesFromStyleValue(styles.animation, names);\n }\n\n // Check animationName property\n if ('animationName' in styles) {\n extractAnimationNamesFromStyleValue(styles.animationName, names);\n }\n\n // Check nested selectors (sub-elements)\n for (const [key, value] of Object.entries(styles)) {\n // Skip non-selector keys and special keys\n if (key === '$' || key === KEYFRAMES_KEY) continue;\n\n // Check if it's a selector (starts with &, ., or uppercase)\n if (\n (key.startsWith('&') || key.startsWith('.') || /^[A-Z]/.test(key)) &&\n value &&\n typeof value === 'object'\n ) {\n // Recursively extract from nested styles\n const nestedNames = extractAnimationNamesFromStyles(value as Styles);\n for (const name of nestedNames) {\n names.add(name);\n }\n }\n }\n\n return names;\n}\n\n// ============================================================================\n// Name Replacement\n// ============================================================================\n\n/**\n * Replace animation names in CSS declarations with injected names.\n * Optimized to avoid regex creation - uses simple string replacement.\n *\n * @param declarations CSS declarations string\n * @param nameMap Map from original name to injected name (only contains names that differ)\n * @returns Updated declarations string\n */\n/**\n * The name a local `@keyframes` block is emitted under.\n *\n * Content-addressed, and a pure function of what was authored: the same steps\n * always produce the same name, and different steps under the same authored\n * name cannot collide. That is what lets the server and the client agree —\n * a name handed out by whichever injector happened to see the definition first\n * depends on run order, so the two would disagree on both the animation name\n * and the class that references it.\n */\nexport function resolveKeyframesName(\n authored: string,\n steps: KeyframesSteps,\n): string {\n return `${authored}-${hashString(JSON.stringify(steps))}`;\n}\n\n/**\n * The emitted name for every local `@keyframes` in `styles`, by authored name.\n * Pure — the server, the RSC pass and the client all reach the same answer.\n */\nexport function resolveKeyframesNames(\n used: Record<string, KeyframesSteps>,\n): Map<string, string> {\n const names = new Map<string, string>();\n\n for (const [authored, steps] of Object.entries(used)) {\n names.set(authored, resolveKeyframesName(authored, steps));\n }\n\n return names;\n}\n\n/**\n * Whether `declarations` names `animation` as an animation to run.\n *\n * Only `animation` and `animation-name` values count, and only whole tokens\n * within them: an animation called `crossfade` does not use keyframes called\n * `fade`. Same parsing as `replaceAnimationNames`, so the two agree on what\n * counts as a reference.\n */\nexport function referencesAnimation(\n declarations: string,\n animation: string,\n): boolean {\n if (!declarations.includes('animation')) return false;\n\n for (const part of declarations.split(';')) {\n const colonIdx = part.indexOf(':');\n if (colonIdx === -1) continue;\n\n const prop = part.slice(0, colonIdx).trim().toLowerCase();\n if (prop !== 'animation' && prop !== 'animation-name') continue;\n\n const value = part.slice(colonIdx + 1);\n if (replaceWord(value, animation, '\\u0000') !== value) return true;\n }\n\n return false;\n}\n\nexport function replaceAnimationNames(\n declarations: string,\n nameMap: Map<string, string>,\n): string {\n // Fast path: no animation properties\n if (!declarations.includes('animation')) return declarations;\n\n // Parse and replace\n const parts = declarations.split(';');\n let modified = false;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const colonIdx = part.indexOf(':');\n if (colonIdx === -1) continue;\n\n const prop = part.slice(0, colonIdx).trim().toLowerCase();\n\n if (prop === 'animation' || prop === 'animation-name') {\n const prefix = part.slice(0, colonIdx + 1);\n let value = part.slice(colonIdx + 1);\n\n // Replace each animation name using simple word replacement\n for (const [original, injected] of nameMap) {\n // Simple word boundary replacement without regex\n const newValue = replaceWord(value, original, injected);\n if (newValue !== value) {\n value = newValue;\n modified = true;\n }\n }\n\n parts[i] = prefix + value;\n }\n }\n\n return modified ? parts.join(';') : declarations;\n}\n\n/**\n * Replace a word in a string (word boundary aware, no regex).\n */\nfunction replaceWord(str: string, word: string, replacement: string): string {\n let result = str;\n let idx = 0;\n\n while ((idx = result.indexOf(word, idx)) !== -1) {\n // Check word boundaries\n const before = idx === 0 ? ' ' : result[idx - 1];\n const after =\n idx + word.length >= result.length ? ' ' : result[idx + word.length];\n\n const isWordBoundaryBefore = !/[a-zA-Z0-9_-]/.test(before);\n const isWordBoundaryAfter = !/[a-zA-Z0-9_-]/.test(after);\n\n if (isWordBoundaryBefore && isWordBoundaryAfter) {\n result =\n result.slice(0, idx) + replacement + result.slice(idx + word.length);\n idx += replacement.length;\n } else {\n idx += word.length;\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Filter Functions\n// ============================================================================\n\n/**\n * Filter keyframes to only those that are actually used.\n * Returns null if no keyframes are used (fast path).\n */\nexport function filterUsedKeyframes(\n keyframes: Record<string, KeyframesSteps> | null,\n usedNames: Set<string>,\n): Record<string, KeyframesSteps> | null {\n if (!keyframes || usedNames.size === 0) return null;\n\n const used: Record<string, KeyframesSteps> = {};\n let hasAny = false;\n\n for (const name of usedNames) {\n if (keyframes[name]) {\n used[name] = keyframes[name];\n hasAny = true;\n }\n }\n\n return hasAny ? used : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,MAAM,cAAiC;CACrC,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;AACd;AAKwB,IAAI,IAC1B,YAAY,KAAK,MAAM,UAAU,CAAC,MAAM,KAAK,CAAC,CAChD;;;;;;;;;;AA0BA,SAAgB,oBACd,QACuB;CAEvB,MAAM,YAAsC,CAAC;CAC7C,MAAM,OAAO,OAAO,KAAK,MAAM;CAE/B,KAAK,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IAAI,CAAC,aAAa,UAAU,SAAS,GAAG,OAAO;CAE/C,MAAM,OAAuC,CAAC;CAC9C,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,WACjB,IAAI,UAAU,OAAO;EACnB,KAAK,QAAQ,UAAU;EACvB,SAAS;CACX;CAGF,OAAO,SAAS,OAAO;AACzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"merge-styles-DuoZEsm9.js","names":[],"sources":["../src/utils/merge-styles.ts"],"sourcesContent":["import { isSelector } from '../pipeline';\nimport type { Styles, StylesWithoutSelectors } from '../styles/types';\n\nimport { isDevEnv } from './is-dev-env';\n\nconst devMode = isDevEnv();\n\nconst INHERIT_VALUE = '@inherit';\n\n/**\n * Check if a value is a state map (object, not array).\n */\nfunction isStateMap(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Normalize a parent value to a state map.\n * - Already a state map → return as-is\n * - Non-null, non-false primitive → wrap as `{ '': value }`\n * - null / undefined / false → return null (no parent to merge with)\n */\nfunction normalizeToStateMap(value: unknown): Record<string, unknown> | null {\n if (isStateMap(value)) return value as Record<string, unknown>;\n if (value != null && value !== false) return { '': value };\n return null;\n}\n\n/**\n * Resolve a child state map against a parent value.\n *\n * Mode is determined by whether the child contains a `''` (default) key:\n * - No `''` → extend mode: parent entries preserved, child adds/overrides/repositions\n * - Has `''` → replace mode: child defines everything, `@inherit` cherry-picks from parent\n *\n * In both modes:\n * - `@inherit` value → resolve from parent state map\n * - `null` value → remove this state from the result\n * - `false` value → tombstone, persists through all layers, blocks recipe\n */\nfunction resolveStateMap(\n parentValue: unknown,\n childMap: Record<string, unknown>,\n): Record<string, unknown> {\n const isExtend = !('' in childMap);\n const parentMap = normalizeToStateMap(parentValue);\n\n if (!parentMap) {\n // No parent to merge with — strip nulls and @inherit, return child entries\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(childMap)) {\n const val = childMap[key];\n if (val === null || val === INHERIT_VALUE) continue;\n result[key] = val;\n }\n return result;\n }\n\n if (isExtend) {\n return resolveExtendMode(parentMap, childMap);\n }\n\n return resolveReplaceMode(parentMap, childMap);\n}\n\n/**\n * Extend mode: parent entries are preserved, child entries add/override/reposition.\n */\nfunction resolveExtendMode(\n parentMap: Record<string, unknown>,\n childMap: Record<string, unknown>,\n): Record<string, unknown> {\n const inheritKeys = new Set<string>();\n const removeKeys = new Set<string>();\n const overrideKeys = new Map<string, unknown>();\n\n for (const key of Object.keys(childMap)) {\n const val = childMap[key];\n if (val === INHERIT_VALUE) {\n if (key in parentMap) {\n inheritKeys.add(key);\n } else if (devMode) {\n console.warn(\n `[Tasty] @inherit used for state '${key}' that does not exist in the parent style map. Entry skipped.`,\n );\n }\n } else if (val === null) {\n removeKeys.add(key);\n } else if (key in parentMap) {\n overrideKeys.set(key, val);\n }\n }\n\n // 1. Parent entries in order (skip removed, skip repositioned, apply overrides)\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(parentMap)) {\n if (removeKeys.has(key)) continue;\n if (inheritKeys.has(key)) continue;\n if (overrideKeys.has(key)) {\n result[key] = overrideKeys.get(key);\n } else {\n result[key] = parentMap[key];\n }\n }\n\n // 2. Append new + repositioned entries in child declaration order\n for (const key of Object.keys(childMap)) {\n if (inheritKeys.has(key)) {\n result[key] = parentMap[key];\n } else if (\n !removeKeys.has(key) &&\n !overrideKeys.has(key) &&\n // Skip @inherit for keys that weren't in the parent (already warned above)\n childMap[key] !== INHERIT_VALUE\n ) {\n result[key] = childMap[key];\n }\n }\n\n return result;\n}\n\n/**\n * Replace mode: child entries define the result, `@inherit` pulls from parent.\n */\nfunction resolveReplaceMode(\n parentMap: Record<string, unknown>,\n childMap: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const key of Object.keys(childMap)) {\n const val = childMap[key];\n if (val === INHERIT_VALUE) {\n if (key in parentMap) {\n result[key] = parentMap[key];\n } else if (devMode) {\n console.warn(\n `[Tasty] @inherit used for state '${key}' that does not exist in the parent style map. Entry skipped.`,\n );\n }\n } else if (val !== null) {\n result[key] = val;\n }\n }\n\n return result;\n}\n\n/**\n * Merge sub-element properties with state map / null / undefined support.\n */\nfunction mergeSubElementStyles(\n parentSub: StylesWithoutSelectors | undefined,\n childSub: StylesWithoutSelectors,\n): StylesWithoutSelectors {\n const parent = parentSub as Record<string, unknown> | undefined;\n const child = childSub as Record<string, unknown>;\n const merged: Record<string, unknown> = { ...parent, ...child };\n\n for (const key of Object.keys(child)) {\n const val = child[key];\n\n if (val === undefined) {\n if (parent && key in parent) {\n merged[key] = parent[key];\n }\n } else if (val === null) {\n delete merged[key];\n } else if (isStateMap(val)) {\n merged[key] = resolveStateMap(\n parent ? parent[key] : undefined,\n val as Record<string, unknown>,\n );\n }\n }\n\n return merged as StylesWithoutSelectors;\n}\n\nexport function mergeStyles(...objects: (Styles | undefined | null)[]): Styles {\n let styles: Styles = objects[0] ? { ...objects[0] } : {};\n let pos = 1;\n\n while (pos in objects) {\n const selectorKeys = Object.keys(styles).filter(\n (key) => isSelector(key) && styles[key],\n );\n const newStyles = objects[pos];\n\n if (newStyles) {\n const resultStyles = { ...styles, ...newStyles };\n\n // Collect all selector keys from both parent and child\n const newSelectorKeys = Object.keys(newStyles).filter(isSelector);\n const allSelectorKeys = new Set([...selectorKeys, ...newSelectorKeys]);\n\n for (const key of allSelectorKeys) {\n const newValue = newStyles?.[key];\n\n if (newValue === false || newValue === null) {\n delete resultStyles[key];\n } else if (newValue === undefined) {\n resultStyles[key] = styles[key];\n } else if (newValue) {\n resultStyles[key] = mergeSubElementStyles(\n styles[key] as StylesWithoutSelectors,\n newValue as StylesWithoutSelectors,\n );\n }\n }\n\n // Handle non-selector properties: state maps, null, undefined\n for (const key of Object.keys(newStyles)) {\n if (isSelector(key)) continue;\n\n const newValue = newStyles[key];\n\n if (newValue === undefined) {\n if (key in styles) {\n resultStyles[key] = styles[key];\n } else {\n delete resultStyles[key];\n }\n } else if (newValue === null) {\n delete resultStyles[key];\n } else if (isStateMap(newValue)) {\n (resultStyles as Record<string, unknown>)[key] = resolveStateMap(\n styles[key],\n newValue as Record<string, unknown>,\n );\n }\n }\n\n styles = resultStyles;\n }\n\n pos++;\n }\n\n return styles;\n}\n"],"mappings":";;AAKA,MAAM,UAAU,SAAS;AAEzB,MAAM,gBAAgB;;;;AAKtB,SAAS,WAAW,OAAkD;CACpE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;;;AAQA,SAAS,oBAAoB,OAAgD;CAC3E,IAAI,WAAW,KAAK,GAAG,OAAO;CAC9B,IAAI,SAAS,QAAQ,UAAU,OAAO,OAAO,EAAE,IAAI,MAAM;CACzD,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAS,gBACP,aACA,UACyB;CACzB,MAAM,WAAW,EAAE,MAAM;CACzB,MAAM,YAAY,oBAAoB,WAAW;CAEjD,IAAI,CAAC,WAAW;EAEd,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GAAG;GACvC,MAAM,MAAM,SAAS;GACrB,IAAI,QAAQ,QAAQ,QAAQ,eAAe;GAC3C,OAAO,OAAO;EAChB;EACA,OAAO;CACT;CAEA,IAAI,UACF,OAAO,kBAAkB,WAAW,QAAQ;CAG9C,OAAO,mBAAmB,WAAW,QAAQ;AAC/C;;;;AAKA,SAAS,kBACP,WACA,UACyB;CACzB,MAAM,8BAAc,IAAI,IAAY;CACpC,MAAM,6BAAa,IAAI,IAAY;CACnC,MAAM,+BAAe,IAAI,IAAqB;CAE9C,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GAAG;EACvC,MAAM,MAAM,SAAS;EACrB,IAAI,QAAQ;OACN,OAAO,WACT,YAAY,IAAI,GAAG;QACd,IAAI,SACT,QAAQ,KACN,oCAAoC,IAAI,8DAC1C;EAAA,OAEG,IAAI,QAAQ,MACjB,WAAW,IAAI,GAAG;OACb,IAAI,OAAO,W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