/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-f1f3d22 | Cube Dev Team */
import { extractLocalPredefinedStates, extractPredefinedStateRefs } from "../states/index.js";

//#region src/tasty/chunks/cacheKey.ts
/**
* Chunk-specific cache key generation.
*
* Generates cache keys that only include styles relevant to a specific chunk,
* enabling more granular caching and reuse.
*
* Enhanced to support predefined states:
* - Global predefined states don't affect cache keys (constant across app)
* - Local predefined states only affect cache keys if referenced in the chunk
*/
/**
* Recursively serialize a value with sorted keys for stable output.
* This ensures that {a: 1, b: 2} and {b: 2, a: 1} produce the same string.
*/
function stableStringify(value) {
	if (value === null) return "null";
	if (value === void 0) return "undefined";
	if (typeof value !== "object") return JSON.stringify(value);
	if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]";
	const obj = value;
	const sortedKeys = Object.keys(obj).sort();
	const parts = [];
	for (const key of sortedKeys) if (obj[key] !== void 0) parts.push(`${JSON.stringify(key)}:${stableStringify(obj[key])}`);
	return "{" + parts.join(",") + "}";
}
/**
* Generate a cache key for a specific chunk.
*
* Only includes the styles that belong to this chunk, allowing
* chunks to be cached independently.
*
* Also includes relevant local predefined states that are referenced
* by this chunk's styles.
*
* @param styles - The full styles object
* @param chunkName - Name of the chunk
* @param styleKeys - Keys of styles belonging to this chunk
* @returns A stable cache key string
*/
function generateChunkCacheKey(styles, chunkName, styleKeys) {
	const parts = [chunkName];
	const sortedKeys = styleKeys.slice().sort();
	let chunkStylesStr = "";
	for (const key of sortedKeys) {
		const value = styles[key];
		if (value !== void 0) {
			const serialized = stableStringify(value);
			parts.push(`${key}:${serialized}`);
			chunkStylesStr += serialized;
		}
	}
	const localStates = extractLocalPredefinedStates(styles);
	if (Object.keys(localStates).length > 0) {
		const referencedStates = extractPredefinedStateRefs(chunkStylesStr);
		const relevantLocalStates = [];
		for (const stateName of referencedStates) if (localStates[stateName]) relevantLocalStates.push(`${stateName}=${localStates[stateName]}`);
		if (relevantLocalStates.length > 0) {
			relevantLocalStates.sort();
			parts.unshift(`[states:${relevantLocalStates.join("|")}]`);
		}
	}
	return parts.join("\0");
}

//#endregion
export { generateChunkCacheKey };
//# sourceMappingURL=cacheKey.js.map