Utility Functions
Core utility functions for working with Coral specifications.
Utility Functions
Core utility functions for parsing, transforming, and working with Coral specifications.
Parsing & Validation
parseUISpec
Parses and validates a UI specification against the Coral schema.
Prop
Type
import { parseUISpec } from '@reallygoodwork/coral-core'
const validatedSpec = await parseUISpec({
name: 'Button',
elementType: 'button',
styles: { padding: '10px', backgroundColor: '#007bff' },
})Returns: Promise<CoralRootNode> - The validated and parsed specification
transformHTMLToSpec
Transforms an HTML string into a Coral specification.
Prop
Type
import { transformHTMLToSpec } from '@reallygoodwork/coral-core'
const spec = transformHTMLToSpec(`
<div class="card">
<h2>Card Title</h2>
<p>Card content</p>
</div>
`)Returns: CoralRootNode - The transformed Coral specification
Dimension Utilities
dimensionToCSS
Converts a dimension object or number to a CSS string.
Prop
Type
Returns: string - CSS dimension string
import { dimensionToCSS } from '@reallygoodwork/coral-core'
dimensionToCSS(16) // "16px"
dimensionToCSS({ value: 2, unit: 'rem' }) // "2rem"
dimensionToCSS({ value: 50, unit: '%' }) // "50%"normalizeDimension
Normalizes dimension values to a standard Dimension format.
Prop
Type
Returns: Dimension - Normalized dimension object
import { normalizeDimension } from '@reallygoodwork/coral-core'
normalizeDimension('16px') // { value: 16, unit: 'px' }
normalizeDimension(16) // { value: 16, unit: 'px' }
normalizeDimension('2rem') // { value: 2, unit: 'rem' }
normalizeDimension({ value: 50, unit: '%' }) // { value: 50, unit: '%' }Media Query Utilities
parseMediaQuery
Parses a CSS media query string into a structured format.
Prop
Type
Returns: Breakpoint | RangeBreakpoint - Parsed breakpoint object
import { parseMediaQuery } from '@reallygoodwork/coral-core'
parseMediaQuery('@media (min-width: 768px)')
// { type: 'min-width', value: '768px' }
parseMediaQuery('@media (min-width: 768px) and (max-width: 1024px)')
// { min: { type: 'min-width', value: '768px' }, max: { type: 'max-width', value: '1024px' } }extractMediaQueriesFromCSS
Extracts media queries and their associated styles from CSS.
Prop
Type
Returns: Array<{ mediaQuery: string; styles: Record<string, string> }> - Array of media queries with styles
import { extractMediaQueriesFromCSS } from '@reallygoodwork/coral-core'
const css = `
.container { padding: 10px; }
@media (min-width: 768px) {
.container { padding: 20px; }
}
`
extractMediaQueriesFromCSS(css, '.container')
// [{ mediaQuery: '@media (min-width: 768px)', styles: { padding: '20px' } }]mediaQueriesToResponsiveStyles
Converts media query objects to ResponsiveStyle format.
Prop
Type
Returns: ResponsiveStyle[] - Array of responsive styles
import { mediaQueriesToResponsiveStyles } from '@reallygoodwork/coral-core'
const mediaQueries = [
{ mediaQuery: '@media (min-width: 768px)', styles: { padding: '20px' } }
]
mediaQueriesToResponsiveStyles(mediaQueries)
// [{ breakpoint: { type: 'min-width', value: '768px' }, styles: { padding: '20px' } }]extractResponsiveStylesFromObject
Extracts responsive styles from an object with media query keys.
Prop
Type
Returns: { baseStyles: Record<string, string>; responsiveStyles: ResponsiveStyle[] } - Separated base and responsive styles
import { extractResponsiveStylesFromObject } from '@reallygoodwork/coral-core'
const styles = {
padding: '10px',
'@media (min-width: 768px)': { padding: '20px' },
'@media (min-width: 1024px)': { padding: '30px' }
}
const { baseStyles, responsiveStyles } = extractResponsiveStylesFromObject(styles)
// baseStyles: { padding: '10px' }
// responsiveStyles: [{ breakpoint: {...}, styles: {...} }, ...]String Utilities
pascalCaseString
Converts a string to PascalCase.
Prop
Type
Returns: string - PascalCase string
import { pascalCaseString } from '@reallygoodwork/coral-core'
pascalCaseString('hello world') // "HelloWorld"
pascalCaseString('my-component-name') // "MyComponentName"
pascalCaseString('user_profile') // "UserProfile"toPascalCase
Converts a string to PascalCase (alternative implementation).
Prop
Type
Returns: string - PascalCase string
import { toPascalCase } from '@reallygoodwork/coral-core'
toPascalCase('hello-world') // "HelloWorld"
toPascalCase('my_component') // "MyComponent"toKebabCase
Converts a string to kebab-case.
Prop
Type
Returns: string - kebab-case string
import { toKebabCase } from '@reallygoodwork/coral-core'
toKebabCase('HelloWorld') // "hello-world"
toKebabCase('MyComponent') // "my-component"Package Utilities
loadPackage
Load a Coral package from disk or other source.
Prop
Type
Prop
Type
import { loadPackage } from '@reallygoodwork/coral-core'
import * as fs from 'fs/promises'
const pkg = await loadPackage('./coral.config.json', {
readFile: (path) => fs.readFile(path, 'utf-8'),
resolveExtends: true,
})
console.log(`Loaded ${pkg.components.size} components`)Returns: Promise<LoadedPackage> - The loaded package with components, tokens, and indexes
validatePackage
Validate all references and structure in a loaded package.
Prop
Type
import { validatePackage } from '@reallygoodwork/coral-core'
const result = validatePackage(pkg)
if (!result.valid) {
for (const error of result.errors) {
console.error(`[${error.type}] ${error.message}`)
}
}Returns: ValidationResult - Validation result with errors and warnings
Prop
Type
getComponent
Get a component from a loaded package by name.
Prop
Type
Returns: CoralRootNode | undefined - The component definition, or undefined if not found
hasComponent
Check if a component exists in a package.
Prop
Type
Returns: boolean - Whether the component exists
import { getComponent, hasComponent } from '@reallygoodwork/coral-core'
if (hasComponent(pkg, 'Button')) {
const button = getComponent(pkg, 'Button')
}getComponentNames
Get all component names in a package.
Prop
Type
Returns: string[] - Array of component names
import { getComponentNames } from '@reallygoodwork/coral-core'
const names = getComponentNames(pkg)
// ['Button', 'Card', 'Input', ...]Variant Utilities
resolveNodeStyles
Resolve all styles for a node given active variant values. Merges base styles with variant-specific overrides and compound variant styles.
Prop
Type
Returns: Partial<CoralStyleType> - Merged styles with variant overrides applied
import { resolveNodeStyles } from '@reallygoodwork/coral-core'
const node = {
styles: { backgroundColor: '#ffffff' },
variantStyles: {
intent: {
primary: { backgroundColor: '#007bff' },
secondary: { backgroundColor: '#6c757d' },
},
},
}
const styles = resolveNodeStyles(node, { intent: 'primary' })
// { backgroundColor: '#007bff' }resolveTreeStyles
Resolve styles for an entire component tree, returning a map of node IDs to their resolved styles.
Prop
Type
Returns: Map<string, Partial<CoralStyleType>> - Map of node IDs to resolved styles
import { resolveTreeStyles } from '@reallygoodwork/coral-core'
const styleMap = resolveTreeStyles(rootNode, { intent: 'primary', size: 'md' })
// Access styles by node ID
const buttonStyles = styleMap.get('button-1')resolveStateStyles
Resolve state styles (hover, focus, disabled, etc.) for a node with active variants.
Prop
Type
Returns: Partial<CoralStyleType> | null - State styles, or null if not defined
import { resolveStateStyles } from '@reallygoodwork/coral-core'
const hoverStyles = resolveStateStyles(node, 'hover', { intent: 'primary' })getVariantCombinations
Get all possible variant combinations from a list of variant axes.
Prop
Type
Returns: Record<string, string>[] - Array of all possible variant combinations
import { getVariantCombinations } from '@reallygoodwork/coral-core'
const combinations = getVariantCombinations([
{ name: 'intent', values: ['primary', 'secondary'] },
{ name: 'size', values: ['sm', 'md', 'lg'] }
])
// [
// { intent: 'primary', size: 'sm' },
// { intent: 'primary', size: 'md' },
// { intent: 'primary', size: 'lg' },
// { intent: 'secondary', size: 'sm' },
// { intent: 'secondary', size: 'md' },
// { intent: 'secondary', size: 'lg' }
// ]getDefaultVariantValues
Get the default values for all variant axes.
Prop
Type
Returns: Record<string, string> - Map of axis names to their default values
import { getDefaultVariantValues } from '@reallygoodwork/coral-core'
const defaults = getDefaultVariantValues(component.componentVariants)
// { intent: 'primary', size: 'md' }validateVariantValues
Validate that variant values match the component's variant definition.
Prop
Type
Returns: { valid: boolean; errors: string[] } - Validation result
import { validateVariantValues } from '@reallygoodwork/coral-core'
const result = validateVariantValues(component.componentVariants, {
intent: 'primary',
size: 'xl' // Invalid - not in size values
})Type Generation
generatePropsInterface
Generate a TypeScript interface for a component's props, including variant props, component props, and event handlers.
Prop
Type
Returns: string - TypeScript interface code
import { generatePropsInterface } from '@reallygoodwork/coral-core'
const code = generatePropsInterface(buttonComponent)
// export interface ButtonProps {
// intent?: "primary" | "secondary" | "destructive";
// size?: "sm" | "md" | "lg";
// label: string;
// disabled?: boolean;
// onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
// className?: string;
// style?: React.CSSProperties;
// }generateComponentTypes
Generate a complete TypeScript declaration file for a component.
Prop
Type
Returns: string - Complete TypeScript declaration file content
import { generateComponentTypes } from '@reallygoodwork/coral-core'
const dts = generateComponentTypes(buttonComponent)
// Includes props interface, variant types, and JSDoc commentspropTypeToTS
Convert a Coral prop type to a TypeScript type string.
Prop
Type
Returns: string - TypeScript type string
import { propTypeToTS } from '@reallygoodwork/coral-core'
propTypeToTS('string') // 'string'
propTypeToTS('number') // 'number'
propTypeToTS('boolean') // 'boolean'
propTypeToTS({ enum: ['a', 'b'] }) // '"a" | "b"'
propTypeToTS({ array: 'string' }) // 'string[]'
propTypeToTS('ReactNode') // 'React.ReactNode'
propTypeToTS('function') // '(...args: unknown[]) => void'generateVariantTypes
Generate TypeScript types for component variants.
Prop
Type
Returns: string - TypeScript type definitions for variants
import { generateVariantTypes } from '@reallygoodwork/coral-core'
const types = generateVariantTypes(component.componentVariants, 'Button')
// export type ButtonIntent = "primary" | "secondary" | "destructive";
// export type ButtonSize = "sm" | "md" | "lg";generateVariantDefaults
Generate default variant values as a TypeScript constant.
Prop
Type
Returns: string - TypeScript constant definition
import { generateVariantDefaults } from '@reallygoodwork/coral-core'
const defaults = generateVariantDefaults(component.componentVariants, 'Button')
// export const ButtonDefaultVariants = { intent: "primary", size: "md" } as const;Reference Utilities
createReferenceResolver
Create a reference resolver for resolving token, prop, and asset references in a loaded package.
Prop
Type
Prop
Type
Returns: ReferenceResolver - Reference resolver with methods to resolve tokens, props, and assets
import { createReferenceResolver } from '@reallygoodwork/coral-core'
const resolver = createReferenceResolver(pkg, { tokenContext: 'dark' })
// Resolve token references
const color = resolver.resolveToken({ $token: 'color.primary.500' })
// Resolve prop references
const label = resolver.resolveProp({ $prop: 'label' }, { label: 'Click me' })
// Resolve asset references
const imagePath = resolver.resolveAsset({ $asset: 'logo.png' })resolveStyleReferences
Resolve all token and prop references in a style object.
Prop
Type
Returns: CoralStyleType - Style object with all references resolved
import { resolveStyleReferences } from '@reallygoodwork/coral-core'
const resolvedStyles = resolveStyleReferences(
{
color: { $token: 'color.text.primary' },
padding: { $prop: 'padding' }
},
resolver,
{ padding: '16px' }
)
// { color: '#000000', padding: '16px' }resolveValue
Resolve a single value that may contain references.
Prop
Type
Returns: unknown - Resolved value
import { resolveValue } from '@reallygoodwork/coral-core'
const resolved = resolveValue(
{ $token: 'spacing.md' },
resolver,
{}
)
// '16px'collectTokenReferences
Collect all token references from a node tree.
Prop
Type
Returns: Set<string> - Set of all token reference paths
import { collectTokenReferences } from '@reallygoodwork/coral-core'
const tokens = collectTokenReferences(rootNode)
// Set(['color.primary.500', 'spacing.md', 'typography.body'])collectPropReferences
Collect all prop references from a node tree.
Prop
Type
Returns: Set<string> - Set of all prop names referenced
import { collectPropReferences } from '@reallygoodwork/coral-core'
const props = collectPropReferences(rootNode)
// Set(['label', 'disabled', 'onClick'])Composition Utilities
resolveComponentInstance
Resolve a component instance to its full definition with props and slots resolved.
Prop
Type
Returns: ResolvedInstance - Resolved instance with component, props, and slots
Prop
Type
import { resolveComponentInstance } from '@reallygoodwork/coral-core'
const resolved = resolveComponentInstance(
buttonInstance,
{ intent: 'primary', label: 'Click me' },
{},
pkg
)
console.log(resolved.resolvedProps) // { intent: 'primary', label: 'Click me', ... }flattenComponentTree
Flatten a component tree by resolving all component instances to their actual node structures.
Prop
Type
Returns: CoralNode - Flattened component tree with all instances resolved
import { flattenComponentTree } from '@reallygoodwork/coral-core'
const flattened = flattenComponentTree(rootNode, {}, {}, pkg)
// All component instances are now resolved to their actual node structuresfindComponentInstances
Find all component instances in a node tree.
Prop
Type
Returns: ComponentInstance[] - Array of all component instances found
import { findComponentInstances } from '@reallygoodwork/coral-core'
const instances = findComponentInstances(rootNode)
// All nodes with $component referencesgetComponentDependencies
Get all component dependencies for a given component.
Prop
Type
Returns: string[] - Array of component names that this component depends on
import { getComponentDependencies } from '@reallygoodwork/coral-core'
const deps = getComponentDependencies(cardComponent)
// ['Button', 'Icon']getComponentOrder
Get the order in which components should be built (topological sort).
Prop
Type
Returns: string[] - Array of component names in build order
import { getComponentOrder } from '@reallygoodwork/coral-core'
const order = getComponentOrder(pkg)
// Components are ordered so dependencies come before dependentsfindCircularDependencies
Check for circular component dependencies in a package.
Prop
Type
Returns: string[][] - Array of circular dependency chains (each chain is an array of component names)
import { findCircularDependencies } from '@reallygoodwork/coral-core'
const circles = findCircularDependencies(pkg)
if (circles.length > 0) {
console.error('Circular dependencies found:', circles)
}validateComposition
Validate that all component instances in a package can be resolved.
Prop
Type
Returns: { valid: boolean; errors: string[] } - Validation result
import { validateComposition } from '@reallygoodwork/coral-core'
const result = validateComposition(pkg)
if (!result.valid) {
console.error('Composition errors:', result.errors)
}hasComponentInstances
Check if a node tree contains any component instances.
Prop
Type
Returns: boolean - Whether the tree contains component instances
import { hasComponentInstances } from '@reallygoodwork/coral-core'
if (hasComponentInstances(rootNode)) {
// Tree contains component instances
}countComponentInstances
Count the number of component instances in a node tree.
Prop
Type
Returns: number - Number of component instances
import { countComponentInstances } from '@reallygoodwork/coral-core'
const count = countComponentInstances(rootNode)
console.log(`Found ${count} component instances`)Conditional Utilities
evaluateCondition
Evaluate a conditional expression against a set of props.
Prop
Type
Returns: boolean - The result of the conditional expression
import { evaluateCondition } from '@reallygoodwork/coral-core'
// Simple prop check
evaluateCondition({ $prop: 'enabled' }, { enabled: true })
// true
// Complex expression
const result = evaluateCondition(
{ $and: [{ $prop: 'enabled' }, { $not: { $prop: 'loading' } }] },
{ enabled: true, loading: false }
)
// true
// Equality check
evaluateCondition(
{ $eq: [{ $prop: 'status' }, 'active'] },
{ status: 'active' }
)
// trueSupported operators:
{ $prop: string }- Check if prop is truthy{ $not: ConditionalExpression }- Logical NOT{ $and: ConditionalExpression[] }- Logical AND{ $or: ConditionalExpression[] }- Logical OR{ $eq: [ConditionalExpression, unknown] }- Equality check{ $ne: [ConditionalExpression, unknown] }- Inequality check
Props Validation Utilities
validateProps
Validate all prop bindings in a package, checking for missing required props, type mismatches, and constraint violations.
Prop
Type
Returns: PropValidationResult - Validation result with errors and warnings
Prop
Type
import { validateProps } from '@reallygoodwork/coral-core'
const result = validateProps(pkg)
if (!result.valid) {
for (const error of result.errors) {
console.error(`[${error.type}] ${error.path}: ${error.message}`)
}
}findUnusedProps
Find props that are defined but never used in a component.
Prop
Type
Returns: string[] - Array of unused prop names
import { findUnusedProps } from '@reallygoodwork/coral-core'
const unused = findUnusedProps(component)
if (unused.length > 0) {
console.warn(`Unused props: ${unused.join(', ')}`)
}Package Writer Utilities
writePackage
Write a complete Coral package to disk.
Prop
Type
Returns: Promise<void>
import { writePackage } from '@reallygoodwork/coral-core'
import * as fs from 'fs/promises'
await writePackage('./my-package', {
config: packageConfig,
components: componentMap,
tokens: tokenMap,
}, {
writeFile: (path, content) => fs.writeFile(path, content, 'utf-8'),
})writeComponent
Write a single component to disk.
Prop
Type
Returns: Promise<void>
import { writeComponent } from '@reallygoodwork/coral-core'
await writeComponent(
'./components/button/button.coral.json',
buttonComponent,
{ writeFile: (path, content) => fs.writeFile(path, content, 'utf-8') }
)createComponentScaffold
Create a scaffold for a new component with default structure.
Prop
Type
Returns: CoralRootNode - Scaffolded component with default structure
import { createComponentScaffold } from '@reallygoodwork/coral-core'
const scaffold = createComponentScaffold('Button', 'Actions')
// Returns a basic component structure ready for customizationRelated
- Types & Guards - Type definitions
- CLI Commands - Command-line interface
- Package System - Package management