@tenphi/tasty 1.5.3 → 2.0.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.
- package/README.md +20 -15
- package/dist/compute-styles.js +13 -26
- package/dist/compute-styles.js.map +1 -1
- package/dist/config.d.ts +39 -1
- package/dist/config.js +64 -2
- package/dist/config.js.map +1 -1
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/debug.js +4 -4
- package/dist/debug.js.map +1 -1
- package/dist/hooks/useCounterStyle.js +2 -1
- package/dist/hooks/useCounterStyle.js.map +1 -1
- package/dist/hooks/useGlobalStyles.js +2 -2
- package/dist/hooks/useKeyframes.js +2 -1
- package/dist/hooks/useKeyframes.js.map +1 -1
- package/dist/hooks/useRawCSS.js +1 -1
- package/dist/hooks/useStyles.d.ts +4 -4
- package/dist/hooks/useStyles.js +7 -5
- package/dist/hooks/useStyles.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/injector/index.js +1 -1
- package/dist/injector/index.js.map +1 -1
- package/dist/injector/injector.d.ts +5 -0
- package/dist/injector/injector.js +93 -6
- package/dist/injector/injector.js.map +1 -1
- package/dist/injector/sheet-manager.js +3 -2
- package/dist/injector/sheet-manager.js.map +1 -1
- package/dist/injector/types.d.ts +9 -2
- package/dist/pipeline/exclusive.js +57 -2
- package/dist/pipeline/exclusive.js.map +1 -1
- package/dist/pipeline/index.js +2 -2
- package/dist/pipeline/index.js.map +1 -1
- package/dist/pipeline/materialize.js +56 -2
- package/dist/pipeline/materialize.js.map +1 -1
- package/dist/pipeline/simplify.js +180 -5
- package/dist/pipeline/simplify.js.map +1 -1
- package/dist/plugins/types.d.ts +12 -1
- package/dist/rsc-cache.js +2 -4
- package/dist/rsc-cache.js.map +1 -1
- package/dist/ssr/astro-client.js +5 -10
- package/dist/ssr/astro-client.js.map +1 -1
- package/dist/ssr/astro.d.ts +4 -2
- package/dist/ssr/astro.js +4 -4
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/collector.d.ts +9 -13
- package/dist/ssr/collector.js +32 -16
- package/dist/ssr/collector.js.map +1 -1
- package/dist/ssr/context.js +16 -0
- package/dist/ssr/context.js.map +1 -0
- package/dist/ssr/hydrate.d.ts +20 -13
- package/dist/ssr/hydrate.js +24 -28
- package/dist/ssr/hydrate.js.map +1 -1
- package/dist/ssr/index.d.ts +3 -3
- package/dist/ssr/index.js +4 -4
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next.d.ts +7 -4
- package/dist/ssr/next.js +7 -6
- package/dist/ssr/next.js.map +1 -1
- package/dist/ssr/ssr-collector-ref.js +17 -1
- package/dist/ssr/ssr-collector-ref.js.map +1 -1
- package/dist/tasty.d.ts +1 -1
- package/dist/tasty.js +9 -4
- package/dist/tasty.js.map +1 -1
- package/dist/utils/typography.d.ts +21 -10
- package/dist/utils/typography.js +1 -1
- package/dist/utils/typography.js.map +1 -1
- package/dist/zero/babel.d.ts +7 -108
- package/dist/zero/babel.js +36 -12
- package/dist/zero/babel.js.map +1 -1
- package/docs/README.md +2 -2
- package/docs/adoption.md +5 -3
- package/docs/comparison.md +24 -25
- package/docs/configuration.md +69 -1
- package/docs/design-system.md +22 -10
- package/docs/dsl.md +3 -3
- package/docs/getting-started.md +10 -10
- package/docs/injector.md +2 -2
- package/docs/methodology.md +2 -2
- package/docs/{runtime.md → react-api.md} +5 -1
- package/docs/ssr.md +14 -7
- package/docs/tasty-static.md +14 -2
- package/package.json +5 -5
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["/**\n * Tasty Configuration Module\n *\n * Centralizes all tasty configuration, including:\n * - Style injector settings (nonce, cleanup thresholds, etc.)\n * - Global predefined states for advanced state mapping\n * - stylesGenerated flag that locks configuration after first style generation\n *\n * Configuration must be done BEFORE any styles are generated.\n * After the first `inject()` call, configuration is locked and attempts to\n * reconfigure will emit a warning and be ignored.\n */\n\nimport { StyleInjector } from './injector/injector';\nimport { clearPipelineCache, isSelector, renderStyles } from './pipeline';\nimport { setGlobalPredefinedStates } from './states';\nimport {\n normalizeHandlerDefinition,\n registerHandler,\n resetHandlers,\n} from './styles/predefined';\nimport { resetColorSpace, setColorSpace } from './utils/color-space';\nimport { isDevEnv } from './utils/is-dev-env';\nimport {\n CUSTOM_UNITS,\n getGlobalFuncs,\n getGlobalParser,\n normalizeColorTokenValue,\n resetGlobalPredefinedTokens,\n setGlobalPredefinedTokens,\n} from './utils/styles';\n\nimport type { ColorSpace } from './utils/color-space';\n\nimport type {\n CounterStyleDescriptors,\n FontFaceInput,\n GCConfig,\n KeyframesSteps,\n PropertyDefinition,\n} from './injector/types';\nimport type { StyleDetails, UnitHandler } from './parser/types';\nimport type { StyleResult } from './pipeline';\nimport type { TastyPlugin } from './plugins/types';\nimport type { RecipeStyles, ConfigTokens } from './styles/types';\nimport type { StyleHandlerDefinition } from './utils/styles';\n\n/**\n * Configuration options for the Tasty style system\n */\nexport interface TastyConfig {\n /** CSP nonce for style elements */\n nonce?: string;\n /** Maximum rules per stylesheet (default: 8192) */\n maxRulesPerSheet?: number;\n /** Force text injection mode, auto-detected in test environments (default: auto) */\n forceTextInjection?: boolean;\n /** Enable development mode features: performance metrics and debug info (default: auto) */\n devMode?: boolean;\n /**\n * Global predefined states for advanced state mapping.\n * These are state aliases that can be used in any component.\n * Example: { '@mobile': '@media(w < 920px)', '@dark': '@root(theme=dark)' }\n */\n states?: Record<string, string>;\n /**\n * Parser LRU cache size (default: 1000).\n * Larger values improve performance for apps with many unique style values.\n */\n parserCacheSize?: number;\n /**\n * Custom units for the style parser (merged with built-in units).\n * Units transform numeric values like `2x` → `calc(2 * var(--gap))`.\n * @example { em: 'em', vw: 'vw', custom: (n) => `${n * 10}px` }\n */\n units?: Record<string, string | UnitHandler>;\n /**\n * Custom functions for the style parser (merged with existing).\n * Functions process parsed style groups and return CSS values.\n * @example { myFunc: (groups) => groups.map(g => g.output).join(' ') }\n */\n funcs?: Record<string, (groups: StyleDetails[]) => string>;\n /**\n * Color space used for decomposed color token companion variables.\n * Controls the CSS function and suffix for alpha composition.\n *\n * - `'rgb'` — suffix `-rgb`, e.g. `rgb(var(--name-color-rgb) / .5)`\n * - `'hsl'` — suffix `-hsl`, e.g. `hsl(var(--name-color-hsl) / .5)`\n * - `'oklch'` — suffix `-oklch`, e.g. `oklch(var(--name-color-oklch) / .5)`\n *\n * @default 'oklch'\n */\n colorSpace?: ColorSpace;\n /**\n * Automatically infer and register CSS @property declarations\n * from custom property values found in styles, keyframes, and global config.\n * Covers all types: \\<color\\>, \\<number\\>, \\<length\\>, \\<angle\\>, \\<percentage\\>, \\<time\\>.\n * When false, only explicitly declared @properties are registered.\n * @default true\n */\n autoPropertyTypes?: boolean;\n /**\n * Garbage collection configuration for unused styles.\n * GC is triggered by touch count: every `touchInterval` touches, the\n * oldest unused styles are evicted when their count exceeds `capacity`.\n * @example\n * ```ts\n * configure({\n * gc: { touchInterval: 1000, capacity: 1000 },\n * });\n * ```\n */\n gc?: GCConfig;\n /**\n * Plugins that extend tasty with custom functions, units, or states.\n * Plugins are processed in order, with later plugins overriding earlier ones.\n * @example\n * ```ts\n * import { okhslPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhslPlugin()],\n * });\n * ```\n */\n plugins?: TastyPlugin[];\n /**\n * Global keyframes definitions that can be referenced by animation names in styles.\n * Keys are animation names, values are keyframes step definitions.\n * Keyframes are only injected when actually used in styles.\n * @example\n * ```ts\n * configure({\n * keyframes: {\n * fadeIn: { from: { opacity: 0 }, to: { opacity: 1 } },\n * pulse: { '0%, 100%': { transform: 'scale(1)' }, '50%': { transform: 'scale(1.05)' } },\n * },\n * });\n * ```\n */\n keyframes?: Record<string, KeyframesSteps>;\n /**\n * Global CSS @property definitions for custom properties.\n * Keys use tasty token syntax ($name for properties, #name for colors).\n *\n * Tasty ships with `DEFAULT_PROPERTIES` (e.g. `$gap`, `$radius`, `#white`,\n * `#black`, `#clear`, `#border`, etc.) that are always included.\n * Properties you specify here are merged on top, so you can override any\n * default by using the same key.\n *\n * For color tokens (#name), `syntax: '<color>'` is auto-set and\n * `initialValue` defaults to `'transparent'` if not specified.\n *\n * @example\n * ```ts\n * configure({\n * properties: {\n * '$rotation': { syntax: '<angle>', initialValue: '0deg' },\n * '$scale': { syntax: '<number>', inherits: false, initialValue: 1 },\n * '#accent': { initialValue: 'purple' }, // syntax: '<color>' auto-set\n * // Override a default property:\n * '$gap': { syntax: '<length>', inherits: true, initialValue: '8px' },\n * },\n * });\n *\n * // Now use in styles - properties are registered when component renders:\n * const Spinner = tasty({\n * styles: {\n * transform: 'rotate($rotation)',\n * transition: '$$rotation 0.3s', // outputs: --rotation 0.3s\n * },\n * });\n * ```\n */\n properties?: Record<string, PropertyDefinition>;\n /**\n * Global @font-face definitions.\n * Keys are font-family names, values are descriptors or arrays of descriptors\n * (for multiple weights/styles of the same family).\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * fontFace: {\n * 'Brand Sans': [\n * { src: 'url(\"/fonts/brand-regular.woff2\") format(\"woff2\")', fontWeight: 400, fontDisplay: 'swap' },\n * { src: 'url(\"/fonts/brand-bold.woff2\") format(\"woff2\")', fontWeight: 700, fontDisplay: 'swap' },\n * ],\n * Icons: { src: 'url(\"/fonts/icons.woff2\") format(\"woff2\")', fontDisplay: 'block' },\n * },\n * });\n * ```\n */\n fontFace?: Record<string, FontFaceInput>;\n /**\n * Global @counter-style definitions.\n * Keys are counter-style names, values are descriptor objects.\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * counterStyle: {\n * thumbs: { system: 'cyclic', symbols: '\"👍\"', suffix: '\" \"' },\n * },\n * });\n * ```\n */\n counterStyle?: Record<string, CounterStyleDescriptors>;\n /**\n * Custom style handlers that transform style properties into CSS declarations.\n * Handlers replace built-in handlers for the same style name.\n * @example\n * ```ts\n * import { styleHandlers } from '@tenphi/tasty';\n *\n * configure({\n * handlers: {\n * // Override fill with custom behavior\n * fill: ({ fill }) => {\n * if (fill?.startsWith('gradient:')) {\n * return { background: fill.slice(9) };\n * }\n * return styleHandlers.fill({ fill });\n * },\n * // Add new custom style\n * elevation: ({ elevation }) => {\n * const level = parseInt(elevation) || 1;\n * return {\n * 'box-shadow': `0 ${level * 2}px ${level * 4}px rgba(0,0,0,0.1)`,\n * 'z-index': String(level * 100),\n * };\n * },\n * },\n * });\n * ```\n */\n handlers?: Record<string, StyleHandlerDefinition>;\n /**\n * Design tokens injected as CSS custom properties on `:root`.\n * Values are parsed through the Tasty DSL. Supports state maps\n * for responsive/theme-aware tokens.\n *\n * - `$name` keys become `--name` CSS custom properties\n * - `#name` keys become `--name-color` and `--name-color-{colorSpace}` properties\n *\n * Tokens are injected once when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * tokens: {\n * '$gap': '4px',\n * '#primary': {\n * '': '#purple',\n * '@dark': '#light-purple',\n * },\n * },\n * });\n * ```\n */\n tokens?: ConfigTokens;\n /**\n * Predefined tokens that are replaced during style parsing (parse-time substitution).\n * Use `$name` for custom properties and `#name` for color tokens.\n * Values are substituted inline before CSS generation, unlike `tokens` which\n * inject CSS custom properties on `:root`.\n *\n * For color tokens (#name), boolean `true` is converted to `transparent`.\n *\n * @example\n * ```ts\n * configure({\n * replaceTokens: {\n * $spacing: '2x',\n * '#accent': '#purple',\n * '#overlay': true, // → transparent\n * },\n * });\n *\n * // Now use in styles - tokens are replaced at parse time:\n * const Card = tasty({\n * styles: {\n * padding: '$spacing', // → calc(2 * var(--gap))\n * fill: '#accent', // → var(--purple-color)\n * },\n * });\n * ```\n */\n replaceTokens?: Record<`$${string}`, string | number | boolean> &\n Record<`#${string}`, string | number | boolean>;\n /**\n * Predefined style recipes -- named style bundles that can be applied via `recipe` style property.\n * Recipe values are flat tasty styles (no sub-element keys). They may contain base styles,\n * tokens (`$name`/`#name` definitions), local states, `@keyframes`, and `@properties`.\n *\n * Components reference recipes via: `recipe: 'name1 name2'` in their styles.\n * Use `/` to separate base recipes from post recipes: `recipe: 'base1 base2 / post1'`.\n * Use `none` to skip base recipes: `recipe: 'none / post1'`.\n * Resolution order: `base_recipes → component styles → post_recipes`.\n *\n * Recipes cannot reference other recipes.\n *\n * @example\n * ```ts\n * configure({\n * recipes: {\n * card: { padding: '4x', fill: '#surface', radius: '1r', border: true },\n * elevated: { shadow: '2x 2x 4x #shadow' },\n * },\n * });\n *\n * // Usage in styles:\n * const Card = tasty({\n * styles: {\n * recipe: 'card elevated',\n * color: '#text', // Overrides recipe values\n * },\n * });\n * ```\n */\n recipes?: Record<string, RecipeStyles>;\n}\n\n// Warnings tracking to avoid duplicates\nconst emittedWarnings = new Set<string>();\n\nconst devMode = isDevEnv();\n\n/**\n * Emit a warning only once\n */\nfunction warnOnce(key: string, message: string): void {\n if (devMode && !emittedWarnings.has(key)) {\n emittedWarnings.add(key);\n console.warn(message);\n }\n}\n\n// ============================================================================\n// Configuration State\n// ============================================================================\n\n// Track whether styles have been generated (locks configuration)\nlet stylesGenerated = false;\n\n// Current configuration (null until first configure() or auto-configured on first use)\nlet currentConfig: TastyConfig | null = null;\n\n// Global keyframes storage (null = no keyframes configured, empty object checked via hasGlobalKeyframes)\nlet globalKeyframes: Record<string, KeyframesSteps> | null = null;\n\n// Global font-face storage (null = no font faces configured)\nlet globalFontFace: Record<string, FontFaceInput> | null = null;\n\n// Global counter-style storage (null = no counter styles configured)\nlet globalCounterStyle: Record<string, CounterStyleDescriptors> | null = null;\n\n// Global properties storage (null = no properties configured)\nlet globalProperties: Record<string, PropertyDefinition> | null = null;\n\n// Global recipes storage (null = no recipes configured)\nlet globalRecipes: Record<string, RecipeStyles> | null = null;\n\n// Global token styles storage (injected as :root CSS custom properties)\nlet globalConfigTokens: ConfigTokens | null = null;\n\n// ============================================================================\n// Cross-module config sharing via globalThis\n//\n// Frameworks like Astro may load middleware and page components from\n// separate module graphs, creating duplicate module-level state.\n// Config values read by SSR collector's collectInternals() are mirrored\n// to globalThis so they're accessible regardless of which module instance\n// the collector was loaded from.\n// ============================================================================\n\nconst GTKEY_TOKENS = '__tasty_cfg_tokens__';\nconst GTKEY_FONT_FACE = '__tasty_cfg_font_face__';\nconst GTKEY_COUNTER_STYLE = '__tasty_cfg_counter_style__';\nconst GTKEY_PROPERTIES = '__tasty_cfg_properties__';\n\nfunction setOnGlobalThis(key: string, value: unknown): void {\n (globalThis as Record<string, unknown>)[key] = value;\n}\n\nfunction getFromGlobalThis<T>(key: string): T | undefined {\n return (globalThis as Record<string, unknown>)[key] as T | undefined;\n}\n\nfunction clearGlobalThisConfig(): void {\n const g = globalThis as Record<string, unknown>;\n delete g[GTKEY_TOKENS];\n delete g[GTKEY_FONT_FACE];\n delete g[GTKEY_COUNTER_STYLE];\n delete g[GTKEY_PROPERTIES];\n}\n\n/**\n * Default properties shipped with tasty.\n * These are always included unless explicitly overridden via `configure({ properties })`.\n * Keys use tasty token syntax (#name for colors, $name for other properties).\n *\n * For properties with CSS @property-compatible types (length, time, number, color),\n * an `initialValue` is provided so the property works even without a project-level token.\n */\nexport const DEFAULT_PROPERTIES: Record<string, PropertyDefinition> = {\n // Used by dual-fill feature to enable CSS transitions on the second fill color\n '#tasty-second-fill': {\n inherits: false,\n initialValue: 'transparent',\n },\n // Current color context variable (set by the color style handler).\n '#current': {\n inherits: true,\n initialValue: 'transparent',\n },\n // White and black are fundamental colors that need explicit initial values.\n '#white': {\n inherits: true,\n initialValue: 'rgb(255 255 255)',\n },\n '#black': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n // Shorthand for transparent\n '#clear': {\n inherits: true,\n initialValue: 'transparent',\n },\n // Default border color\n '#border': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n\n // ---- Core design tokens used by style handlers ----\n // These provide sensible defaults so tasty works standalone without a design system.\n // Consuming projects (e.g. uikit) override these by defining tokens on :root.\n\n $gap: {\n syntax: '<length>',\n inherits: true,\n initialValue: '4px',\n },\n $radius: {\n syntax: '<length>',\n inherits: true,\n initialValue: '6px',\n },\n '$border-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '1px',\n },\n '$outline-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '3px',\n },\n $transition: {\n syntax: '<time>',\n inherits: true,\n initialValue: '80ms',\n },\n // Used by radius.ts for `radius=\"leaf\"` modifier\n '$sharp-radius': {\n syntax: '<length>',\n inherits: true,\n initialValue: '0px',\n },\n // Used by preset.ts for `preset=\"name / strong\"`\n '$bold-font-weight': {\n syntax: '<number>',\n inherits: true,\n initialValue: '700',\n },\n // Used by preset.ts as fallback font stacks\n '$font-sans-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'system-ui, -apple-system, \"Segoe UI\", Roboto, Helvetica, Arial, \"Apple Color Emoji\", \"Segoe UI Emoji\", sans-serif',\n },\n '$font-mono-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace',\n },\n};\n\n// Global injector instance key\nconst GLOBAL_INJECTOR_KEY = '__TASTY_GLOBAL_INJECTOR__';\n\ninterface TastyGlobalStorage {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n}\n\ndeclare global {\n interface Window {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n }\n\n var __TASTY_GLOBAL_INJECTOR__: StyleInjector | undefined;\n}\n\n/**\n * Detect if we're running in a test environment\n */\nexport function isTestEnvironment(): boolean {\n // Check Node.js environment\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n return true;\n }\n\n // Check for test runner globals (safely)\n if (typeof global !== 'undefined') {\n const g = global as unknown as Record<string, unknown>;\n if (g.vi || g.jest || g.expect || g.describe || g.it) {\n return true;\n }\n }\n\n // Check for jsdom environment (common in tests)\n if (\n typeof window !== 'undefined' &&\n window.navigator?.userAgent?.includes('jsdom')\n ) {\n return true;\n }\n\n // Check for other test runners\n if (typeof globalThis !== 'undefined') {\n const gt = globalThis as unknown as Record<string, unknown>;\n if (gt.vitest || gt.mocha) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Create default configuration with optional test environment detection\n */\nfunction createDefaultConfig(isTest?: boolean): TastyConfig {\n return {\n maxRulesPerSheet: 8192,\n forceTextInjection: isTest ?? false,\n devMode: isDevEnv(),\n };\n}\n\n// ============================================================================\n// stylesGenerated Flag Management\n// ============================================================================\n\n/**\n * Mark that styles have been generated (called by injector on first inject)\n * This locks the configuration - no further changes allowed.\n * Also injects internal and global properties.\n */\nexport function markStylesGenerated(): void {\n if (stylesGenerated) return; // Already marked, skip\n\n stylesGenerated = true;\n\n const injector = getGlobalInjector();\n\n // Inject all properties (defaults merged with user-configured overrides)\n for (const [token, definition] of Object.entries(getEffectiveProperties())) {\n injector.property(token, definition);\n }\n\n // Inject global @font-face rules (eagerly — fonts should be available before render)\n if (globalFontFace && Object.keys(globalFontFace).length > 0) {\n for (const [family, input] of Object.entries(globalFontFace)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n injector.fontFace(family, desc);\n }\n }\n }\n\n // Inject global @counter-style rules (eagerly)\n if (globalCounterStyle && Object.keys(globalCounterStyle).length > 0) {\n for (const [name, descriptors] of Object.entries(globalCounterStyle)) {\n injector.counterStyle(name, descriptors);\n }\n }\n\n // Inject configured tokens as :root CSS custom properties\n if (globalConfigTokens && Object.keys(globalConfigTokens).length > 0) {\n const tokenRules = renderStyles(\n globalConfigTokens,\n ':root',\n ) as StyleResult[];\n if (tokenRules.length > 0) {\n injector.injectGlobal(tokenRules);\n }\n }\n}\n\n/**\n * Check if styles have been generated (configuration is locked)\n */\nexport function hasStylesGenerated(): boolean {\n return stylesGenerated;\n}\n\n/**\n * Reset styles generated flag (for testing only)\n */\nexport function resetStylesGenerated(): void {\n stylesGenerated = false;\n emittedWarnings.clear();\n}\n\n// ============================================================================\n// Global Keyframes Management\n// ============================================================================\n\nlet _hasGlobalKeyframes = false;\n\n/**\n * Check if any global keyframes are configured.\n * Uses a pre-computed flag to avoid Object.keys() allocation on every call.\n */\nexport function hasGlobalKeyframes(): boolean {\n return _hasGlobalKeyframes;\n}\n\n/**\n * Get global keyframes configuration.\n * Returns null if no keyframes configured (fast path for zero-overhead).\n */\nexport function getGlobalKeyframes(): Record<string, KeyframesSteps> | null {\n return globalKeyframes;\n}\n\n/**\n * Set global keyframes (called from configure).\n * Internal use only.\n */\nfunction setGlobalKeyframes(keyframes: Record<string, KeyframesSteps>): void {\n if (stylesGenerated) {\n warnOnce(\n 'keyframes-after-styles',\n `[Tasty] Cannot update keyframes after styles have been generated.\\n` +\n `The new keyframes will be ignored.`,\n );\n return;\n }\n globalKeyframes = keyframes;\n _hasGlobalKeyframes = Object.keys(keyframes).length > 0;\n}\n\n// ============================================================================\n// Global Properties Management\n// ============================================================================\n\n/**\n * Check if any global properties are configured.\n * Fast path: returns false if no properties were ever set.\n */\nexport function hasGlobalProperties(): boolean {\n return globalProperties !== null && Object.keys(globalProperties).length > 0;\n}\n\n/**\n * Get global properties configuration.\n * Returns null if no properties configured (fast path for zero-overhead).\n */\nexport function getGlobalProperties(): Record<\n string,\n PropertyDefinition\n> | null {\n return globalProperties;\n}\n\n/**\n * Set global properties (called from configure).\n * Internal use only.\n */\nfunction setGlobalProperties(\n properties: Record<string, PropertyDefinition>,\n): void {\n if (stylesGenerated) {\n warnOnce(\n 'properties-after-styles',\n `[Tasty] Cannot update properties after styles have been generated.\\n` +\n `The new properties will be ignored.`,\n );\n return;\n }\n globalProperties = properties;\n setOnGlobalThis(GTKEY_PROPERTIES, globalProperties);\n}\n\n/**\n * Get the effective properties: DEFAULT_PROPERTIES merged with user-configured\n * properties. User properties override defaults with matching keys.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getEffectiveProperties(): Record<string, PropertyDefinition> {\n const props =\n globalProperties ??\n getFromGlobalThis<Record<string, PropertyDefinition>>(GTKEY_PROPERTIES);\n if (!props) return DEFAULT_PROPERTIES;\n return { ...DEFAULT_PROPERTIES, ...props };\n}\n\n// ============================================================================\n// Global Font Face Management\n// ============================================================================\n\n/**\n * Get global font-face configuration.\n * Returns null if no font faces configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalFontFace(): Record<string, FontFaceInput> | null {\n return (\n globalFontFace ??\n getFromGlobalThis<Record<string, FontFaceInput>>(GTKEY_FONT_FACE) ??\n null\n );\n}\n\n/**\n * Set global font faces (called from configure).\n * Internal use only.\n */\nfunction setGlobalFontFace(fontFace: Record<string, FontFaceInput>): void {\n if (stylesGenerated) {\n warnOnce(\n 'fontface-after-styles',\n `[Tasty] Cannot update fontFace after styles have been generated.\\n` +\n `The new font faces will be ignored.`,\n );\n return;\n }\n globalFontFace = fontFace;\n setOnGlobalThis(GTKEY_FONT_FACE, globalFontFace);\n}\n\n// ============================================================================\n// Global Counter Style Management\n// ============================================================================\n\n/**\n * Get global counter-style configuration.\n * Returns null if no counter styles configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalCounterStyle(): Record<\n string,\n CounterStyleDescriptors\n> | null {\n return (\n globalCounterStyle ??\n getFromGlobalThis<Record<string, CounterStyleDescriptors>>(\n GTKEY_COUNTER_STYLE,\n ) ??\n null\n );\n}\n\n/**\n * Set global counter styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalCounterStyle(\n counterStyle: Record<string, CounterStyleDescriptors>,\n): void {\n if (stylesGenerated) {\n warnOnce(\n 'counterstyle-after-styles',\n `[Tasty] Cannot update counterStyle after styles have been generated.\\n` +\n `The new counter styles will be ignored.`,\n );\n return;\n }\n globalCounterStyle = counterStyle;\n setOnGlobalThis(GTKEY_COUNTER_STYLE, globalCounterStyle);\n}\n\n// ============================================================================\n// Global Recipes Management\n// ============================================================================\n\n/**\n * Check if any global recipes are configured.\n * Fast path: returns false if no recipes were ever set.\n */\nexport function hasGlobalRecipes(): boolean {\n return globalRecipes !== null && Object.keys(globalRecipes).length > 0;\n}\n\n/**\n * Get global recipes configuration.\n * Returns null if no recipes configured (fast path for zero-overhead).\n */\nexport function getGlobalRecipes(): Record<string, RecipeStyles> | null {\n return globalRecipes;\n}\n\n/**\n * Set global recipes (called from configure).\n * Internal use only.\n */\nfunction setGlobalRecipes(recipes: Record<string, RecipeStyles>): void {\n if (stylesGenerated) {\n warnOnce(\n 'recipes-after-styles',\n `[Tasty] Cannot update recipes after styles have been generated.\\n` +\n `The new recipes will be ignored.`,\n );\n return;\n }\n\n // Dev-mode validation\n if (devMode) {\n for (const [name, recipeStyles] of Object.entries(recipes)) {\n if (name === 'none') {\n warnOnce(\n 'recipe-reserved-none',\n `[Tasty] Recipe name \"none\" is reserved. ` +\n `It is used as a keyword meaning \"no base recipes\" ` +\n `(e.g. recipe: 'none / post-recipe'). ` +\n `Choose a different name for your recipe.`,\n );\n }\n\n for (const key of Object.keys(recipeStyles)) {\n if (isSelector(key)) {\n warnOnce(\n `recipe-selector-${name}-${key}`,\n `[Tasty] Recipe \"${name}\" contains sub-element key \"${key}\". ` +\n `Recipes must be flat styles without sub-element keys. ` +\n `Remove the sub-element key from the recipe definition.`,\n );\n }\n if (key === 'recipe') {\n warnOnce(\n `recipe-recursive-${name}`,\n `[Tasty] Recipe \"${name}\" contains a \"recipe\" key. ` +\n `Recipes cannot reference other recipes. ` +\n `Use space-separated names for composition: recipe: 'base elevated'.`,\n );\n }\n }\n }\n }\n\n globalRecipes = recipes;\n}\n\n// ============================================================================\n// Global Token Styles Management\n// ============================================================================\n\n/**\n * Get global token styles for :root injection.\n * Returns null if no tokens configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalConfigTokens(): ConfigTokens | null {\n return (\n globalConfigTokens ?? getFromGlobalThis<ConfigTokens>(GTKEY_TOKENS) ?? null\n );\n}\n\n/**\n * Set global token styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalConfigTokens(styles: ConfigTokens): void {\n if (stylesGenerated) {\n warnOnce(\n 'tokens-after-styles',\n `[Tasty] Cannot update tokens after styles have been generated.\\n` +\n `The new tokens will be ignored.`,\n );\n return;\n }\n globalConfigTokens = globalConfigTokens\n ? { ...globalConfigTokens, ...styles }\n : styles;\n setOnGlobalThis(GTKEY_TOKENS, globalConfigTokens);\n}\n\n/**\n * Check if configuration is locked (styles have been generated)\n */\nexport function isConfigLocked(): boolean {\n return stylesGenerated;\n}\n\n// ============================================================================\n// Configuration API\n// ============================================================================\n\n/**\n * Configure the Tasty style system.\n *\n * Must be called BEFORE any styles are generated (before first render that uses tasty).\n * After styles are generated, configuration is locked and calls to configure() will\n * emit a warning and be ignored.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n *\n * // Configure before app renders\n * configure({\n * nonce: 'abc123',\n * states: {\n * '@mobile': '@media(w < 768px)',\n * '@dark': '@root(theme=dark)',\n * },\n * });\n * ```\n */\nexport function configure(config: Partial<TastyConfig> = {}): void {\n if (stylesGenerated) {\n warnOnce(\n 'configure-after-styles',\n `[Tasty] Cannot call configure() after styles have been generated.\\n` +\n `Configuration must be done before the first render. The configuration will be ignored.`,\n );\n return;\n }\n\n // Collect merged values from plugins first, then override with direct config\n let mergedStates: Record<string, string> = {};\n let mergedUnits: Record<string, string | UnitHandler> = {};\n let mergedFuncs: Record<string, (groups: StyleDetails[]) => string> = {};\n let mergedHandlers: Record<string, StyleHandlerDefinition> = {};\n let mergedReplaceTokens: Record<string, string | number | boolean> = {};\n let mergedConfigTokens: ConfigTokens = {} as ConfigTokens;\n let mergedRecipes: Record<string, RecipeStyles> = {};\n\n // Process plugins in order\n if (config.plugins) {\n for (const plugin of config.plugins) {\n if (plugin.states) {\n mergedStates = { ...mergedStates, ...plugin.states };\n }\n if (plugin.units) {\n mergedUnits = { ...mergedUnits, ...plugin.units };\n }\n if (plugin.funcs) {\n mergedFuncs = { ...mergedFuncs, ...plugin.funcs };\n }\n if (plugin.handlers) {\n mergedHandlers = { ...mergedHandlers, ...plugin.handlers };\n }\n if (plugin.replaceTokens) {\n mergedReplaceTokens = {\n ...mergedReplaceTokens,\n ...plugin.replaceTokens,\n };\n }\n if (plugin.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...plugin.tokens };\n }\n if (plugin.recipes) {\n mergedRecipes = { ...mergedRecipes, ...plugin.recipes };\n }\n }\n }\n\n // Direct config overrides plugins\n if (config.states) {\n mergedStates = { ...mergedStates, ...config.states };\n }\n if (config.units) {\n mergedUnits = { ...mergedUnits, ...config.units };\n }\n if (config.funcs) {\n mergedFuncs = { ...mergedFuncs, ...config.funcs };\n }\n if (config.handlers) {\n mergedHandlers = { ...mergedHandlers, ...config.handlers };\n }\n if (config.replaceTokens) {\n mergedReplaceTokens = { ...mergedReplaceTokens, ...config.replaceTokens };\n }\n if (config.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...config.tokens };\n }\n if (config.recipes) {\n mergedRecipes = { ...mergedRecipes, ...config.recipes };\n }\n\n // Warn on tokens/replaceTokens key conflicts\n if (devMode) {\n const tokenKeys = new Set(Object.keys(mergedConfigTokens));\n for (const key of Object.keys(mergedReplaceTokens)) {\n if (tokenKeys.has(key)) {\n warnOnce(\n `token-conflict-${key}`,\n `[Tasty] Token \"${key}\" is defined in both \\`tokens\\` and \\`replaceTokens\\`. ` +\n `\\`replaceTokens\\` performs parse-time substitution, so the \\`tokens\\` ` +\n `CSS custom property will be injected but never used by Tasty styles. ` +\n `Remove it from one of the two.`,\n );\n }\n }\n }\n\n // Handle color space (must be set before any token processing)\n if (config.colorSpace) {\n setColorSpace(config.colorSpace);\n // Color space affects parser output (e.g. #name.5 → oklch(...) vs rgb(...))\n getGlobalParser().clearCache();\n }\n\n // Handle predefined states\n if (Object.keys(mergedStates).length > 0) {\n setGlobalPredefinedStates(mergedStates);\n }\n\n // Handle parser configuration (merge semantics - extend, not replace)\n const parser = getGlobalParser();\n\n if (config.parserCacheSize !== undefined) {\n parser.updateOptions({ cacheSize: config.parserCacheSize });\n }\n\n if (Object.keys(mergedUnits).length > 0) {\n // Merge with existing units\n const currentUnits = parser.getUnits() ?? CUSTOM_UNITS;\n parser.setUnits({ ...currentUnits, ...mergedUnits });\n }\n\n if (Object.keys(mergedFuncs).length > 0) {\n // Merge with existing funcs\n const currentFuncs = getGlobalFuncs();\n const finalFuncs = { ...currentFuncs, ...mergedFuncs };\n parser.setFuncs(finalFuncs);\n // Also update the global registry so customFunc() continues to work\n Object.assign(currentFuncs, mergedFuncs);\n }\n\n // Handle keyframes\n if (config.keyframes) {\n setGlobalKeyframes(config.keyframes);\n }\n\n // Handle properties\n if (config.properties) {\n setGlobalProperties(config.properties);\n }\n\n // Handle font faces\n if (config.fontFace) {\n setGlobalFontFace(config.fontFace);\n }\n\n // Handle counter styles\n if (config.counterStyle) {\n setGlobalCounterStyle(config.counterStyle);\n }\n\n // Handle custom handlers\n if (Object.keys(mergedHandlers).length > 0) {\n for (const [name, definition] of Object.entries(mergedHandlers)) {\n const handler = normalizeHandlerDefinition(name, definition);\n registerHandler(handler);\n }\n }\n\n // Handle replaceTokens (parse-time substitution)\n if (Object.keys(mergedReplaceTokens).length > 0) {\n const processedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(mergedReplaceTokens)) {\n if (key.startsWith('#')) {\n const normalized = normalizeColorTokenValue(value);\n if (normalized === null) continue;\n processedTokens[key] = String(normalized);\n } else if (value === false) {\n continue;\n } else {\n processedTokens[key] = String(value);\n }\n }\n setGlobalPredefinedTokens(processedTokens);\n }\n\n // Handle tokens (CSS custom properties on :root)\n if (Object.keys(mergedConfigTokens).length > 0) {\n setGlobalConfigTokens(mergedConfigTokens);\n }\n\n // Handle recipes\n if (Object.keys(mergedRecipes).length > 0) {\n setGlobalRecipes(mergedRecipes);\n }\n\n const {\n states: _states,\n parserCacheSize: _parserCacheSize,\n units: _units,\n funcs: _funcs,\n plugins: _plugins,\n keyframes: _keyframes,\n properties: _properties,\n fontFace: _fontFace,\n counterStyle: _counterStyle,\n handlers: _handlers,\n tokens: _tokens,\n replaceTokens: _replaceTokens,\n recipes: _recipes,\n colorSpace: _colorSpace,\n ...injectorConfig\n } = config;\n\n const fullConfig: TastyConfig = {\n ...createDefaultConfig(),\n ...currentConfig,\n ...injectorConfig,\n };\n\n // Store the config\n currentConfig = fullConfig;\n\n // Create/replace the global injector\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n storage[GLOBAL_INJECTOR_KEY] = new StyleInjector(fullConfig);\n}\n\n/**\n * Get the current configuration.\n * If not configured, returns default configuration.\n */\nexport function getConfig(): TastyConfig {\n if (!currentConfig) {\n currentConfig = createDefaultConfig(isTestEnvironment());\n }\n return currentConfig;\n}\n\n/**\n * Get the global injector instance.\n * Auto-configures with defaults if not already configured.\n */\nexport function getGlobalInjector(): StyleInjector {\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n\n if (!storage[GLOBAL_INJECTOR_KEY]) {\n configure();\n }\n\n return storage[GLOBAL_INJECTOR_KEY]!;\n}\n\n/**\n * Reset configuration (for testing only).\n * Clears the global injector and allows reconfiguration.\n */\nexport function resetConfig(): void {\n stylesGenerated = false;\n currentConfig = null;\n globalKeyframes = null;\n _hasGlobalKeyframes = false;\n globalProperties = null;\n globalFontFace = null;\n globalCounterStyle = null;\n globalRecipes = null;\n globalConfigTokens = null;\n clearGlobalThisConfig();\n resetGlobalPredefinedTokens();\n resetHandlers();\n resetColorSpace();\n clearPipelineCache();\n emittedWarnings.clear();\n\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n delete storage[GLOBAL_INJECTOR_KEY];\n}\n\n// Re-export TastyConfig as StyleInjectorConfig for backward compatibility\nexport type { TastyConfig as StyleInjectorConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoUA,MAAM,kCAAkB,IAAI,KAAa;AAEzC,MAAM,UAAU,UAAU;;;;AAK1B,SAAS,SAAS,KAAa,SAAuB;AACpD,KAAI,WAAW,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACxC,kBAAgB,I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C3C,SAAQ,uBAAuB,IAAI,cAAc,WAAW;;;;;;AAO9D,SAAgB,YAAyB;AACvC,KAAI,CAAC,cACH,iBAAgB,oBAAoB,mBAAmB,CAAC;AAE1D,QAAO;;;;;;AAOT,SAAgB,oBAAmC;CACjD,MAAM,UACJ,OAAO,WAAW,cAAc,SAAS;AAE3C,KAAI,CAAC,QAAQ,qBACX,YAAW;AAGb,QAAO,QAAQ;;;;;;AAOjB,SAAgB,cAAoB;AAClC,mBAAkB;AAClB,iBAAgB;AAChB,mBAAkB;AAClB,uBAAsB;AACtB,oBAAmB;AACnB,kBAAiB;AACjB,sBAAqB;AACrB,iBAAgB;AAChB,sBAAqB;AACrB,wBAAuB;AACvB,8BAA6B;AAC7B,gBAAe;AACf,kBAAiB;AACjB,qBAAoB;AACpB,iBAAgB,OAAO;CAEvB,MAAM,UACJ,OAAO,WAAW,cAAc,SAAS;AAC3C,QAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["/**\n * Tasty Configuration Module\n *\n * Centralizes all tasty configuration, including:\n * - Style injector settings (nonce, cleanup thresholds, etc.)\n * - Global predefined states for advanced state mapping\n * - stylesGenerated flag that locks configuration after first style generation\n *\n * Configuration must be done BEFORE any styles are generated.\n * After the first `inject()` call, configuration is locked and attempts to\n * reconfigure will emit a warning and be ignored.\n */\n\nimport { StyleInjector } from './injector/injector';\nimport { clearPipelineCache, isSelector, renderStyles } from './pipeline';\nimport { setGlobalPredefinedStates } from './states';\nimport {\n normalizeHandlerDefinition,\n registerHandler,\n resetHandlers,\n} from './styles/predefined';\nimport { resetColorSpace, setColorSpace } from './utils/color-space';\nimport { isDevEnv } from './utils/is-dev-env';\nimport {\n CUSTOM_UNITS,\n getGlobalFuncs,\n getGlobalParser,\n normalizeColorTokenValue,\n resetGlobalPredefinedTokens,\n setGlobalPredefinedTokens,\n} from './utils/styles';\n\nimport type { ColorSpace } from './utils/color-space';\n\nimport type {\n CounterStyleDescriptors,\n FontFaceInput,\n GCConfig,\n KeyframesSteps,\n PropertyDefinition,\n} from './injector/types';\nimport type { StyleDetails, UnitHandler } from './parser/types';\nimport type { StyleResult } from './pipeline';\nimport type { TastyPlugin } from './plugins/types';\nimport type { RecipeStyles, ConfigTokens } from './styles/types';\nimport type { Styles } from './styles/types';\nimport type { StyleHandlerDefinition } from './utils/styles';\nimport type { TypographyPreset } from './utils/typography';\nimport { generateTypographyTokens } from './utils/typography';\n\n/**\n * Configuration options for the Tasty style system\n */\nexport interface TastyConfig {\n /** CSP nonce for style elements */\n nonce?: string;\n /** Maximum rules per stylesheet (default: 8192) */\n maxRulesPerSheet?: number;\n /** Force text injection mode, auto-detected in test environments (default: auto) */\n forceTextInjection?: boolean;\n /** Enable development mode features: performance metrics and debug info (default: auto) */\n devMode?: boolean;\n /**\n * Global predefined states for advanced state mapping.\n * These are state aliases that can be used in any component.\n * Example: { '@mobile': '@media(w < 920px)', '@dark': '@root(theme=dark)' }\n */\n states?: Record<string, string>;\n /**\n * Parser LRU cache size (default: 1000).\n * Larger values improve performance for apps with many unique style values.\n */\n parserCacheSize?: number;\n /**\n * Custom units for the style parser (merged with built-in units).\n * Units transform numeric values like `2x` → `calc(2 * var(--gap))`.\n * @example { em: 'em', vw: 'vw', custom: (n) => `${n * 10}px` }\n */\n units?: Record<string, string | UnitHandler>;\n /**\n * Custom functions for the style parser (merged with existing).\n * Functions process parsed style groups and return CSS values.\n * @example { myFunc: (groups) => groups.map(g => g.output).join(' ') }\n */\n funcs?: Record<string, (groups: StyleDetails[]) => string>;\n /**\n * Color space used for decomposed color token companion variables.\n * Controls the CSS function and suffix for alpha composition.\n *\n * - `'rgb'` — suffix `-rgb`, e.g. `rgb(var(--name-color-rgb) / .5)`\n * - `'hsl'` — suffix `-hsl`, e.g. `hsl(var(--name-color-hsl) / .5)`\n * - `'oklch'` — suffix `-oklch`, e.g. `oklch(var(--name-color-oklch) / .5)`\n *\n * @default 'oklch'\n */\n colorSpace?: ColorSpace;\n /**\n * Automatically infer and register CSS @property declarations\n * from custom property values found in styles, keyframes, and global config.\n * Covers all types: \\<color\\>, \\<number\\>, \\<length\\>, \\<angle\\>, \\<percentage\\>, \\<time\\>.\n * When false, only explicitly declared @properties are registered.\n * @default true\n */\n autoPropertyTypes?: boolean;\n /**\n * Garbage collection configuration for unused styles.\n * GC is triggered by touch count: every `touchInterval` touches, the\n * oldest unused styles are evicted when their count exceeds `capacity`.\n * @example\n * ```ts\n * configure({\n * gc: { touchInterval: 1000, capacity: 1000 },\n * });\n * ```\n */\n gc?: GCConfig;\n /**\n * Plugins that extend tasty with custom functions, units, or states.\n * Plugins are processed in order, with later plugins overriding earlier ones.\n * @example\n * ```ts\n * import { okhslPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhslPlugin()],\n * });\n * ```\n */\n plugins?: TastyPlugin[];\n /**\n * Global keyframes definitions that can be referenced by animation names in styles.\n * Keys are animation names, values are keyframes step definitions.\n * Keyframes are only injected when actually used in styles.\n * @example\n * ```ts\n * configure({\n * keyframes: {\n * fadeIn: { from: { opacity: 0 }, to: { opacity: 1 } },\n * pulse: { '0%, 100%': { transform: 'scale(1)' }, '50%': { transform: 'scale(1.05)' } },\n * },\n * });\n * ```\n */\n keyframes?: Record<string, KeyframesSteps>;\n /**\n * Global CSS @property definitions for custom properties.\n * Keys use tasty token syntax ($name for properties, #name for colors).\n *\n * Tasty ships with `DEFAULT_PROPERTIES` (e.g. `$gap`, `$radius`, `#white`,\n * `#black`, `#clear`, `#border`, etc.) that are always included.\n * Properties you specify here are merged on top, so you can override any\n * default by using the same key.\n *\n * For color tokens (#name), `syntax: '<color>'` is auto-set and\n * `initialValue` defaults to `'transparent'` if not specified.\n *\n * @example\n * ```ts\n * configure({\n * properties: {\n * '$rotation': { syntax: '<angle>', initialValue: '0deg' },\n * '$scale': { syntax: '<number>', inherits: false, initialValue: 1 },\n * '#accent': { initialValue: 'purple' }, // syntax: '<color>' auto-set\n * // Override a default property:\n * '$gap': { syntax: '<length>', inherits: true, initialValue: '8px' },\n * },\n * });\n *\n * // Now use in styles - properties are registered when component renders:\n * const Spinner = tasty({\n * styles: {\n * transform: 'rotate($rotation)',\n * transition: '$$rotation 0.3s', // outputs: --rotation 0.3s\n * },\n * });\n * ```\n */\n properties?: Record<string, PropertyDefinition>;\n /**\n * Global @font-face definitions.\n * Keys are font-family names, values are descriptors or arrays of descriptors\n * (for multiple weights/styles of the same family).\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * fontFace: {\n * 'Brand Sans': [\n * { src: 'url(\"/fonts/brand-regular.woff2\") format(\"woff2\")', fontWeight: 400, fontDisplay: 'swap' },\n * { src: 'url(\"/fonts/brand-bold.woff2\") format(\"woff2\")', fontWeight: 700, fontDisplay: 'swap' },\n * ],\n * Icons: { src: 'url(\"/fonts/icons.woff2\") format(\"woff2\")', fontDisplay: 'block' },\n * },\n * });\n * ```\n */\n fontFace?: Record<string, FontFaceInput>;\n /**\n * Global @counter-style definitions.\n * Keys are counter-style names, values are descriptor objects.\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * counterStyle: {\n * thumbs: { system: 'cyclic', symbols: '\"👍\"', suffix: '\" \"' },\n * },\n * });\n * ```\n */\n counterStyle?: Record<string, CounterStyleDescriptors>;\n /**\n * Custom style handlers that transform style properties into CSS declarations.\n * Handlers replace built-in handlers for the same style name.\n * @example\n * ```ts\n * import { styleHandlers } from '@tenphi/tasty';\n *\n * configure({\n * handlers: {\n * // Override fill with custom behavior\n * fill: ({ fill }) => {\n * if (fill?.startsWith('gradient:')) {\n * return { background: fill.slice(9) };\n * }\n * return styleHandlers.fill({ fill });\n * },\n * // Add new custom style\n * elevation: ({ elevation }) => {\n * const level = parseInt(elevation) || 1;\n * return {\n * 'box-shadow': `0 ${level * 2}px ${level * 4}px rgba(0,0,0,0.1)`,\n * 'z-index': String(level * 100),\n * };\n * },\n * },\n * });\n * ```\n */\n handlers?: Record<string, StyleHandlerDefinition>;\n /**\n * Design tokens injected as CSS custom properties on `:root`.\n * Values are parsed through the Tasty DSL. Supports state maps\n * for responsive/theme-aware tokens.\n *\n * - `$name` keys become `--name` CSS custom properties\n * - `#name` keys become `--name-color` and `--name-color-{colorSpace}` properties\n *\n * Tokens are injected once when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * tokens: {\n * '$gap': '4px',\n * '#primary': {\n * '': '#purple',\n * '@dark': '#light-purple',\n * },\n * },\n * });\n * ```\n */\n tokens?: ConfigTokens;\n /**\n * Predefined tokens that are replaced during style parsing (parse-time substitution).\n * Use `$name` for custom properties and `#name` for color tokens.\n * Values are substituted inline before CSS generation, unlike `tokens` which\n * inject CSS custom properties on `:root`.\n *\n * For color tokens (#name), boolean `true` is converted to `transparent`.\n *\n * @example\n * ```ts\n * configure({\n * replaceTokens: {\n * $spacing: '2x',\n * '#accent': '#purple',\n * '#overlay': true, // → transparent\n * },\n * });\n *\n * // Now use in styles - tokens are replaced at parse time:\n * const Card = tasty({\n * styles: {\n * padding: '$spacing', // → calc(2 * var(--gap))\n * fill: '#accent', // → var(--purple-color)\n * },\n * });\n * ```\n */\n replaceTokens?: Record<`$${string}`, string | number | boolean> &\n Record<`#${string}`, string | number | boolean>;\n /**\n * Predefined style recipes -- named style bundles that can be applied via `recipe` style property.\n * Recipe values are flat tasty styles (no sub-element keys). They may contain base styles,\n * tokens (`$name`/`#name` definitions), local states, `@keyframes`, and `@properties`.\n *\n * Components reference recipes via: `recipe: 'name1 name2'` in their styles.\n * Use `/` to separate base recipes from post recipes: `recipe: 'base1 base2 / post1'`.\n * Use `none` to skip base recipes: `recipe: 'none / post1'`.\n * Resolution order: `base_recipes → component styles → post_recipes`.\n *\n * Recipes cannot reference other recipes.\n *\n * @example\n * ```ts\n * configure({\n * recipes: {\n * card: { padding: '4x', fill: '#surface', radius: '1r', border: true },\n * elevated: { shadow: '2x 2x 4x #shadow' },\n * },\n * });\n *\n * // Usage in styles:\n * const Card = tasty({\n * styles: {\n * recipe: 'card elevated',\n * color: '#text', // Overrides recipe values\n * },\n * });\n * ```\n */\n recipes?: Record<string, RecipeStyles>;\n /**\n * Typography presets — shorthand for `generateTypographyTokens()`.\n * Accepts the same input and internally generates typography tokens\n * that are merged into `tokens`. Explicit `tokens` override preset-generated ones.\n *\n * @example\n * ```ts\n * configure({\n * presets: {\n * h1: { fontSize: '32px', lineHeight: '1.2', fontWeight: '700' },\n * t2: { fontSize: '16px', lineHeight: '1.5', fontWeight: '400' },\n * },\n * tokens: {\n * // Overrides the preset-generated $t2-font-weight\n * '$t2-font-weight': { '': '400', '@dark': '300' },\n * },\n * });\n * ```\n */\n presets?: Record<string, TypographyPreset>;\n /**\n * Global Tasty styles keyed by CSS selector.\n * Each entry applies the full Tasty style syntax (style properties,\n * tokens, state maps, selector-based sub-styling) to the given selector.\n * Injected alongside `:root` tokens when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * globalStyles: {\n * body: { fill: '#surface', color: '#text', preset: 't2', margin: 0 },\n * html: { overflow: 'hidden' },\n * },\n * });\n * ```\n */\n globalStyles?: Record<string, Styles>;\n}\n\n// Warnings tracking to avoid duplicates\nconst emittedWarnings = new Set<string>();\n\nconst devMode = isDevEnv();\n\n/**\n * Emit a warning only once\n */\nfunction warnOnce(key: string, message: string): void {\n if (devMode && !emittedWarnings.has(key)) {\n emittedWarnings.add(key);\n console.warn(message);\n }\n}\n\n// ============================================================================\n// Configuration State\n// ============================================================================\n\n// Track whether styles have been generated (locks configuration)\nlet stylesGenerated = false;\n\n// Current configuration (null until first configure() or auto-configured on first use)\nlet currentConfig: TastyConfig | null = null;\n\n// Global keyframes storage (null = no keyframes configured, empty object checked via hasGlobalKeyframes)\nlet globalKeyframes: Record<string, KeyframesSteps> | null = null;\n\n// Global font-face storage (null = no font faces configured)\nlet globalFontFace: Record<string, FontFaceInput> | null = null;\n\n// Global counter-style storage (null = no counter styles configured)\nlet globalCounterStyle: Record<string, CounterStyleDescriptors> | null = null;\n\n// Global properties storage (null = no properties configured)\nlet globalProperties: Record<string, PropertyDefinition> | null = null;\n\n// Global recipes storage (null = no recipes configured)\nlet globalRecipes: Record<string, RecipeStyles> | null = null;\n\n// Global token styles storage (injected as :root CSS custom properties)\nlet globalConfigTokens: ConfigTokens | null = null;\n\n// Global styles storage (injected as CSS for configured selectors)\nlet globalStyles: Record<string, Styles> | null = null;\n\n// ============================================================================\n// Cross-module config sharing via globalThis\n//\n// Frameworks like Astro may load middleware and page components from\n// separate module graphs, creating duplicate module-level state.\n// Config values read by SSR collector's collectInternals() are mirrored\n// to globalThis so they're accessible regardless of which module instance\n// the collector was loaded from.\n// ============================================================================\n\nconst GTKEY_TOKENS = '__tasty_cfg_tokens__';\nconst GTKEY_FONT_FACE = '__tasty_cfg_font_face__';\nconst GTKEY_COUNTER_STYLE = '__tasty_cfg_counter_style__';\nconst GTKEY_PROPERTIES = '__tasty_cfg_properties__';\nconst GTKEY_GLOBAL_STYLES = '__tasty_cfg_global_styles__';\n\nfunction setOnGlobalThis(key: string, value: unknown): void {\n (globalThis as Record<string, unknown>)[key] = value;\n}\n\nfunction getFromGlobalThis<T>(key: string): T | undefined {\n return (globalThis as Record<string, unknown>)[key] as T | undefined;\n}\n\nfunction clearGlobalThisConfig(): void {\n const g = globalThis as Record<string, unknown>;\n delete g[GTKEY_TOKENS];\n delete g[GTKEY_FONT_FACE];\n delete g[GTKEY_COUNTER_STYLE];\n delete g[GTKEY_PROPERTIES];\n delete g[GTKEY_GLOBAL_STYLES];\n}\n\n/**\n * Default properties shipped with tasty.\n * These are always included unless explicitly overridden via `configure({ properties })`.\n * Keys use tasty token syntax (#name for colors, $name for other properties).\n *\n * For properties with CSS @property-compatible types (length, time, number, color),\n * an `initialValue` is provided so the property works even without a project-level token.\n */\nexport const DEFAULT_PROPERTIES: Record<string, PropertyDefinition> = {\n // Used by dual-fill feature to enable CSS transitions on the second fill color\n '#tasty-second-fill': {\n inherits: false,\n initialValue: 'transparent',\n },\n // Current color context variable (set by the color style handler).\n '#current': {\n inherits: true,\n initialValue: 'transparent',\n },\n // White and black are fundamental colors that need explicit initial values.\n '#white': {\n inherits: true,\n initialValue: 'rgb(255 255 255)',\n },\n '#black': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n // Shorthand for transparent\n '#clear': {\n inherits: true,\n initialValue: 'transparent',\n },\n // Default border color\n '#border': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n\n // ---- Core design tokens used by style handlers ----\n // These provide sensible defaults so tasty works standalone without a design system.\n // Consuming projects (e.g. uikit) override these by defining tokens on :root.\n\n $gap: {\n syntax: '<length>',\n inherits: true,\n initialValue: '4px',\n },\n $radius: {\n syntax: '<length>',\n inherits: true,\n initialValue: '6px',\n },\n '$border-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '1px',\n },\n '$outline-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '3px',\n },\n $transition: {\n syntax: '<time>',\n inherits: true,\n initialValue: '80ms',\n },\n // Used by radius.ts for `radius=\"leaf\"` modifier\n '$sharp-radius': {\n syntax: '<length>',\n inherits: true,\n initialValue: '0px',\n },\n // Used by preset.ts for `preset=\"name / strong\"`\n '$bold-font-weight': {\n syntax: '<number>',\n inherits: true,\n initialValue: '700',\n },\n // Used by preset.ts as fallback font stacks\n '$font-sans-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'system-ui, -apple-system, \"Segoe UI\", Roboto, Helvetica, Arial, \"Apple Color Emoji\", \"Segoe UI Emoji\", sans-serif',\n },\n '$font-mono-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace',\n },\n};\n\n// Global injector instance key\nconst GLOBAL_INJECTOR_KEY = '__TASTY_GLOBAL_INJECTOR__';\n\ninterface TastyGlobalStorage {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n}\n\ndeclare global {\n interface Window {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n }\n\n var __TASTY_GLOBAL_INJECTOR__: StyleInjector | undefined;\n}\n\n/**\n * Detect if we're running in a test environment\n */\nexport function isTestEnvironment(): boolean {\n // Check Node.js environment\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n return true;\n }\n\n // Check for test runner globals (safely)\n if (typeof global !== 'undefined') {\n const g = global as unknown as Record<string, unknown>;\n if (g.vi || g.jest || g.expect || g.describe || g.it) {\n return true;\n }\n }\n\n // Check for jsdom environment (common in tests)\n if (\n typeof window !== 'undefined' &&\n window.navigator?.userAgent?.includes('jsdom')\n ) {\n return true;\n }\n\n // Check for other test runners\n if (typeof globalThis !== 'undefined') {\n const gt = globalThis as unknown as Record<string, unknown>;\n if (gt.vitest || gt.mocha) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Create default configuration with optional test environment detection\n */\nfunction createDefaultConfig(isTest?: boolean): TastyConfig {\n return {\n maxRulesPerSheet: 8192,\n forceTextInjection: isTest ?? false,\n devMode: isDevEnv(),\n };\n}\n\n// ============================================================================\n// stylesGenerated Flag Management\n// ============================================================================\n\n/**\n * Mark that styles have been generated (called by injector on first inject)\n * This locks the configuration - no further changes allowed.\n * Also injects internal and global properties.\n */\nexport function markStylesGenerated(): void {\n if (stylesGenerated) return; // Already marked, skip\n\n stylesGenerated = true;\n\n // When SSR styles are already in the document, the SSR collector's\n // collectInternals() already rendered tokens, @property, globalStyles,\n // @font-face, and @counter-style. Skip client-side injection to avoid\n // duplicate CSS rules.\n if (\n typeof document !== 'undefined' &&\n document.querySelector('style[data-tasty-ssr]')\n ) {\n warnOnce(\n 'ssr-globals-skip',\n '[Tasty] SSR styles detected — skipping client-side global CSS injection to avoid duplicates.',\n );\n return;\n }\n\n const injector = getGlobalInjector();\n\n // Inject all properties (defaults merged with user-configured overrides)\n for (const [token, definition] of Object.entries(getEffectiveProperties())) {\n injector.property(token, definition);\n }\n\n // Inject global @font-face rules (eagerly — fonts should be available before render)\n if (globalFontFace && Object.keys(globalFontFace).length > 0) {\n for (const [family, input] of Object.entries(globalFontFace)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n injector.fontFace(family, desc);\n }\n }\n }\n\n // Inject global @counter-style rules (eagerly)\n if (globalCounterStyle && Object.keys(globalCounterStyle).length > 0) {\n for (const [name, descriptors] of Object.entries(globalCounterStyle)) {\n injector.counterStyle(name, descriptors);\n }\n }\n\n // Inject configured tokens as :root CSS custom properties\n if (globalConfigTokens && Object.keys(globalConfigTokens).length > 0) {\n const tokenRules = renderStyles(\n globalConfigTokens,\n ':root',\n ) as StyleResult[];\n if (tokenRules.length > 0) {\n injector.injectGlobal(tokenRules);\n }\n }\n\n // Inject configured global styles\n if (globalStyles) {\n for (const [selector, styles] of Object.entries(globalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n injector.injectGlobal(rules);\n }\n }\n }\n }\n}\n\n/**\n * Check if styles have been generated (configuration is locked)\n */\nexport function hasStylesGenerated(): boolean {\n return stylesGenerated;\n}\n\n/**\n * Reset styles generated flag (for testing only)\n */\nexport function resetStylesGenerated(): void {\n stylesGenerated = false;\n emittedWarnings.clear();\n}\n\n// ============================================================================\n// Global Keyframes Management\n// ============================================================================\n\nlet _hasGlobalKeyframes = false;\n\n/**\n * Check if any global keyframes are configured.\n * Uses a pre-computed flag to avoid Object.keys() allocation on every call.\n */\nexport function hasGlobalKeyframes(): boolean {\n return _hasGlobalKeyframes;\n}\n\n/**\n * Get global keyframes configuration.\n * Returns null if no keyframes configured (fast path for zero-overhead).\n */\nexport function getGlobalKeyframes(): Record<string, KeyframesSteps> | null {\n return globalKeyframes;\n}\n\n/**\n * Set global keyframes (called from configure).\n * Internal use only.\n */\nfunction setGlobalKeyframes(keyframes: Record<string, KeyframesSteps>): void {\n if (stylesGenerated) {\n warnOnce(\n 'keyframes-after-styles',\n `[Tasty] Cannot update keyframes after styles have been generated.\\n` +\n `The new keyframes will be ignored.`,\n );\n return;\n }\n globalKeyframes = keyframes;\n _hasGlobalKeyframes = Object.keys(keyframes).length > 0;\n}\n\n// ============================================================================\n// Global Properties Management\n// ============================================================================\n\n/**\n * Check if any global properties are configured.\n * Fast path: returns false if no properties were ever set.\n */\nexport function hasGlobalProperties(): boolean {\n return globalProperties !== null && Object.keys(globalProperties).length > 0;\n}\n\n/**\n * Get global properties configuration.\n * Returns null if no properties configured (fast path for zero-overhead).\n */\nexport function getGlobalProperties(): Record<\n string,\n PropertyDefinition\n> | null {\n return globalProperties;\n}\n\n/**\n * Set global properties (called from configure).\n * Internal use only.\n */\nfunction setGlobalProperties(\n properties: Record<string, PropertyDefinition>,\n): void {\n if (stylesGenerated) {\n warnOnce(\n 'properties-after-styles',\n `[Tasty] Cannot update properties after styles have been generated.\\n` +\n `The new properties will be ignored.`,\n );\n return;\n }\n globalProperties = properties;\n setOnGlobalThis(GTKEY_PROPERTIES, globalProperties);\n}\n\n/**\n * Get the effective properties: DEFAULT_PROPERTIES merged with user-configured\n * properties. User properties override defaults with matching keys.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getEffectiveProperties(): Record<string, PropertyDefinition> {\n const props =\n globalProperties ??\n getFromGlobalThis<Record<string, PropertyDefinition>>(GTKEY_PROPERTIES);\n if (!props) return DEFAULT_PROPERTIES;\n return { ...DEFAULT_PROPERTIES, ...props };\n}\n\n// ============================================================================\n// Global Font Face Management\n// ============================================================================\n\n/**\n * Get global font-face configuration.\n * Returns null if no font faces configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalFontFace(): Record<string, FontFaceInput> | null {\n return (\n globalFontFace ??\n getFromGlobalThis<Record<string, FontFaceInput>>(GTKEY_FONT_FACE) ??\n null\n );\n}\n\n/**\n * Set global font faces (called from configure).\n * Internal use only.\n */\nfunction setGlobalFontFace(fontFace: Record<string, FontFaceInput>): void {\n if (stylesGenerated) {\n warnOnce(\n 'fontface-after-styles',\n `[Tasty] Cannot update fontFace after styles have been generated.\\n` +\n `The new font faces will be ignored.`,\n );\n return;\n }\n globalFontFace = fontFace;\n setOnGlobalThis(GTKEY_FONT_FACE, globalFontFace);\n}\n\n// ============================================================================\n// Global Counter Style Management\n// ============================================================================\n\n/**\n * Get global counter-style configuration.\n * Returns null if no counter styles configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalCounterStyle(): Record<\n string,\n CounterStyleDescriptors\n> | null {\n return (\n globalCounterStyle ??\n getFromGlobalThis<Record<string, CounterStyleDescriptors>>(\n GTKEY_COUNTER_STYLE,\n ) ??\n null\n );\n}\n\n/**\n * Set global counter styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalCounterStyle(\n counterStyle: Record<string, CounterStyleDescriptors>,\n): void {\n if (stylesGenerated) {\n warnOnce(\n 'counterstyle-after-styles',\n `[Tasty] Cannot update counterStyle after styles have been generated.\\n` +\n `The new counter styles will be ignored.`,\n );\n return;\n }\n globalCounterStyle = counterStyle;\n setOnGlobalThis(GTKEY_COUNTER_STYLE, globalCounterStyle);\n}\n\n// ============================================================================\n// Global Recipes Management\n// ============================================================================\n\n/**\n * Check if any global recipes are configured.\n * Fast path: returns false if no recipes were ever set.\n */\nexport function hasGlobalRecipes(): boolean {\n return globalRecipes !== null && Object.keys(globalRecipes).length > 0;\n}\n\n/**\n * Get global recipes configuration.\n * Returns null if no recipes configured (fast path for zero-overhead).\n */\nexport function getGlobalRecipes(): Record<string, RecipeStyles> | null {\n return globalRecipes;\n}\n\n/**\n * Set global recipes (called from configure).\n * Internal use only.\n */\nfunction setGlobalRecipes(recipes: Record<string, RecipeStyles>): void {\n if (stylesGenerated) {\n warnOnce(\n 'recipes-after-styles',\n `[Tasty] Cannot update recipes after styles have been generated.\\n` +\n `The new recipes will be ignored.`,\n );\n return;\n }\n\n // Dev-mode validation\n if (devMode) {\n for (const [name, recipeStyles] of Object.entries(recipes)) {\n if (name === 'none') {\n warnOnce(\n 'recipe-reserved-none',\n `[Tasty] Recipe name \"none\" is reserved. ` +\n `It is used as a keyword meaning \"no base recipes\" ` +\n `(e.g. recipe: 'none / post-recipe'). ` +\n `Choose a different name for your recipe.`,\n );\n }\n\n for (const key of Object.keys(recipeStyles)) {\n if (isSelector(key)) {\n warnOnce(\n `recipe-selector-${name}-${key}`,\n `[Tasty] Recipe \"${name}\" contains sub-element key \"${key}\". ` +\n `Recipes must be flat styles without sub-element keys. ` +\n `Remove the sub-element key from the recipe definition.`,\n );\n }\n if (key === 'recipe') {\n warnOnce(\n `recipe-recursive-${name}`,\n `[Tasty] Recipe \"${name}\" contains a \"recipe\" key. ` +\n `Recipes cannot reference other recipes. ` +\n `Use space-separated names for composition: recipe: 'base elevated'.`,\n );\n }\n }\n }\n }\n\n globalRecipes = recipes;\n}\n\n// ============================================================================\n// Global Token Styles Management\n// ============================================================================\n\n/**\n * Get global token styles for :root injection.\n * Returns null if no tokens configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalConfigTokens(): ConfigTokens | null {\n return (\n globalConfigTokens ?? getFromGlobalThis<ConfigTokens>(GTKEY_TOKENS) ?? null\n );\n}\n\n/**\n * Set global token styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalConfigTokens(styles: ConfigTokens): void {\n if (stylesGenerated) {\n warnOnce(\n 'tokens-after-styles',\n `[Tasty] Cannot update tokens after styles have been generated.\\n` +\n `The new tokens will be ignored.`,\n );\n return;\n }\n globalConfigTokens = globalConfigTokens\n ? { ...globalConfigTokens, ...styles }\n : styles;\n setOnGlobalThis(GTKEY_TOKENS, globalConfigTokens);\n}\n\n// ============================================================================\n// Global Styles Management\n// ============================================================================\n\n/**\n * Get configured global styles for injection.\n * Returns null if no global styles configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalStyles(): Record<string, Styles> | null {\n return (\n globalStyles ??\n getFromGlobalThis<Record<string, Styles>>(GTKEY_GLOBAL_STYLES) ??\n null\n );\n}\n\n/**\n * Set configured global styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalStyles(styles: Record<string, Styles>): void {\n if (stylesGenerated) {\n warnOnce(\n 'globalStyles-after-styles',\n `[Tasty] Cannot update globalStyles after styles have been generated.\\n` +\n `The new global styles will be ignored.`,\n );\n return;\n }\n if (globalStyles) {\n for (const [selector, selectorStyles] of Object.entries(styles)) {\n globalStyles[selector] = globalStyles[selector]\n ? { ...globalStyles[selector], ...selectorStyles }\n : selectorStyles;\n }\n } else {\n globalStyles = { ...styles };\n }\n setOnGlobalThis(GTKEY_GLOBAL_STYLES, globalStyles);\n}\n\n/**\n * Check if configuration is locked (styles have been generated)\n */\nexport function isConfigLocked(): boolean {\n return stylesGenerated;\n}\n\n// ============================================================================\n// Configuration API\n// ============================================================================\n\n/**\n * Configure the Tasty style system.\n *\n * Must be called BEFORE any styles are generated (before first render that uses tasty).\n * After styles are generated, configuration is locked and calls to configure() will\n * emit a warning and be ignored.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n *\n * // Configure before app renders\n * configure({\n * nonce: 'abc123',\n * states: {\n * '@mobile': '@media(w < 768px)',\n * '@dark': '@root(theme=dark)',\n * },\n * });\n * ```\n */\nexport function configure(config: Partial<TastyConfig> = {}): void {\n if (stylesGenerated) {\n warnOnce(\n 'configure-after-styles',\n `[Tasty] Cannot call configure() after styles have been generated.\\n` +\n `Configuration must be done before the first render. The configuration will be ignored.`,\n );\n return;\n }\n\n // Collect merged values from plugins first, then override with direct config\n let mergedStates: Record<string, string> = {};\n let mergedUnits: Record<string, string | UnitHandler> = {};\n let mergedFuncs: Record<string, (groups: StyleDetails[]) => string> = {};\n let mergedHandlers: Record<string, StyleHandlerDefinition> = {};\n let mergedReplaceTokens: Record<string, string | number | boolean> = {};\n let mergedConfigTokens: ConfigTokens = {} as ConfigTokens;\n let mergedRecipes: Record<string, RecipeStyles> = {};\n let mergedPresets: Record<string, TypographyPreset> = {};\n const mergedGlobalStyles: Record<string, Styles> = {};\n\n // Process plugins in order\n if (config.plugins) {\n for (const plugin of config.plugins) {\n if (plugin.states) {\n mergedStates = { ...mergedStates, ...plugin.states };\n }\n if (plugin.units) {\n mergedUnits = { ...mergedUnits, ...plugin.units };\n }\n if (plugin.funcs) {\n mergedFuncs = { ...mergedFuncs, ...plugin.funcs };\n }\n if (plugin.handlers) {\n mergedHandlers = { ...mergedHandlers, ...plugin.handlers };\n }\n if (plugin.replaceTokens) {\n mergedReplaceTokens = {\n ...mergedReplaceTokens,\n ...plugin.replaceTokens,\n };\n }\n if (plugin.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...plugin.tokens };\n }\n if (plugin.recipes) {\n mergedRecipes = { ...mergedRecipes, ...plugin.recipes };\n }\n if (plugin.presets) {\n mergedPresets = { ...mergedPresets, ...plugin.presets };\n }\n if (plugin.globalStyles) {\n for (const [sel, styles] of Object.entries(plugin.globalStyles)) {\n mergedGlobalStyles[sel] = mergedGlobalStyles[sel]\n ? { ...mergedGlobalStyles[sel], ...styles }\n : styles;\n }\n }\n }\n }\n\n // Direct config overrides plugins\n if (config.states) {\n mergedStates = { ...mergedStates, ...config.states };\n }\n if (config.units) {\n mergedUnits = { ...mergedUnits, ...config.units };\n }\n if (config.funcs) {\n mergedFuncs = { ...mergedFuncs, ...config.funcs };\n }\n if (config.handlers) {\n mergedHandlers = { ...mergedHandlers, ...config.handlers };\n }\n if (config.replaceTokens) {\n mergedReplaceTokens = { ...mergedReplaceTokens, ...config.replaceTokens };\n }\n if (config.presets) {\n mergedPresets = { ...mergedPresets, ...config.presets };\n }\n\n // Generate typography tokens from presets and merge UNDER explicit tokens\n if (Object.keys(mergedPresets).length > 0) {\n const presetTokens = generateTypographyTokens(mergedPresets);\n mergedConfigTokens = {\n ...presetTokens,\n ...mergedConfigTokens,\n };\n }\n\n if (config.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...config.tokens };\n }\n if (config.recipes) {\n mergedRecipes = { ...mergedRecipes, ...config.recipes };\n }\n if (config.globalStyles) {\n for (const [sel, styles] of Object.entries(config.globalStyles)) {\n mergedGlobalStyles[sel] = mergedGlobalStyles[sel]\n ? { ...mergedGlobalStyles[sel], ...styles }\n : styles;\n }\n }\n\n // Warn on tokens/replaceTokens key conflicts\n if (devMode) {\n const tokenKeys = new Set(Object.keys(mergedConfigTokens));\n for (const key of Object.keys(mergedReplaceTokens)) {\n if (tokenKeys.has(key)) {\n warnOnce(\n `token-conflict-${key}`,\n `[Tasty] Token \"${key}\" is defined in both \\`tokens\\` and \\`replaceTokens\\`. ` +\n `\\`replaceTokens\\` performs parse-time substitution, so the \\`tokens\\` ` +\n `CSS custom property will be injected but never used by Tasty styles. ` +\n `Remove it from one of the two.`,\n );\n }\n }\n }\n\n // Handle color space (must be set before any token processing)\n if (config.colorSpace) {\n setColorSpace(config.colorSpace);\n // Color space affects parser output (e.g. #name.5 → oklch(...) vs rgb(...))\n getGlobalParser().clearCache();\n }\n\n // Handle predefined states\n if (Object.keys(mergedStates).length > 0) {\n setGlobalPredefinedStates(mergedStates);\n }\n\n // Handle parser configuration (merge semantics - extend, not replace)\n const parser = getGlobalParser();\n\n if (config.parserCacheSize !== undefined) {\n parser.updateOptions({ cacheSize: config.parserCacheSize });\n }\n\n if (Object.keys(mergedUnits).length > 0) {\n // Merge with existing units\n const currentUnits = parser.getUnits() ?? CUSTOM_UNITS;\n parser.setUnits({ ...currentUnits, ...mergedUnits });\n }\n\n if (Object.keys(mergedFuncs).length > 0) {\n // Merge with existing funcs\n const currentFuncs = getGlobalFuncs();\n const finalFuncs = { ...currentFuncs, ...mergedFuncs };\n parser.setFuncs(finalFuncs);\n // Also update the global registry so customFunc() continues to work\n Object.assign(currentFuncs, mergedFuncs);\n }\n\n // Handle keyframes\n if (config.keyframes) {\n setGlobalKeyframes(config.keyframes);\n }\n\n // Handle properties\n if (config.properties) {\n setGlobalProperties(config.properties);\n }\n\n // Handle font faces\n if (config.fontFace) {\n setGlobalFontFace(config.fontFace);\n }\n\n // Handle counter styles\n if (config.counterStyle) {\n setGlobalCounterStyle(config.counterStyle);\n }\n\n // Handle custom handlers\n if (Object.keys(mergedHandlers).length > 0) {\n for (const [name, definition] of Object.entries(mergedHandlers)) {\n const handler = normalizeHandlerDefinition(name, definition);\n registerHandler(handler);\n }\n }\n\n // Handle replaceTokens (parse-time substitution)\n if (Object.keys(mergedReplaceTokens).length > 0) {\n const processedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(mergedReplaceTokens)) {\n if (key.startsWith('#')) {\n const normalized = normalizeColorTokenValue(value);\n if (normalized === null) continue;\n processedTokens[key] = String(normalized);\n } else if (value === false) {\n continue;\n } else {\n processedTokens[key] = String(value);\n }\n }\n setGlobalPredefinedTokens(processedTokens);\n }\n\n // Handle tokens (CSS custom properties on :root)\n if (Object.keys(mergedConfigTokens).length > 0) {\n setGlobalConfigTokens(mergedConfigTokens);\n }\n\n // Handle recipes\n if (Object.keys(mergedRecipes).length > 0) {\n setGlobalRecipes(mergedRecipes);\n }\n\n // Handle global styles\n if (Object.keys(mergedGlobalStyles).length > 0) {\n setGlobalStyles(mergedGlobalStyles);\n }\n\n const {\n states: _states,\n parserCacheSize: _parserCacheSize,\n units: _units,\n funcs: _funcs,\n plugins: _plugins,\n keyframes: _keyframes,\n properties: _properties,\n fontFace: _fontFace,\n counterStyle: _counterStyle,\n handlers: _handlers,\n tokens: _tokens,\n replaceTokens: _replaceTokens,\n recipes: _recipes,\n colorSpace: _colorSpace,\n presets: _presets,\n globalStyles: _globalStyles,\n ...injectorConfig\n } = config;\n\n const fullConfig: TastyConfig = {\n ...createDefaultConfig(),\n ...currentConfig,\n ...injectorConfig,\n };\n\n // Store the config\n currentConfig = fullConfig;\n\n // Create/replace the global injector\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n storage[GLOBAL_INJECTOR_KEY] = new StyleInjector(fullConfig);\n}\n\n/**\n * Get the current configuration.\n * If not configured, returns default configuration.\n */\nexport function getConfig(): TastyConfig {\n if (!currentConfig) {\n currentConfig = createDefaultConfig(isTestEnvironment());\n }\n return currentConfig;\n}\n\n/**\n * Get the global injector instance.\n * Auto-configures with defaults if not already configured.\n */\nexport function getGlobalInjector(): StyleInjector {\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n\n if (!storage[GLOBAL_INJECTOR_KEY]) {\n configure();\n }\n\n return storage[GLOBAL_INJECTOR_KEY]!;\n}\n\n/**\n * Reset configuration (for testing only).\n * Clears the global injector and allows reconfiguration.\n */\nexport function resetConfig(): void {\n stylesGenerated = false;\n currentConfig = null;\n globalKeyframes = null;\n _hasGlobalKeyframes = false;\n globalProperties = null;\n globalFontFace = null;\n globalCounterStyle = null;\n globalRecipes = null;\n globalConfigTokens = null;\n globalStyles = null;\n clearGlobalThisConfig();\n resetGlobalPredefinedTokens();\n resetHandlers();\n resetColorSpace();\n clearPipelineCache();\n emittedWarnings.clear();\n\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n delete storage[GLOBAL_INJECTOR_KEY];\n}\n\n// Re-export TastyConfig as StyleInjectorConfig for backward compatibility\nexport type { TastyConfig as StyleInjectorConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4WA,MAAM,kCAAkB,IAAI,KAAa;AAEzC,MAAM,UAAU,UAAU;;;;AAK1B,SAAS,SAAS,KAAa,SAAuB;AACpD,KAAI,WAAW,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACxC,kBAAgB,IAAI,IAAI;AACxB,UAAQ,KAAK,QAAQ;;;AASzB,IAAI,kBAAkB;AAGtB,IAAI,gBAAoC;AAGxC,IAAI,kBAAyD;AAG7D,IAAI,iBAAuD;AAG3D,IAAI,qBAAqE;AAGzE,IAAI,mBAA8D;AAGlE,IAAI,gBAAqD;AAGzD,IAAI,qBAA0C;AAG9C,IAAI,eAA8C;AAYlD,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAE5B,SAAS,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D,MAAM,UACJ,OAAO,WAAW,cAAc,SAAS;AAE3C,KAAI,CAAC,QAAQ,qBACX,YAAW;AAGb,QAAO,QAAQ;;;;;;AAOjB,SAAgB,cAAoB;AAClC,mBAAkB;AAClB,iBAAgB;AAChB,mBAAkB;AAClB,uBAAsB;AACtB,oBAAmB;AACnB,kBAAiB;AACjB,sBAAqB;AACrB,iBAAgB;AAChB,sBAAqB;AACrB,gBAAe;AACf,wBAAuB;AACvB,8BAA6B;AAC7B,gBAAe;AACf,kBAAiB;AACjB,qBAAoB;AACpB,iBAAgB,OAAO;CAEvB,MAAM,UACJ,OAAO,WAAW,cAAc,SAAS;AAC3C,QAAO,QAAQ"}
|
package/dist/core/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { RenderResult, StyleResult, isSelector, renderStyles } from "../pipeline
|
|
|
12
12
|
import { SheetManager } from "../injector/sheet-manager.js";
|
|
13
13
|
import { StyleInjector } from "../injector/injector.js";
|
|
14
14
|
import { ColorSpace } from "../utils/color-space.js";
|
|
15
|
+
import { TypographyPreset, TypographyTokenValue, generateTypographyTokens } from "../utils/typography.js";
|
|
15
16
|
import { TastyPlugin, TastyPluginFactory } from "../plugins/types.js";
|
|
16
17
|
import { TastyConfig, configure, getConfig, getGlobalCounterStyle, getGlobalFontFace, getGlobalKeyframes, getGlobalRecipes, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, isConfigLocked, isTestEnvironment, resetConfig } from "../config.js";
|
|
17
18
|
import { okhslFunc, okhslPlugin } from "../plugins/okhsl-plugin.js";
|
|
@@ -29,6 +30,5 @@ import { mergeStyles } from "../utils/merge-styles.js";
|
|
|
29
30
|
import { resolveRecipes } from "../utils/resolve-recipes.js";
|
|
30
31
|
import { deprecationWarning, warn } from "../utils/warnings.js";
|
|
31
32
|
import { processTokens } from "../utils/process-tokens.js";
|
|
32
|
-
import { TypographyPreset, generateTypographyTokens } from "../utils/typography.js";
|
|
33
33
|
import { tastyDebug } from "../debug.js";
|
|
34
|
-
export { type AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseStyleProps, type BlockInnerStyleProps, type BlockOuterStyleProps, type BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, CONTAINER_STYLES, CSSMap, type CSSProperties, CUSTOM_UNITS, CacheMetrics, type ChunkInfo, type ChunkName, type ColorSpace, type ColorStyleProps, type ComputeStylesOptions, type ComputeStylesResult, type ConditionNode, type ConfigTokenValue, type ConfigTokens, type ContainerStyleProps, CounterStyleDescriptors, DIMENSION_STYLES, DIRECTIONS, type DimensionStyleProps, DisposeFunction, FLOW_STYLES, type FlowStyleProps, FontFaceDescriptors, FontFaceInput, GCConfig, GCOptions, type GlobalStyledProps, INNER_STYLES, InjectResult, type InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, type ModValue, type Mods, type NoType, type NotSelector, OUTER_STYLES, type OuterStyleProps, POSITION_STYLES, type ParseStateKeyOptions, type ParsedAdvancedState, ParsedColor, type ParserOptions, type PositionStyleProps, type ProcessedStyle, PropertyDefinition, PropertyOptions, type Props, RawCSSResult, RawStyleHandler, type RecipeStyles, type RenderResult, RootRegistry, RuleInfo, STYLE_TO_CHUNK, type Selector, SheetInfo, SheetManager, type ShortGridStyles, type StateParserContext, type StyleDetails, type StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, type StyleResult, StyleRule, StyleUsage, StyleValue, StyleValueStateMap, type Styles, type StylesInterface, type StylesWithoutSelectors, type SuffixForSelector, TEXT_STYLES, type TagName, type TastyConfig, type TastyExtensionConfig, type TastyNamedColors, type TastyPlugin, type TastyPluginFactory, type TastyPresetNames, type TastyThemeNames, type TextStyleProps, type TokenValue, type Tokens, TypographyPreset, type UnitHandler, categorizeStyleKeys, cleanup, color, computeStyles, configure, counterStyle, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, filterBaseProps, filterMods, fontFace, gc, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalCounterStyle, getGlobalFontFace, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getNamedColorHex, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleHandlers, tastyDebug, touch, warn };
|
|
34
|
+
export { type AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseStyleProps, type BlockInnerStyleProps, type BlockOuterStyleProps, type BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, CONTAINER_STYLES, CSSMap, type CSSProperties, CUSTOM_UNITS, CacheMetrics, type ChunkInfo, type ChunkName, type ColorSpace, type ColorStyleProps, type ComputeStylesOptions, type ComputeStylesResult, type ConditionNode, type ConfigTokenValue, type ConfigTokens, type ContainerStyleProps, CounterStyleDescriptors, DIMENSION_STYLES, DIRECTIONS, type DimensionStyleProps, DisposeFunction, FLOW_STYLES, type FlowStyleProps, FontFaceDescriptors, FontFaceInput, GCConfig, GCOptions, type GlobalStyledProps, INNER_STYLES, InjectResult, type InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, type ModValue, type Mods, type NoType, type NotSelector, OUTER_STYLES, type OuterStyleProps, POSITION_STYLES, type ParseStateKeyOptions, type ParsedAdvancedState, ParsedColor, type ParserOptions, type PositionStyleProps, type ProcessedStyle, PropertyDefinition, PropertyOptions, type Props, RawCSSResult, RawStyleHandler, type RecipeStyles, type RenderResult, RootRegistry, RuleInfo, STYLE_TO_CHUNK, type Selector, SheetInfo, SheetManager, type ShortGridStyles, type StateParserContext, type StyleDetails, type StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, type StyleResult, StyleRule, StyleUsage, StyleValue, StyleValueStateMap, type Styles, type StylesInterface, type StylesWithoutSelectors, type SuffixForSelector, TEXT_STYLES, type TagName, type TastyConfig, type TastyExtensionConfig, type TastyNamedColors, type TastyPlugin, type TastyPluginFactory, type TastyPresetNames, type TastyThemeNames, type TextStyleProps, type TokenValue, type Tokens, TypographyPreset, TypographyTokenValue, type UnitHandler, categorizeStyleKeys, cleanup, color, computeStyles, configure, counterStyle, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, filterBaseProps, filterMods, fontFace, gc, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalCounterStyle, getGlobalFontFace, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getNamedColorHex, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleHandlers, tastyDebug, touch, warn };
|
package/dist/core/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { StyleInjector } from "../injector/injector.js";
|
|
|
10
10
|
import { createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "../states/index.js";
|
|
11
11
|
import { parseStateKey } from "../pipeline/parseStateKey.js";
|
|
12
12
|
import { isSelector, renderStyles } from "../pipeline/index.js";
|
|
13
|
+
import { generateTypographyTokens } from "../utils/typography.js";
|
|
13
14
|
import { configure, getConfig, getGlobalCounterStyle, getGlobalFontFace, getGlobalKeyframes, getGlobalRecipes, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, isConfigLocked, isTestEnvironment, resetConfig } from "../config.js";
|
|
14
15
|
import { CHUNK_NAMES, STYLE_TO_CHUNK, categorizeStyleKeys } from "../chunks/definitions.js";
|
|
15
16
|
import { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, COLOR_STYLES, CONTAINER_STYLES, DIMENSION_STYLES, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, TEXT_STYLES } from "../styles/list.js";
|
|
@@ -22,6 +23,5 @@ import { color } from "../utils/colors.js";
|
|
|
22
23
|
import { _modAttrs } from "../utils/mod-attrs.js";
|
|
23
24
|
import { dotize } from "../utils/dotize.js";
|
|
24
25
|
import { processTokens } from "../utils/process-tokens.js";
|
|
25
|
-
import { generateTypographyTokens } from "../utils/typography.js";
|
|
26
26
|
import { tastyDebug } from "../debug.js";
|
|
27
27
|
export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, categorizeStyleKeys, cleanup, color, computeStyles, configure, counterStyle, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, filterBaseProps, filterMods, fontFace, gc, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalCounterStyle, getGlobalFontFace, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getNamedColorHex, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleHandlers, tastyDebug, touch, warn };
|
package/dist/debug.js
CHANGED
|
@@ -26,7 +26,7 @@ function findDomTastyClasses(root = document) {
|
|
|
26
26
|
(root.querySelectorAll?.("[class]") || []).forEach((el) => {
|
|
27
27
|
const attr = el.getAttribute("class");
|
|
28
28
|
if (attr) {
|
|
29
|
-
for (const cls of attr.split(/\s+/)) if (/^t
|
|
29
|
+
for (const cls of attr.split(/\s+/)) if (/^t[a-z0-9]+$/.test(cls)) classes.add(cls);
|
|
30
30
|
}
|
|
31
31
|
});
|
|
32
32
|
return sortTastyClasses(classes);
|
|
@@ -222,7 +222,7 @@ const tastyDebug = {
|
|
|
222
222
|
css(target, opts) {
|
|
223
223
|
const { root = document, prettify = true, raw = false, source = false } = opts || {};
|
|
224
224
|
let css = "";
|
|
225
|
-
if (source && typeof target === "string" && /^t
|
|
225
|
+
if (source && typeof target === "string" && /^t[a-z0-9]+$/.test(target)) {
|
|
226
226
|
const src = getSourceCssForClasses([target], root);
|
|
227
227
|
if (src) css = src;
|
|
228
228
|
else {
|
|
@@ -247,7 +247,7 @@ const tastyDebug = {
|
|
|
247
247
|
const unused = getUnusedClasses(root);
|
|
248
248
|
css = injector.instance.getCssTextForClasses(unused, { root });
|
|
249
249
|
} else if (target === "page") css = getPageCSS(root);
|
|
250
|
-
else if (/^t
|
|
250
|
+
else if (/^t[a-z0-9]+$/.test(target)) css = injector.instance.getCssTextForClasses([target], { root });
|
|
251
251
|
else {
|
|
252
252
|
const el = root.querySelector?.(target);
|
|
253
253
|
if (el) css = getCssTextForNode(el, { root });
|
|
@@ -279,7 +279,7 @@ const tastyDebug = {
|
|
|
279
279
|
if (!raw) console.warn("tastyDebug.inspect: element not found");
|
|
280
280
|
return empty;
|
|
281
281
|
}
|
|
282
|
-
const tastyClasses = (element.getAttribute("class") || "").split(/\s+/).filter((cls) => /^t
|
|
282
|
+
const tastyClasses = (element.getAttribute("class") || "").split(/\s+/).filter((cls) => /^t[a-z0-9]+$/.test(cls));
|
|
283
283
|
const chunks = tastyClasses.map((className) => ({
|
|
284
284
|
className,
|
|
285
285
|
chunkName: getChunkForClass(className, root)
|
package/dist/debug.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { CHUNK_NAMES } from './chunks/definitions';\nimport { getCssTextForNode, injector } from './injector';\nimport type { CacheMetrics, RootRegistry } from './injector/types';\nimport { isDevEnv } from './utils/is-dev-env';\n\ndeclare global {\n interface Window {\n tastyDebug?: typeof tastyDebug;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype CSSTarget =\n | 'all'\n | 'global'\n | 'active'\n | 'unused'\n | 'page'\n | string\n | string[]\n | Element;\n\ninterface DebugOptions {\n root?: Document | ShadowRoot;\n /** Suppress console logging and return data only (default: false) */\n raw?: boolean;\n}\n\ninterface CssOptions extends DebugOptions {\n prettify?: boolean;\n /** Read from stored source CSS (dev-mode only) instead of live CSSOM */\n source?: boolean;\n}\n\ninterface ChunkInfo {\n className: string;\n chunkName: string | null;\n}\n\ninterface InspectResult {\n element?: Element | null;\n classes: string[];\n chunks: ChunkInfo[];\n css: string;\n size: number;\n rules: number;\n}\n\ninterface CacheStatus {\n classes: {\n active: string[];\n unused: string[];\n all: string[];\n };\n metrics: CacheMetrics | null;\n}\n\ninterface ChunkBreakdown {\n byChunk: Record<\n string,\n { classes: string[]; cssSize: number; ruleCount: number }\n >;\n totalChunkTypes: number;\n totalClasses: number;\n}\n\ninterface Summary {\n activeClasses: string[];\n unusedClasses: string[];\n totalStyledClasses: string[];\n\n activeCSSSize: number;\n unusedCSSSize: number;\n globalCSSSize: number;\n rawCSSSize: number;\n keyframesCSSSize: number;\n propertyCSSSize: number;\n totalCSSSize: number;\n\n activeRuleCount: number;\n unusedRuleCount: number;\n globalRuleCount: number;\n rawRuleCount: number;\n keyframesRuleCount: number;\n propertyRuleCount: number;\n totalRuleCount: number;\n\n metrics: CacheMetrics | null;\n definedProperties: string[];\n definedKeyframes: { name: string; refCount: number }[];\n chunkBreakdown: ChunkBreakdown;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction fmtSize(bytes: number): string {\n return bytes > 1024 ? `${(bytes / 1024).toFixed(1)}KB` : `${bytes}B`;\n}\n\nfunction countRules(css: string): number {\n return (css.match(/\\{[^}]*\\}/g) || []).length;\n}\n\nfunction sortTastyClasses(classes: Iterable<string>): string[] {\n return Array.from(classes).sort(\n (a, b) => parseInt(a.slice(1)) - parseInt(b.slice(1)),\n );\n}\n\nfunction getRegistry(\n root: Document | ShadowRoot = document,\n): RootRegistry | undefined {\n return injector.instance._sheetManager?.getRegistry(root);\n}\n\nfunction getUnusedClasses(root: Document | ShadowRoot = document): string[] {\n const registry = getRegistry(root);\n if (!registry) return [];\n const result: string[] = [];\n for (const [cls, rc] of registry.refCounts as Map<string, number>) {\n if (rc === 0) result.push(cls);\n }\n return sortTastyClasses(result);\n}\n\nfunction findDomTastyClasses(root: Document | ShadowRoot = document): string[] {\n const classes = new Set<string>();\n const elements = (root as Document).querySelectorAll?.('[class]') || [];\n elements.forEach((el) => {\n const attr = el.getAttribute('class');\n if (attr) {\n for (const cls of attr.split(/\\s+/)) {\n if (/^t\\d+$/.test(cls)) classes.add(cls);\n }\n }\n });\n return sortTastyClasses(classes);\n}\n\n// ---------------------------------------------------------------------------\n// prettifyCSS — readable output for nested at-rules & comma selectors\n// ---------------------------------------------------------------------------\n\nfunction prettifyCSS(css: string): string {\n if (!css || !css.trim()) return '';\n\n const out: string[] = [];\n let depth = 0;\n const indent = () => ' '.repeat(depth);\n\n let normalized = css.replace(/\\s+/g, ' ').trim();\n // Ensure braces are surrounded by spaces for splitting\n normalized = normalized.replace(/\\s*\\{\\s*/g, ' { ');\n normalized = normalized.replace(/\\s*\\}\\s*/g, ' } ');\n normalized = normalized.replace(/;\\s*/g, '; ');\n\n const tokens = normalized.split(/\\s+/);\n let buf = '';\n\n for (const t of tokens) {\n if (t === '{') {\n // buf contains the selector / at-rule header\n const header = buf.trim();\n if (header) {\n // Split comma-separated selectors onto their own lines\n // but only if the comma is outside parentheses\n const parts = splitOutsideParens(header, ',');\n if (parts.length > 1) {\n out.push(\n parts\n .map((p, idx) =>\n idx === 0\n ? `${indent()}${p.trim()},`\n : `${indent()}${p.trim()}${idx < parts.length - 1 ? ',' : ''}`,\n )\n .join('\\n') + ' {',\n );\n } else {\n out.push(`${indent()}${header} {`);\n }\n } else {\n out.push(`${indent()}{`);\n }\n depth++;\n buf = '';\n } else if (t === '}') {\n // Flush any trailing declarations\n if (buf.trim()) {\n for (const decl of buf.split(';').filter((s) => s.trim())) {\n out.push(`${indent()}${decl.trim()};`);\n }\n buf = '';\n }\n depth = Math.max(0, depth - 1);\n out.push(`${indent()}}`);\n } else if (t.endsWith(';')) {\n buf += ` ${t}`;\n const full = buf.trim();\n if (full) out.push(`${indent()}${full}`);\n buf = '';\n } else {\n buf += ` ${t}`;\n }\n }\n if (buf.trim()) out.push(buf.trim());\n\n return out\n .filter((l) => l.trim())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** Split `str` by `sep` only when not inside parentheses */\nfunction splitOutsideParens(str: string, sep: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n if (ch === '(') depth++;\n else if (ch === ')') depth--;\n else if (depth === 0 && str.startsWith(sep, i)) {\n parts.push(str.slice(start, i));\n start = i + sep.length;\n }\n }\n parts.push(str.slice(start));\n return parts;\n}\n\n// ---------------------------------------------------------------------------\n// Chunk helpers\n// ---------------------------------------------------------------------------\n\nfunction extractChunkName(cacheKey: string): string | null {\n for (const part of cacheKey.split('\\0')) {\n if (part.startsWith('[states:')) continue;\n if (!part.includes(':') && part.length > 0) return part;\n }\n return null;\n}\n\nfunction getChunkForClass(\n className: string,\n root: Document | ShadowRoot = document,\n): string | null {\n const registry = getRegistry(root);\n if (!registry) return null;\n for (const [key, cn] of registry.cacheKeyToClassName) {\n if (cn === className) return extractChunkName(key);\n }\n return null;\n}\n\nfunction buildChunkBreakdown(\n root: Document | ShadowRoot = document,\n): ChunkBreakdown {\n const registry = getRegistry(root);\n if (!registry) return { byChunk: {}, totalChunkTypes: 0, totalClasses: 0 };\n\n const byChunk: ChunkBreakdown['byChunk'] = {};\n for (const [cacheKey, className] of registry.cacheKeyToClassName) {\n const chunk = extractChunkName(cacheKey) || 'unknown';\n if (!byChunk[chunk])\n byChunk[chunk] = { classes: [], cssSize: 0, ruleCount: 0 };\n byChunk[chunk].classes.push(className);\n const css = injector.instance.getCssTextForClasses([className], { root });\n byChunk[chunk].cssSize += css.length;\n byChunk[chunk].ruleCount += countRules(css);\n }\n\n for (const entry of Object.values(byChunk)) {\n entry.classes = sortTastyClasses(entry.classes);\n }\n\n const totalClasses = Object.values(byChunk).reduce(\n (s, e) => s + e.classes.length,\n 0,\n );\n return {\n byChunk,\n totalChunkTypes: Object.keys(byChunk).length,\n totalClasses,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Global-type CSS helper (internal only)\n// ---------------------------------------------------------------------------\n\nfunction getGlobalTypeCSS(\n type: 'global' | 'raw' | 'keyframes' | 'property',\n root: Document | ShadowRoot = document,\n): { css: string; ruleCount: number; size: number } {\n const registry = getRegistry(root);\n if (!registry) return { css: '', ruleCount: 0, size: 0 };\n\n const chunks: string[] = [];\n let rc = 0;\n\n if (type === 'keyframes') {\n for (const [, entry] of registry.keyframesCache) {\n const info = entry.info;\n const sheet = registry.sheets[info.sheetIndex];\n const ss = sheet?.sheet?.sheet;\n if (ss && info.ruleIndex < ss.cssRules.length) {\n const rule = ss.cssRules[info.ruleIndex];\n if (rule) {\n chunks.push(rule.cssText);\n rc++;\n }\n } else if (info.cssText) {\n chunks.push(info.cssText);\n rc++;\n }\n }\n } else {\n const prefix =\n type === 'global' ? 'global:' : type === 'raw' ? 'raw:' : 'property:';\n for (const [key, ri] of registry.globalRules) {\n if (!key.startsWith(prefix)) continue;\n const sheet = registry.sheets[ri.sheetIndex];\n const ss = sheet?.sheet?.sheet;\n if (ss) {\n const start = Math.max(0, ri.ruleIndex);\n const end = Math.min(\n ss.cssRules.length - 1,\n (ri.endRuleIndex as number) ?? ri.ruleIndex,\n );\n if (start >= 0 && end >= start && start < ss.cssRules.length) {\n for (let i = start; i <= end; i++) {\n const rule = ss.cssRules[i];\n if (rule) {\n chunks.push(rule.cssText);\n rc++;\n }\n }\n }\n } else if (ri.cssText?.length) {\n chunks.push(...ri.cssText);\n rc += ri.cssText.length;\n }\n }\n }\n\n const raw = chunks.join('\\n');\n return { css: prettifyCSS(raw), ruleCount: rc, size: raw.length };\n}\n\n// ---------------------------------------------------------------------------\n// Source CSS (dev-mode RuleInfo.cssText)\n// ---------------------------------------------------------------------------\n\nfunction getSourceCssForClasses(\n classNames: string[],\n root: Document | ShadowRoot = document,\n): string | null {\n const registry = getRegistry(root);\n if (!registry) return null;\n\n const chunks: string[] = [];\n let found = false;\n for (const cls of classNames) {\n const info = registry.rules.get(cls);\n if (info?.cssText?.length) {\n chunks.push(...info.cssText);\n found = true;\n }\n }\n return found ? chunks.join('\\n') : null;\n}\n\n// ---------------------------------------------------------------------------\n// Definitions helper (internal)\n// ---------------------------------------------------------------------------\n\nfunction getDefs(root: Document | ShadowRoot = document) {\n const registry = getRegistry(root);\n let properties: string[] = [];\n if (registry?.injectedProperties) {\n properties = Array.from(\n (registry.injectedProperties as Map<string, string>).keys(),\n ).sort();\n }\n\n const keyframes: { name: string; refCount: number }[] = [];\n if (registry) {\n for (const entry of registry.keyframesCache.values()) {\n keyframes.push({ name: entry.name, refCount: entry.refCount });\n }\n keyframes.sort((a, b) => a.name.localeCompare(b.name));\n }\n\n return { properties, keyframes };\n}\n\n// ---------------------------------------------------------------------------\n// Chunk display order\n// ---------------------------------------------------------------------------\n\nconst CHUNK_ORDER = [\n CHUNK_NAMES.COMBINED,\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];\n\n// ---------------------------------------------------------------------------\n// tastyDebug API\n// ---------------------------------------------------------------------------\n\nexport const tastyDebug = {\n css(target: CSSTarget, opts?: CssOptions): string {\n const {\n root = document,\n prettify = true,\n raw = false,\n source = false,\n } = opts || {};\n let css = '';\n\n if (source && typeof target === 'string' && /^t\\d+$/.test(target)) {\n const src = getSourceCssForClasses([target], root);\n if (src) {\n css = src;\n } else {\n if (!raw) {\n console.warn(\n 'tastyDebug: source CSS not available (requires dev mode or TASTY_DEBUG=true). Falling back to live CSSOM.',\n );\n }\n css = injector.instance.getCssTextForClasses([target], { root });\n }\n } else if (source && Array.isArray(target)) {\n const src = getSourceCssForClasses(target, root);\n if (src) {\n css = src;\n } else {\n if (!raw) {\n console.warn(\n 'tastyDebug: source CSS not available. Falling back to live CSSOM.',\n );\n }\n css = injector.instance.getCssTextForClasses(target, { root });\n }\n } else if (typeof target === 'string') {\n if (target === 'all') {\n css = injector.instance.getCssText({ root });\n } else if (target === 'global') {\n css = getGlobalTypeCSS('global', root).css;\n return css; // already prettified\n } else if (target === 'active') {\n const active = findDomTastyClasses(root);\n css = injector.instance.getCssTextForClasses(active, { root });\n } else if (target === 'unused') {\n const unused = getUnusedClasses(root);\n css = injector.instance.getCssTextForClasses(unused, { root });\n } else if (target === 'page') {\n css = getPageCSS(root);\n } else if (/^t\\d+$/.test(target)) {\n css = injector.instance.getCssTextForClasses([target], { root });\n } else {\n const el = (root as Document).querySelector?.(target);\n if (el) css = getCssTextForNode(el, { root });\n }\n } else if (Array.isArray(target)) {\n css = injector.instance.getCssTextForClasses(target, { root });\n } else if (target instanceof Element) {\n css = getCssTextForNode(target, { root });\n }\n\n const result = prettify ? prettifyCSS(css) : css;\n\n if (!raw) {\n const label = Array.isArray(target) ? `[${target.join(', ')}]` : target;\n const rc = countRules(css);\n console.group(`CSS for ${label} (${rc} rules, ${fmtSize(css.length)})`);\n console.log(result || '(empty)');\n console.groupEnd();\n }\n\n return result;\n },\n\n inspect(target: string | Element, opts?: DebugOptions): InspectResult {\n const { root = document, raw = false } = opts || {};\n const element =\n typeof target === 'string'\n ? (root as Document).querySelector?.(target)\n : target;\n\n if (!element) {\n const empty: InspectResult = {\n element: null,\n classes: [],\n chunks: [],\n css: '',\n size: 0,\n rules: 0,\n };\n if (!raw) console.warn('tastyDebug.inspect: element not found');\n return empty;\n }\n\n const classList = element.getAttribute('class') || '';\n const tastyClasses = classList\n .split(/\\s+/)\n .filter((cls) => /^t\\d+$/.test(cls));\n\n const chunks: ChunkInfo[] = tastyClasses.map((className) => ({\n className,\n chunkName: getChunkForClass(className, root),\n }));\n\n const css = getCssTextForNode(element, { root });\n const rules = countRules(css);\n\n const result: InspectResult = {\n element,\n classes: tastyClasses,\n chunks,\n css: prettifyCSS(css),\n size: css.length,\n rules,\n };\n\n if (!raw) {\n const tag = element.tagName.toLowerCase();\n const id = element.id ? `#${element.id}` : '';\n console.group(\n `inspect ${tag}${id} — ${tastyClasses.length} classes, ${rules} rules, ${fmtSize(css.length)}`,\n );\n if (chunks.length) {\n console.log(\n 'Chunks:',\n chunks.map((c) => `${c.className}→${c.chunkName || '?'}`).join(', '),\n );\n }\n console.groupCollapsed('CSS');\n console.log(result.css || '(empty)');\n console.groupEnd();\n console.groupEnd();\n }\n\n return result;\n },\n\n summary(opts?: DebugOptions): Summary {\n const { root = document, raw = false } = opts || {};\n\n const activeClasses = findDomTastyClasses(root);\n const unusedClasses = getUnusedClasses(root);\n const totalStyledClasses = [...activeClasses, ...unusedClasses];\n\n const activeCSS = injector.instance.getCssTextForClasses(activeClasses, {\n root,\n });\n const unusedCSS = injector.instance.getCssTextForClasses(unusedClasses, {\n root,\n });\n const allCSS = injector.instance.getCssText({ root });\n\n const activeRuleCount = countRules(activeCSS);\n const unusedRuleCount = countRules(unusedCSS);\n\n const globalData = getGlobalTypeCSS('global', root);\n const rawData = getGlobalTypeCSS('raw', root);\n const kfData = getGlobalTypeCSS('keyframes', root);\n const propData = getGlobalTypeCSS('property', root);\n\n const totalRuleCount =\n activeRuleCount +\n unusedRuleCount +\n globalData.ruleCount +\n rawData.ruleCount +\n kfData.ruleCount +\n propData.ruleCount;\n\n const metrics = injector.instance.getMetrics({ root });\n const defs = getDefs(root);\n const chunkBreakdown = buildChunkBreakdown(root);\n\n const summary: Summary = {\n activeClasses,\n unusedClasses,\n totalStyledClasses,\n activeCSSSize: activeCSS.length,\n unusedCSSSize: unusedCSS.length,\n globalCSSSize: globalData.size,\n rawCSSSize: rawData.size,\n keyframesCSSSize: kfData.size,\n propertyCSSSize: propData.size,\n totalCSSSize: allCSS.length,\n activeRuleCount,\n unusedRuleCount,\n globalRuleCount: globalData.ruleCount,\n rawRuleCount: rawData.ruleCount,\n keyframesRuleCount: kfData.ruleCount,\n propertyRuleCount: propData.ruleCount,\n totalRuleCount,\n metrics,\n definedProperties: defs.properties,\n definedKeyframes: defs.keyframes,\n chunkBreakdown,\n };\n\n if (!raw) {\n console.group('Tasty Summary');\n console.log(\n `Active: ${activeClasses.length} classes, ${activeRuleCount} rules, ${fmtSize(activeCSS.length)}`,\n );\n console.log(\n `Unused: ${unusedClasses.length} classes, ${unusedRuleCount} rules, ${fmtSize(unusedCSS.length)}`,\n );\n console.log(\n `Global: ${globalData.ruleCount} rules, ${fmtSize(globalData.size)}`,\n );\n if (rawData.ruleCount)\n console.log(\n `Raw: ${rawData.ruleCount} rules, ${fmtSize(rawData.size)}`,\n );\n if (kfData.ruleCount)\n console.log(\n `Keyframes: ${kfData.ruleCount} rules, ${fmtSize(kfData.size)}`,\n );\n if (propData.ruleCount)\n console.log(\n `@property: ${propData.ruleCount} rules, ${fmtSize(propData.size)}`,\n );\n console.log(\n `Total: ${totalStyledClasses.length} classes, ${totalRuleCount} rules, ${fmtSize(allCSS.length)}`,\n );\n\n if (metrics) {\n const total = metrics.hits + metrics.misses;\n const rate = total > 0 ? ((metrics.hits / total) * 100).toFixed(1) : 0;\n console.log(`Cache: ${rate}% hit rate (${total} lookups)`);\n }\n\n if (chunkBreakdown.totalChunkTypes > 0) {\n console.groupCollapsed(\n `Chunks (${chunkBreakdown.totalChunkTypes} types, ${chunkBreakdown.totalClasses} classes)`,\n );\n for (const name of CHUNK_ORDER) {\n const d = chunkBreakdown.byChunk[name];\n if (d)\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n for (const [name, d] of Object.entries(chunkBreakdown.byChunk)) {\n if (!CHUNK_ORDER.includes(name as (typeof CHUNK_ORDER)[number]))\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n console.groupEnd();\n }\n\n if (defs.properties.length || defs.keyframes.length) {\n console.log(\n `Defs: ${defs.properties.length} @property, ${defs.keyframes.length} @keyframes`,\n );\n }\n\n console.groupEnd();\n }\n\n return summary;\n },\n\n chunks(opts?: DebugOptions): ChunkBreakdown {\n const { root = document, raw = false } = opts || {};\n const breakdown = buildChunkBreakdown(root);\n\n if (!raw) {\n console.group(\n `Chunks (${breakdown.totalChunkTypes} types, ${breakdown.totalClasses} classes)`,\n );\n for (const name of CHUNK_ORDER) {\n const d = breakdown.byChunk[name];\n if (d)\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n for (const [name, d] of Object.entries(breakdown.byChunk)) {\n if (!CHUNK_ORDER.includes(name as (typeof CHUNK_ORDER)[number]))\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n console.groupEnd();\n }\n\n return breakdown;\n },\n\n cache(opts?: DebugOptions): CacheStatus {\n const { root = document, raw = false } = opts || {};\n const active = findDomTastyClasses(root);\n const unused = getUnusedClasses(root);\n const metrics = injector.instance.getMetrics({ root });\n\n const status: CacheStatus = {\n classes: { active, unused, all: [...active, ...unused] },\n metrics,\n };\n\n if (!raw) {\n console.group('Cache');\n console.log(`Active: ${active.length}, Unused: ${unused.length}`);\n if (metrics) {\n const total = metrics.hits + metrics.misses;\n const rate = total > 0 ? ((metrics.hits / total) * 100).toFixed(1) : 0;\n console.log(\n `Hits: ${metrics.hits}, Misses: ${metrics.misses}, Rate: ${rate}%`,\n );\n }\n console.groupEnd();\n }\n\n return status;\n },\n\n cleanup(opts?: { root?: Document | ShadowRoot }): void {\n injector.instance.cleanup(opts?.root);\n },\n\n help(): void {\n console.log(`tastyDebug API:\n .summary() — overview (classes, rules, sizes)\n .css(\"active\") — CSS for classes in DOM\n .css(\"t42\") — CSS for a specific class\n .css(\"t42\",{source:1})— original CSS before browser parsing (dev only)\n .css(\".selector\") — CSS for a DOM element\n .inspect(\".selector\") — element details (classes, chunks, rules)\n .chunks() — style chunk breakdown\n .cache() — cache status and metrics\n .cleanup() — force unused style cleanup\nOptions: { raw: true } suppresses logging, { root: shadowRoot } targets Shadow DOM`);\n },\n\n install(): void {\n if (typeof window !== 'undefined' && window.tastyDebug !== tastyDebug) {\n window.tastyDebug = tastyDebug;\n console.log('tastyDebug installed. Run tastyDebug.help() for commands.');\n }\n },\n};\n\n// ---------------------------------------------------------------------------\n// Page CSS (minimal, kept internal)\n// ---------------------------------------------------------------------------\n\nfunction getPageCSS(root: Document | ShadowRoot = document): string {\n const chunks: string[] = [];\n try {\n if ('styleSheets' in root) {\n for (const sheet of Array.from((root as Document).styleSheets)) {\n try {\n if (sheet.cssRules)\n chunks.push(\n Array.from(sheet.cssRules)\n .map((r) => r.cssText)\n .join('\\n'),\n );\n } catch {\n /* cross-origin */\n }\n }\n }\n } catch {\n /* ignore */\n }\n return chunks.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Auto-install in development\n// ---------------------------------------------------------------------------\n\nif (typeof window !== 'undefined' && isDevEnv()) {\n tastyDebug.install();\n}\n"],"mappings":";;;;AAqGA,SAAS,QAAQ,OAAuB;AACtC,QAAO,QAAQ,OAAO,IAAI,QAAQ,MAAM,QAAQ,EAAE,CAAC,MAAM,GAAG,MAAM;;AAGpE,SAAS,WAAW,KAAqB;AACvC,SAAQ,IAAI,MAAM,aAAa,IAAI,EAAE,EAAE;;AAGzC,SAAS,iBAAiB,SAAqC;AAC7D,QAAO,MAAM,KAAK,QAAQ,CAAC,MACxB,GAAG,MAAM,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,SAAS,EAAE,MAAM,EAAE,CAAC,CACtD;;AAGH,SAAS,YACP,OAA8B,UACJ;AAC1B,QAAO,SAAS,SAAS,eAAe,YAAY,KAAK;;AAG3D,SAAS,iBAAiB,OAA8B,UAAoB;CAC1E,MAAM,WAAW,YAAY,KAAK;AAClC,KAAI,CAAC,SAAU,QAAO,EAAE;CACxB,MAAM,SAAmB,EAAE;AAC3B,MAAK,MAAM,CAAC,KAAK,OAAO,SAAS,UAC/B,KAAI,OAAO,EAAG,QAAO,KAAK,IAAI;AAEhC,QAAO,iBAAiB,OAAO;;AAGjC,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AACd,MAAI,OAAO,WAAW,eAAe,OAAO,eAAe,YAAY;AACrE,UAAO,aAAa;AACpB,WAAQ,IAAI,4DAA4D;;;CAG7E;AAMD,SAAS,WAAW,OAA8B,UAAkB;CAClE,MAAM,SAAmB,EAAE;AAC3B,KAAI;AACF,MAAI,iBAAiB,KACnB,MAAK,MAAM,SAAS,MAAM,KAAM,KAAkB,YAAY,CAC5D,KAAI;AACF,OAAI,MAAM,SACR,QAAO,KACL,MAAM,KAAK,MAAM,SAAS,CACvB,KAAK,MAAM,EAAE,QAAQ,CACrB,KAAK,KAAK,CACd;UACG;SAKN;AAGR,QAAO,OAAO,KAAK,KAAK;;AAO1B,IAAI,OAAO,WAAW,eAAe,UAAU,CAC7C,YAAW,SAAS"}
|
|
1
|
+
{"version":3,"file":"debug.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { CHUNK_NAMES } from './chunks/definitions';\nimport { getCssTextForNode, injector } from './injector';\nimport type { CacheMetrics, RootRegistry } from './injector/types';\nimport { isDevEnv } from './utils/is-dev-env';\n\ndeclare global {\n interface Window {\n tastyDebug?: typeof tastyDebug;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype CSSTarget =\n | 'all'\n | 'global'\n | 'active'\n | 'unused'\n | 'page'\n | string\n | string[]\n | Element;\n\ninterface DebugOptions {\n root?: Document | ShadowRoot;\n /** Suppress console logging and return data only (default: false) */\n raw?: boolean;\n}\n\ninterface CssOptions extends DebugOptions {\n prettify?: boolean;\n /** Read from stored source CSS (dev-mode only) instead of live CSSOM */\n source?: boolean;\n}\n\ninterface ChunkInfo {\n className: string;\n chunkName: string | null;\n}\n\ninterface InspectResult {\n element?: Element | null;\n classes: string[];\n chunks: ChunkInfo[];\n css: string;\n size: number;\n rules: number;\n}\n\ninterface CacheStatus {\n classes: {\n active: string[];\n unused: string[];\n all: string[];\n };\n metrics: CacheMetrics | null;\n}\n\ninterface ChunkBreakdown {\n byChunk: Record<\n string,\n { classes: string[]; cssSize: number; ruleCount: number }\n >;\n totalChunkTypes: number;\n totalClasses: number;\n}\n\ninterface Summary {\n activeClasses: string[];\n unusedClasses: string[];\n totalStyledClasses: string[];\n\n activeCSSSize: number;\n unusedCSSSize: number;\n globalCSSSize: number;\n rawCSSSize: number;\n keyframesCSSSize: number;\n propertyCSSSize: number;\n totalCSSSize: number;\n\n activeRuleCount: number;\n unusedRuleCount: number;\n globalRuleCount: number;\n rawRuleCount: number;\n keyframesRuleCount: number;\n propertyRuleCount: number;\n totalRuleCount: number;\n\n metrics: CacheMetrics | null;\n definedProperties: string[];\n definedKeyframes: { name: string; refCount: number }[];\n chunkBreakdown: ChunkBreakdown;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction fmtSize(bytes: number): string {\n return bytes > 1024 ? `${(bytes / 1024).toFixed(1)}KB` : `${bytes}B`;\n}\n\nfunction countRules(css: string): number {\n return (css.match(/\\{[^}]*\\}/g) || []).length;\n}\n\nfunction sortTastyClasses(classes: Iterable<string>): string[] {\n return Array.from(classes).sort(\n (a, b) => parseInt(a.slice(1)) - parseInt(b.slice(1)),\n );\n}\n\nfunction getRegistry(\n root: Document | ShadowRoot = document,\n): RootRegistry | undefined {\n return injector.instance._sheetManager?.getRegistry(root);\n}\n\nfunction getUnusedClasses(root: Document | ShadowRoot = document): string[] {\n const registry = getRegistry(root);\n if (!registry) return [];\n const result: string[] = [];\n for (const [cls, rc] of registry.refCounts as Map<string, number>) {\n if (rc === 0) result.push(cls);\n }\n return sortTastyClasses(result);\n}\n\nfunction findDomTastyClasses(root: Document | ShadowRoot = document): string[] {\n const classes = new Set<string>();\n const elements = (root as Document).querySelectorAll?.('[class]') || [];\n elements.forEach((el) => {\n const attr = el.getAttribute('class');\n if (attr) {\n for (const cls of attr.split(/\\s+/)) {\n if (/^t[a-z0-9]+$/.test(cls)) classes.add(cls);\n }\n }\n });\n return sortTastyClasses(classes);\n}\n\n// ---------------------------------------------------------------------------\n// prettifyCSS — readable output for nested at-rules & comma selectors\n// ---------------------------------------------------------------------------\n\nfunction prettifyCSS(css: string): string {\n if (!css || !css.trim()) return '';\n\n const out: string[] = [];\n let depth = 0;\n const indent = () => ' '.repeat(depth);\n\n let normalized = css.replace(/\\s+/g, ' ').trim();\n // Ensure braces are surrounded by spaces for splitting\n normalized = normalized.replace(/\\s*\\{\\s*/g, ' { ');\n normalized = normalized.replace(/\\s*\\}\\s*/g, ' } ');\n normalized = normalized.replace(/;\\s*/g, '; ');\n\n const tokens = normalized.split(/\\s+/);\n let buf = '';\n\n for (const t of tokens) {\n if (t === '{') {\n // buf contains the selector / at-rule header\n const header = buf.trim();\n if (header) {\n // Split comma-separated selectors onto their own lines\n // but only if the comma is outside parentheses\n const parts = splitOutsideParens(header, ',');\n if (parts.length > 1) {\n out.push(\n parts\n .map((p, idx) =>\n idx === 0\n ? `${indent()}${p.trim()},`\n : `${indent()}${p.trim()}${idx < parts.length - 1 ? ',' : ''}`,\n )\n .join('\\n') + ' {',\n );\n } else {\n out.push(`${indent()}${header} {`);\n }\n } else {\n out.push(`${indent()}{`);\n }\n depth++;\n buf = '';\n } else if (t === '}') {\n // Flush any trailing declarations\n if (buf.trim()) {\n for (const decl of buf.split(';').filter((s) => s.trim())) {\n out.push(`${indent()}${decl.trim()};`);\n }\n buf = '';\n }\n depth = Math.max(0, depth - 1);\n out.push(`${indent()}}`);\n } else if (t.endsWith(';')) {\n buf += ` ${t}`;\n const full = buf.trim();\n if (full) out.push(`${indent()}${full}`);\n buf = '';\n } else {\n buf += ` ${t}`;\n }\n }\n if (buf.trim()) out.push(buf.trim());\n\n return out\n .filter((l) => l.trim())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** Split `str` by `sep` only when not inside parentheses */\nfunction splitOutsideParens(str: string, sep: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n if (ch === '(') depth++;\n else if (ch === ')') depth--;\n else if (depth === 0 && str.startsWith(sep, i)) {\n parts.push(str.slice(start, i));\n start = i + sep.length;\n }\n }\n parts.push(str.slice(start));\n return parts;\n}\n\n// ---------------------------------------------------------------------------\n// Chunk helpers\n// ---------------------------------------------------------------------------\n\nfunction extractChunkName(cacheKey: string): string | null {\n for (const part of cacheKey.split('\\0')) {\n if (part.startsWith('[states:')) continue;\n if (!part.includes(':') && part.length > 0) return part;\n }\n return null;\n}\n\nfunction getChunkForClass(\n className: string,\n root: Document | ShadowRoot = document,\n): string | null {\n const registry = getRegistry(root);\n if (!registry) return null;\n for (const [key, cn] of registry.cacheKeyToClassName) {\n if (cn === className) return extractChunkName(key);\n }\n return null;\n}\n\nfunction buildChunkBreakdown(\n root: Document | ShadowRoot = document,\n): ChunkBreakdown {\n const registry = getRegistry(root);\n if (!registry) return { byChunk: {}, totalChunkTypes: 0, totalClasses: 0 };\n\n const byChunk: ChunkBreakdown['byChunk'] = {};\n for (const [cacheKey, className] of registry.cacheKeyToClassName) {\n const chunk = extractChunkName(cacheKey) || 'unknown';\n if (!byChunk[chunk])\n byChunk[chunk] = { classes: [], cssSize: 0, ruleCount: 0 };\n byChunk[chunk].classes.push(className);\n const css = injector.instance.getCssTextForClasses([className], { root });\n byChunk[chunk].cssSize += css.length;\n byChunk[chunk].ruleCount += countRules(css);\n }\n\n for (const entry of Object.values(byChunk)) {\n entry.classes = sortTastyClasses(entry.classes);\n }\n\n const totalClasses = Object.values(byChunk).reduce(\n (s, e) => s + e.classes.length,\n 0,\n );\n return {\n byChunk,\n totalChunkTypes: Object.keys(byChunk).length,\n totalClasses,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Global-type CSS helper (internal only)\n// ---------------------------------------------------------------------------\n\nfunction getGlobalTypeCSS(\n type: 'global' | 'raw' | 'keyframes' | 'property',\n root: Document | ShadowRoot = document,\n): { css: string; ruleCount: number; size: number } {\n const registry = getRegistry(root);\n if (!registry) return { css: '', ruleCount: 0, size: 0 };\n\n const chunks: string[] = [];\n let rc = 0;\n\n if (type === 'keyframes') {\n for (const [, entry] of registry.keyframesCache) {\n const info = entry.info;\n const sheet = registry.sheets[info.sheetIndex];\n const ss = sheet?.sheet?.sheet;\n if (ss && info.ruleIndex < ss.cssRules.length) {\n const rule = ss.cssRules[info.ruleIndex];\n if (rule) {\n chunks.push(rule.cssText);\n rc++;\n }\n } else if (info.cssText) {\n chunks.push(info.cssText);\n rc++;\n }\n }\n } else {\n const prefix =\n type === 'global' ? 'global:' : type === 'raw' ? 'raw:' : 'property:';\n for (const [key, ri] of registry.globalRules) {\n if (!key.startsWith(prefix)) continue;\n const sheet = registry.sheets[ri.sheetIndex];\n const ss = sheet?.sheet?.sheet;\n if (ss) {\n const start = Math.max(0, ri.ruleIndex);\n const end = Math.min(\n ss.cssRules.length - 1,\n (ri.endRuleIndex as number) ?? ri.ruleIndex,\n );\n if (start >= 0 && end >= start && start < ss.cssRules.length) {\n for (let i = start; i <= end; i++) {\n const rule = ss.cssRules[i];\n if (rule) {\n chunks.push(rule.cssText);\n rc++;\n }\n }\n }\n } else if (ri.cssText?.length) {\n chunks.push(...ri.cssText);\n rc += ri.cssText.length;\n }\n }\n }\n\n const raw = chunks.join('\\n');\n return { css: prettifyCSS(raw), ruleCount: rc, size: raw.length };\n}\n\n// ---------------------------------------------------------------------------\n// Source CSS (dev-mode RuleInfo.cssText)\n// ---------------------------------------------------------------------------\n\nfunction getSourceCssForClasses(\n classNames: string[],\n root: Document | ShadowRoot = document,\n): string | null {\n const registry = getRegistry(root);\n if (!registry) return null;\n\n const chunks: string[] = [];\n let found = false;\n for (const cls of classNames) {\n const info = registry.rules.get(cls);\n if (info?.cssText?.length) {\n chunks.push(...info.cssText);\n found = true;\n }\n }\n return found ? chunks.join('\\n') : null;\n}\n\n// ---------------------------------------------------------------------------\n// Definitions helper (internal)\n// ---------------------------------------------------------------------------\n\nfunction getDefs(root: Document | ShadowRoot = document) {\n const registry = getRegistry(root);\n let properties: string[] = [];\n if (registry?.injectedProperties) {\n properties = Array.from(\n (registry.injectedProperties as Map<string, string>).keys(),\n ).sort();\n }\n\n const keyframes: { name: string; refCount: number }[] = [];\n if (registry) {\n for (const entry of registry.keyframesCache.values()) {\n keyframes.push({ name: entry.name, refCount: entry.refCount });\n }\n keyframes.sort((a, b) => a.name.localeCompare(b.name));\n }\n\n return { properties, keyframes };\n}\n\n// ---------------------------------------------------------------------------\n// Chunk display order\n// ---------------------------------------------------------------------------\n\nconst CHUNK_ORDER = [\n CHUNK_NAMES.COMBINED,\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];\n\n// ---------------------------------------------------------------------------\n// tastyDebug API\n// ---------------------------------------------------------------------------\n\nexport const tastyDebug = {\n css(target: CSSTarget, opts?: CssOptions): string {\n const {\n root = document,\n prettify = true,\n raw = false,\n source = false,\n } = opts || {};\n let css = '';\n\n if (source && typeof target === 'string' && /^t[a-z0-9]+$/.test(target)) {\n const src = getSourceCssForClasses([target], root);\n if (src) {\n css = src;\n } else {\n if (!raw) {\n console.warn(\n 'tastyDebug: source CSS not available (requires dev mode or TASTY_DEBUG=true). Falling back to live CSSOM.',\n );\n }\n css = injector.instance.getCssTextForClasses([target], { root });\n }\n } else if (source && Array.isArray(target)) {\n const src = getSourceCssForClasses(target, root);\n if (src) {\n css = src;\n } else {\n if (!raw) {\n console.warn(\n 'tastyDebug: source CSS not available. Falling back to live CSSOM.',\n );\n }\n css = injector.instance.getCssTextForClasses(target, { root });\n }\n } else if (typeof target === 'string') {\n if (target === 'all') {\n css = injector.instance.getCssText({ root });\n } else if (target === 'global') {\n css = getGlobalTypeCSS('global', root).css;\n return css; // already prettified\n } else if (target === 'active') {\n const active = findDomTastyClasses(root);\n css = injector.instance.getCssTextForClasses(active, { root });\n } else if (target === 'unused') {\n const unused = getUnusedClasses(root);\n css = injector.instance.getCssTextForClasses(unused, { root });\n } else if (target === 'page') {\n css = getPageCSS(root);\n } else if (/^t[a-z0-9]+$/.test(target)) {\n css = injector.instance.getCssTextForClasses([target], { root });\n } else {\n const el = (root as Document).querySelector?.(target);\n if (el) css = getCssTextForNode(el, { root });\n }\n } else if (Array.isArray(target)) {\n css = injector.instance.getCssTextForClasses(target, { root });\n } else if (target instanceof Element) {\n css = getCssTextForNode(target, { root });\n }\n\n const result = prettify ? prettifyCSS(css) : css;\n\n if (!raw) {\n const label = Array.isArray(target) ? `[${target.join(', ')}]` : target;\n const rc = countRules(css);\n console.group(`CSS for ${label} (${rc} rules, ${fmtSize(css.length)})`);\n console.log(result || '(empty)');\n console.groupEnd();\n }\n\n return result;\n },\n\n inspect(target: string | Element, opts?: DebugOptions): InspectResult {\n const { root = document, raw = false } = opts || {};\n const element =\n typeof target === 'string'\n ? (root as Document).querySelector?.(target)\n : target;\n\n if (!element) {\n const empty: InspectResult = {\n element: null,\n classes: [],\n chunks: [],\n css: '',\n size: 0,\n rules: 0,\n };\n if (!raw) console.warn('tastyDebug.inspect: element not found');\n return empty;\n }\n\n const classList = element.getAttribute('class') || '';\n const tastyClasses = classList\n .split(/\\s+/)\n .filter((cls) => /^t[a-z0-9]+$/.test(cls));\n\n const chunks: ChunkInfo[] = tastyClasses.map((className) => ({\n className,\n chunkName: getChunkForClass(className, root),\n }));\n\n const css = getCssTextForNode(element, { root });\n const rules = countRules(css);\n\n const result: InspectResult = {\n element,\n classes: tastyClasses,\n chunks,\n css: prettifyCSS(css),\n size: css.length,\n rules,\n };\n\n if (!raw) {\n const tag = element.tagName.toLowerCase();\n const id = element.id ? `#${element.id}` : '';\n console.group(\n `inspect ${tag}${id} — ${tastyClasses.length} classes, ${rules} rules, ${fmtSize(css.length)}`,\n );\n if (chunks.length) {\n console.log(\n 'Chunks:',\n chunks.map((c) => `${c.className}→${c.chunkName || '?'}`).join(', '),\n );\n }\n console.groupCollapsed('CSS');\n console.log(result.css || '(empty)');\n console.groupEnd();\n console.groupEnd();\n }\n\n return result;\n },\n\n summary(opts?: DebugOptions): Summary {\n const { root = document, raw = false } = opts || {};\n\n const activeClasses = findDomTastyClasses(root);\n const unusedClasses = getUnusedClasses(root);\n const totalStyledClasses = [...activeClasses, ...unusedClasses];\n\n const activeCSS = injector.instance.getCssTextForClasses(activeClasses, {\n root,\n });\n const unusedCSS = injector.instance.getCssTextForClasses(unusedClasses, {\n root,\n });\n const allCSS = injector.instance.getCssText({ root });\n\n const activeRuleCount = countRules(activeCSS);\n const unusedRuleCount = countRules(unusedCSS);\n\n const globalData = getGlobalTypeCSS('global', root);\n const rawData = getGlobalTypeCSS('raw', root);\n const kfData = getGlobalTypeCSS('keyframes', root);\n const propData = getGlobalTypeCSS('property', root);\n\n const totalRuleCount =\n activeRuleCount +\n unusedRuleCount +\n globalData.ruleCount +\n rawData.ruleCount +\n kfData.ruleCount +\n propData.ruleCount;\n\n const metrics = injector.instance.getMetrics({ root });\n const defs = getDefs(root);\n const chunkBreakdown = buildChunkBreakdown(root);\n\n const summary: Summary = {\n activeClasses,\n unusedClasses,\n totalStyledClasses,\n activeCSSSize: activeCSS.length,\n unusedCSSSize: unusedCSS.length,\n globalCSSSize: globalData.size,\n rawCSSSize: rawData.size,\n keyframesCSSSize: kfData.size,\n propertyCSSSize: propData.size,\n totalCSSSize: allCSS.length,\n activeRuleCount,\n unusedRuleCount,\n globalRuleCount: globalData.ruleCount,\n rawRuleCount: rawData.ruleCount,\n keyframesRuleCount: kfData.ruleCount,\n propertyRuleCount: propData.ruleCount,\n totalRuleCount,\n metrics,\n definedProperties: defs.properties,\n definedKeyframes: defs.keyframes,\n chunkBreakdown,\n };\n\n if (!raw) {\n console.group('Tasty Summary');\n console.log(\n `Active: ${activeClasses.length} classes, ${activeRuleCount} rules, ${fmtSize(activeCSS.length)}`,\n );\n console.log(\n `Unused: ${unusedClasses.length} classes, ${unusedRuleCount} rules, ${fmtSize(unusedCSS.length)}`,\n );\n console.log(\n `Global: ${globalData.ruleCount} rules, ${fmtSize(globalData.size)}`,\n );\n if (rawData.ruleCount)\n console.log(\n `Raw: ${rawData.ruleCount} rules, ${fmtSize(rawData.size)}`,\n );\n if (kfData.ruleCount)\n console.log(\n `Keyframes: ${kfData.ruleCount} rules, ${fmtSize(kfData.size)}`,\n );\n if (propData.ruleCount)\n console.log(\n `@property: ${propData.ruleCount} rules, ${fmtSize(propData.size)}`,\n );\n console.log(\n `Total: ${totalStyledClasses.length} classes, ${totalRuleCount} rules, ${fmtSize(allCSS.length)}`,\n );\n\n if (metrics) {\n const total = metrics.hits + metrics.misses;\n const rate = total > 0 ? ((metrics.hits / total) * 100).toFixed(1) : 0;\n console.log(`Cache: ${rate}% hit rate (${total} lookups)`);\n }\n\n if (chunkBreakdown.totalChunkTypes > 0) {\n console.groupCollapsed(\n `Chunks (${chunkBreakdown.totalChunkTypes} types, ${chunkBreakdown.totalClasses} classes)`,\n );\n for (const name of CHUNK_ORDER) {\n const d = chunkBreakdown.byChunk[name];\n if (d)\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n for (const [name, d] of Object.entries(chunkBreakdown.byChunk)) {\n if (!CHUNK_ORDER.includes(name as (typeof CHUNK_ORDER)[number]))\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n console.groupEnd();\n }\n\n if (defs.properties.length || defs.keyframes.length) {\n console.log(\n `Defs: ${defs.properties.length} @property, ${defs.keyframes.length} @keyframes`,\n );\n }\n\n console.groupEnd();\n }\n\n return summary;\n },\n\n chunks(opts?: DebugOptions): ChunkBreakdown {\n const { root = document, raw = false } = opts || {};\n const breakdown = buildChunkBreakdown(root);\n\n if (!raw) {\n console.group(\n `Chunks (${breakdown.totalChunkTypes} types, ${breakdown.totalClasses} classes)`,\n );\n for (const name of CHUNK_ORDER) {\n const d = breakdown.byChunk[name];\n if (d)\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n for (const [name, d] of Object.entries(breakdown.byChunk)) {\n if (!CHUNK_ORDER.includes(name as (typeof CHUNK_ORDER)[number]))\n console.log(\n ` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`,\n );\n }\n console.groupEnd();\n }\n\n return breakdown;\n },\n\n cache(opts?: DebugOptions): CacheStatus {\n const { root = document, raw = false } = opts || {};\n const active = findDomTastyClasses(root);\n const unused = getUnusedClasses(root);\n const metrics = injector.instance.getMetrics({ root });\n\n const status: CacheStatus = {\n classes: { active, unused, all: [...active, ...unused] },\n metrics,\n };\n\n if (!raw) {\n console.group('Cache');\n console.log(`Active: ${active.length}, Unused: ${unused.length}`);\n if (metrics) {\n const total = metrics.hits + metrics.misses;\n const rate = total > 0 ? ((metrics.hits / total) * 100).toFixed(1) : 0;\n console.log(\n `Hits: ${metrics.hits}, Misses: ${metrics.misses}, Rate: ${rate}%`,\n );\n }\n console.groupEnd();\n }\n\n return status;\n },\n\n cleanup(opts?: { root?: Document | ShadowRoot }): void {\n injector.instance.cleanup(opts?.root);\n },\n\n help(): void {\n console.log(`tastyDebug API:\n .summary() — overview (classes, rules, sizes)\n .css(\"active\") — CSS for classes in DOM\n .css(\"t42\") — CSS for a specific class\n .css(\"t42\",{source:1})— original CSS before browser parsing (dev only)\n .css(\".selector\") — CSS for a DOM element\n .inspect(\".selector\") — element details (classes, chunks, rules)\n .chunks() — style chunk breakdown\n .cache() — cache status and metrics\n .cleanup() — force unused style cleanup\nOptions: { raw: true } suppresses logging, { root: shadowRoot } targets Shadow DOM`);\n },\n\n install(): void {\n if (typeof window !== 'undefined' && window.tastyDebug !== tastyDebug) {\n window.tastyDebug = tastyDebug;\n console.log('tastyDebug installed. Run tastyDebug.help() for commands.');\n }\n },\n};\n\n// ---------------------------------------------------------------------------\n// Page CSS (minimal, kept internal)\n// ---------------------------------------------------------------------------\n\nfunction getPageCSS(root: Document | ShadowRoot = document): string {\n const chunks: string[] = [];\n try {\n if ('styleSheets' in root) {\n for (const sheet of Array.from((root as Document).styleSheets)) {\n try {\n if (sheet.cssRules)\n chunks.push(\n Array.from(sheet.cssRules)\n .map((r) => r.cssText)\n .join('\\n'),\n );\n } catch {\n /* cross-origin */\n }\n }\n }\n } catch {\n /* ignore */\n }\n return chunks.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Auto-install in development\n// ---------------------------------------------------------------------------\n\nif (typeof window !== 'undefined' && isDevEnv()) {\n tastyDebug.install();\n}\n"],"mappings":";;;;AAqGA,SAAS,QAAQ,OAAuB;AACtC,QAAO,QAAQ,OAAO,IAAI,QAAQ,MAAM,QAAQ,EAAE,CAAC,MAAM,GAAG,MAAM;;AAGpE,SAAS,WAAW,KAAqB;AACvC,SAAQ,IAAI,MAAM,aAAa,IAAI,EAAE,EAAE;;AAGzC,SAAS,iBAAiB,SAAqC;AAC7D,QAAO,MAAM,KAAK,QAAQ,CAAC,MACxB,GAAG,MAAM,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,SAAS,EAAE,MAAM,EAAE,CAAC,CACtD;;AAGH,SAAS,YACP,OAA8B,UACJ;AAC1B,QAAO,SAAS,SAAS,eAAe,YAAY,KAAK;;AAG3D,SAAS,iBAAiB,OAA8B,UAAoB;CAC1E,MAAM,WAAW,YAAY,KAAK;AAClC,KAAI,CAAC,SAAU,QAAO,EAAE;CACxB,MAAM,SAAmB,EAAE;AAC3B,MAAK,MAAM,CAAC,KAAK,OAAO,SAAS,UAC/B,KAAI,OAAO,EAAG,QAAO,KAAK,IAAI;AAEhC,QAAO,iBAAiB,OAAO;;AAGjC,SAAS,oBAAoB,OAA8B,UAAoB;CAC7E,MAAM,0BAAU,IAAI,KAAa;AAEjC,EADkB,KAAkB,mBAAmB,UAAU,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G7E;AAMD,SAAS,WAAW,OAA8B,UAAkB;CAClE,MAAM,SAAmB,EAAE;AAC3B,KAAI;AACF,MAAI,iBAAiB,KACnB,MAAK,MAAM,SAAS,MAAM,KAAM,KAAkB,YAAY,CAC5D,KAAI;AACF,OAAI,MAAM,SACR,QAAO,KACL,MAAM,KAAK,MAAM,SAAS,CACvB,KAAK,MAAM,EAAE,QAAQ,CACrB,KAAK,KAAK,CACd;UACG;SAKN;AAGR,QAAO,OAAO,KAAK,KAAK;;AAO1B,IAAI,OAAO,WAAW,eAAe,UAAU,CAC7C,YAAW,SAAS"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hashString } from "../utils/hash.js";
|
|
1
2
|
import { formatCounterStyleRule } from "../counter-style/index.js";
|
|
2
3
|
import { getGlobalInjector } from "../config.js";
|
|
3
4
|
import { getStyleTarget, pushRSCCSS } from "../rsc-cache.js";
|
|
@@ -43,7 +44,7 @@ function useCounterStyle(descriptors, options) {
|
|
|
43
44
|
const key = `__cs:${options?.name ?? ""}:${serializedContent}`;
|
|
44
45
|
const existingName = target.cache.generatedNames.get(key);
|
|
45
46
|
if (existingName) return existingName;
|
|
46
|
-
const actualName = options?.name ?? `cs${
|
|
47
|
+
const actualName = options?.name ?? `cs${hashString(serializedContent)}`;
|
|
47
48
|
const css = formatCounterStyleRule(actualName, descriptors);
|
|
48
49
|
pushRSCCSS(target.cache, key, css);
|
|
49
50
|
target.cache.generatedNames.set(key, actualName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCounterStyle.js","names":[],"sources":["../../src/hooks/useCounterStyle.ts"],"sourcesContent":["import { getGlobalInjector } from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport type { CounterStyleDescriptors } from '../injector/types';\nimport { getStyleTarget, pushRSCCSS } from '../rsc-cache';\n\ninterface UseCounterStyleOptions {\n name?: string;\n root?: Document | ShadowRoot;\n}\n\nlet clientCounterStyleCounter = 0;\n\nconst clientContentToName = new Map<string, string>();\n\n/* @internal — used only for tests */\nexport function _resetCounterStyleCache(): void {\n clientContentToName.clear();\n clientCounterStyleCounter = 0;\n}\n\n/**\n * Inject a CSS @counter-style rule and return the generated name.\n * Permanent — no cleanup on unmount. Deduplicates by name.\n *\n * Works in all environments: client, SSR with collector, and React Server Components.\n *\n * @example Basic usage\n * ```tsx\n * function EmojiList() {\n * const styleName = useCounterStyle({\n * system: 'cyclic',\n * symbols: '\"👍\"',\n * suffix: '\" \"',\n * }, { name: 'thumbs' });\n *\n * return (\n * <ol style={{ listStyleType: styleName }}>\n * <li>First</li>\n * <li>Second</li>\n * </ol>\n * );\n * }\n * ```\n *\n */\nexport function useCounterStyle(\n descriptors: CounterStyleDescriptors,\n options?: UseCounterStyleOptions,\n): string {\n if (!descriptors || !descriptors.system) {\n return '';\n }\n\n const target = getStyleTarget();\n\n if (target.mode === 'ssr') {\n const actualName = target.collector.allocateCounterStyleName(options?.name);\n const css = formatCounterStyleRule(actualName, descriptors);\n target.collector.collectCounterStyle(actualName, css);\n return actualName;\n }\n\n if (target.mode === 'rsc') {\n const serializedContent = JSON.stringify(descriptors);\n const key = `__cs:${options?.name ?? ''}:${serializedContent}`;\n\n const existingName = target.cache.generatedNames.get(key);\n if (existingName) return existingName;\n\n const actualName
|
|
1
|
+
{"version":3,"file":"useCounterStyle.js","names":[],"sources":["../../src/hooks/useCounterStyle.ts"],"sourcesContent":["import { getGlobalInjector } from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport type { CounterStyleDescriptors } from '../injector/types';\nimport { getStyleTarget, pushRSCCSS } from '../rsc-cache';\nimport { hashString } from '../utils/hash';\n\ninterface UseCounterStyleOptions {\n name?: string;\n root?: Document | ShadowRoot;\n}\n\nlet clientCounterStyleCounter = 0;\n\nconst clientContentToName = new Map<string, string>();\n\n/* @internal — used only for tests */\nexport function _resetCounterStyleCache(): void {\n clientContentToName.clear();\n clientCounterStyleCounter = 0;\n}\n\n/**\n * Inject a CSS @counter-style rule and return the generated name.\n * Permanent — no cleanup on unmount. Deduplicates by name.\n *\n * Works in all environments: client, SSR with collector, and React Server Components.\n *\n * @example Basic usage\n * ```tsx\n * function EmojiList() {\n * const styleName = useCounterStyle({\n * system: 'cyclic',\n * symbols: '\"👍\"',\n * suffix: '\" \"',\n * }, { name: 'thumbs' });\n *\n * return (\n * <ol style={{ listStyleType: styleName }}>\n * <li>First</li>\n * <li>Second</li>\n * </ol>\n * );\n * }\n * ```\n *\n */\nexport function useCounterStyle(\n descriptors: CounterStyleDescriptors,\n options?: UseCounterStyleOptions,\n): string {\n if (!descriptors || !descriptors.system) {\n return '';\n }\n\n const target = getStyleTarget();\n\n if (target.mode === 'ssr') {\n const actualName = target.collector.allocateCounterStyleName(options?.name);\n const css = formatCounterStyleRule(actualName, descriptors);\n target.collector.collectCounterStyle(actualName, css);\n return actualName;\n }\n\n if (target.mode === 'rsc') {\n const serializedContent = JSON.stringify(descriptors);\n const key = `__cs:${options?.name ?? ''}:${serializedContent}`;\n\n const existingName = target.cache.generatedNames.get(key);\n if (existingName) return existingName;\n\n const actualName = options?.name ?? `cs${hashString(serializedContent)}`;\n const css = formatCounterStyleRule(actualName, descriptors);\n pushRSCCSS(target.cache, key, css);\n target.cache.generatedNames.set(key, actualName);\n return actualName;\n }\n\n // Client path: stable name via content-based dedup\n const serializedContent = JSON.stringify(descriptors);\n const cacheKey = `${options?.name ?? ''}:${serializedContent}`;\n\n const existingName = clientContentToName.get(cacheKey);\n if (existingName) {\n return existingName;\n }\n\n const name = options?.name ?? `cs${clientCounterStyleCounter++}`;\n clientContentToName.set(cacheKey, name);\n\n const injector = getGlobalInjector();\n injector.counterStyle(name, descriptors, { root: options?.root });\n\n return name;\n}\n"],"mappings":";;;;;AAWA,IAAI,4BAA4B;AAEhC,MAAM,sCAAsB,IAAI,KAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCrD,SAAgB,gBACd,aACA,SACQ;AACR,KAAI,CAAC,eAAe,CAAC,YAAY,OAC/B,QAAO;CAGT,MAAM,SAAS,gBAAgB;AAE/B,KAAI,OAAO,SAAS,OAAO;EACzB,MAAM,aAAa,OAAO,UAAU,yBAAyB,SAAS,KAAK;EAC3E,MAAM,MAAM,uBAAuB,YAAY,YAAY;AAC3D,SAAO,UAAU,oBAAoB,YAAY,IAAI;AACrD,SAAO;;AAGT,KAAI,OAAO,SAAS,OAAO;EACzB,MAAM,oBAAoB,KAAK,UAAU,YAAY;EACrD,MAAM,MAAM,QAAQ,SAAS,QAAQ,GAAG,GAAG;EAE3C,MAAM,eAAe,OAAO,MAAM,eAAe,IAAI,IAAI;AACzD,MAAI,aAAc,QAAO;EAEzB,MAAM,aAAa,SAAS,QAAQ,KAAK,WAAW,kBAAkB;EACtE,MAAM,MAAM,uBAAuB,YAAY,YAAY;AAC3D,aAAW,OAAO,OAAO,KAAK,IAAI;AAClC,SAAO,MAAM,eAAe,IAAI,KAAK,WAAW;AAChD,SAAO;;CAIT,MAAM,oBAAoB,KAAK,UAAU,YAAY;CACrD,MAAM,WAAW,GAAG,SAAS,QAAQ,GAAG,GAAG;CAE3C,MAAM,eAAe,oBAAoB,IAAI,SAAS;AACtD,KAAI,aACF,QAAO;CAGT,MAAM,OAAO,SAAS,QAAQ,KAAK;AACnC,qBAAoB,IAAI,UAAU,KAAK;AAEtB,oBAAmB,CAC3B,aAAa,MAAM,aAAa,EAAE,MAAM,SAAS,MAAM,CAAC;AAEjE,QAAO"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
+
import { hashString } from "../utils/hash.js";
|
|
1
2
|
import { renderStyles } from "../pipeline/index.js";
|
|
2
3
|
import { getConfig } from "../config.js";
|
|
3
4
|
import { injectGlobal } from "../injector/index.js";
|
|
4
5
|
import { getStyleTarget, pushRSCCSS } from "../rsc-cache.js";
|
|
5
6
|
import { collectAutoInferredProperties, collectAutoInferredPropertiesRSC } from "../ssr/collect-auto-properties.js";
|
|
6
|
-
import { formatGlobalRules } from "../ssr/format-global-rules.js";
|
|
7
7
|
import { resolveRecipes } from "../utils/resolve-recipes.js";
|
|
8
|
-
import {
|
|
8
|
+
import { formatGlobalRules } from "../ssr/format-global-rules.js";
|
|
9
9
|
//#region src/hooks/useGlobalStyles.ts
|
|
10
10
|
const clientGlobalEntries = /* @__PURE__ */ new Map();
|
|
11
11
|
/**
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hashString } from "../utils/hash.js";
|
|
1
2
|
import { keyframes } from "../injector/index.js";
|
|
2
3
|
import { getStyleTarget, pushRSCCSS } from "../rsc-cache.js";
|
|
3
4
|
import { formatKeyframesCSS } from "../ssr/format-keyframes.js";
|
|
@@ -27,7 +28,7 @@ function useKeyframes(stepsOrFactory, depsOrOptions, options) {
|
|
|
27
28
|
const key = `__kf:${opts?.name ?? ""}:${serializedContent}`;
|
|
28
29
|
const existingName = target.cache.generatedNames.get(key);
|
|
29
30
|
if (existingName) return existingName;
|
|
30
|
-
const actualName = opts?.name ?? `k${
|
|
31
|
+
const actualName = opts?.name ?? `k${hashString(serializedContent)}`;
|
|
31
32
|
const css = formatKeyframesCSS(actualName, steps);
|
|
32
33
|
pushRSCCSS(target.cache, key, css);
|
|
33
34
|
target.cache.generatedNames.set(key, actualName);
|