title: Core API Reference | TokiForge description: Complete API reference for TokiForge core classes. ThemeRuntime, TokenExporter, TokenParser, and all core functionality for design token management.
Core API Reference
Complete API reference for @tokiforge/core package.
ThemeRuntime
Central class for managing theme lifecycle and CSS variable injection.
Constructor
new ThemeRuntime(config: ThemeConfig)Creates a new theme runtime instance.
Parameters:
config: ThemeConfig- Theme configuration object
Example:
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime({
themes: [
{
name: 'light',
tokens: {
color: {
primary: { value: '#3b82f6' },
background: { value: '#ffffff' },
},
},
},
{
name: 'dark',
tokens: {
color: {
primary: { value: '#60a5fa' },
background: { value: '#1f2937' },
},
},
},
],
defaultTheme: 'light',
});init()
async init(selector?: string, prefix?: string): Promise<void>Initialize the runtime and apply the default theme.
Parameters:
selector?: string- CSS selector for variable injection (default::root)prefix?: string- Prefix for CSS variables (default:hf)
Example:
await runtime.init(':root', 'app');
// CSS variables will be: --app-color-primary, --app-color-background, etc.applyTheme()
async applyTheme(
themeName: string,
selector?: string,
prefix?: string
): Promise<void>Apply a theme by injecting CSS variables.
Parameters:
themeName: string- Name of the theme to applyselector?: string- CSS selector (default::root)prefix?: string- Variable prefix (default:hf)
Throws:
ThemeNotFoundError- If theme doesn't exist
Events:
- Dispatches
tokiforge:theme-changeevent with{ theme, tokens }
Example:
await runtime.applyTheme('dark');
// With custom selector and prefix
await runtime.applyTheme('dark', '[data-theme="dark"]', 'custom');getCurrentTheme()
getCurrentTheme(): string | nullGet the currently active theme name.
Returns: string | null - Current theme name or null if none applied
Example:
const currentTheme = runtime.getCurrentTheme();
console.log(currentTheme); // 'dark'getThemeTokens()
getThemeTokens(themeName: string): DesignTokensGet token values for a specific theme.
Parameters:
themeName: string- Theme name
Returns: DesignTokens - Token object
Throws:
ThemeError- If theme not loaded or doesn't exist
Example:
const tokens = runtime.getThemeTokens('dark');
console.log(tokens.color.primary.value); // '#60a5fa'getAvailableThemes()
getAvailableThemes(): string[]Get list of all available theme names.
Returns: string[] - Array of theme names
Example:
const themes = runtime.getAvailableThemes();
console.log(themes); // ['light', 'dark']nextTheme()
nextTheme(): stringGet the next theme in rotation.
Returns: string - Next theme name
Example:
const next = runtime.nextTheme();
await runtime.applyTheme(next);watchSystemTheme()
watchSystemTheme(callback: (theme: string) => void): () => voidWatch for system theme changes (light/dark).
Parameters:
callback: (theme: string) => void- Called with 'light' or 'dark'
Returns: () => void - Unwatch function
Example:
const unwatch = runtime.watchSystemTheme((systemTheme) => {
console.log('System theme changed to:', systemTheme);
runtime.applyTheme(systemTheme);
});
// Later: stop watching
unwatch();destroy()
destroy(): voidClean up runtime resources and remove injected styles.
Example:
runtime.destroy();Static: detectSystemTheme()
static detectSystemTheme(): stringDetect current system color scheme preference.
Returns: string - 'dark' or 'light'
Example:
const systemTheme = ThemeRuntime.detectSystemTheme();
console.log(systemTheme); // 'dark' or 'light'TokenExporter
Export tokens to various formats.
export()
static export(
tokens: DesignTokens,
options: TokenExportOptions
): stringExport tokens to specified format.
Parameters:
tokens: DesignTokens- Token object to exportoptions: TokenExportOptions- Export configuration
Returns: string - Formatted output
Example:
import { TokenExporter } from '@tokiforge/core';
const css = TokenExporter.export(tokens, {
format: 'css',
selector: ':root',
prefix: 'app',
});exportCSS()
static exportCSS(
tokens: DesignTokens,
options?: { selector?: string; prefix?: string }
): stringExport as CSS variables.
Example:
const css = TokenExporter.exportCSS(tokens, {
selector: ':root',
prefix: 'app',
});
console.log(css);
// :root {
// --app-color-primary: #3b82f6;
// --app-color-background: #ffffff;
// }exportSCSS()
static exportSCSS(
tokens: DesignTokens,
options?: { prefix?: string }
): stringExport as SCSS variables.
Example:
const scss = TokenExporter.exportSCSS(tokens, { prefix: 'app' });
console.log(scss);
// $app-color-primary: #3b82f6;
// $app-color-background: #ffffff;exportJS()
static exportJS(
tokens: DesignTokens,
options?: { variables?: boolean; prefix?: string }
): stringExport as JavaScript module.
Example:
// Export as CSS variable references
const jsVars = TokenExporter.exportJS(tokens, {
variables: true,
prefix: 'app'
});
// Export as plain object
const jsObj = TokenExporter.exportJS(tokens, { variables: false });exportTS()
static exportTS(tokens: DesignTokens): stringExport as TypeScript module with const assertion.
Example:
const ts = TokenExporter.exportTS(tokens);
// export default { ... } as const;exportJSON()
static exportJSON(tokens: DesignTokens): stringExport as formatted JSON.
Example:
const json = TokenExporter.exportJSON(tokens);TokenParser
Parse and validate token files. Now supports advanced features including functions, expressions, and fallback references.
Advanced Features
The parser supports:
- Token Functions:
darken({color.primary}, 20) - Expressions:
{spacing.base} * 2 - Fallback References:
{color.primary || #000000}
See Token Functions, Token Expressions, and Token References for details.
parse()
static parse(
filePath: string,
options?: TokenParserOptions
): DesignTokensParse token file (JSON or YAML).
Parameters:
filePath: string- Path to token fileoptions?: TokenParserOptions- Parser options
Throws:
ParseError- If file can't be parsedValidationError- If validation fails
Example:
import { TokenParser } from '@tokiforge/core';
const tokens = TokenParser.parse('./tokens.json', {
validate: true,
expandReferences: true,
});validate()
static validate(tokens: DesignTokens): voidValidate token structure.
Throws:
ValidationError- If validation fails
Example:
try {
TokenParser.validate(tokens);
console.log('Tokens are valid!');
} catch (error) {
console.error('Validation failed:', error.message);
}expandReferences()
static expandReferences(tokens: DesignTokens): DesignTokensExpand token references (e.g., {color.primary}).
Example:
const tokens = {
color: {
blue: { value: '#3b82f6' },
primary: { value: '{color.blue}' },
},
};
const expanded = TokenParser.expandReferences(tokens);
console.log(expanded.color.primary.value); // '#3b82f6'Type Definitions
ThemeConfig
interface ThemeConfig {
themes: Theme[];
defaultTheme?: string;
}Theme
interface Theme {
name: string;
tokens: ThemeTokensProvider;
}
type ThemeTokensProvider =
| DesignTokens
| (() => Promise<DesignTokens>);DesignTokens
interface DesignTokens {
[key: string]: TokenValue | DesignTokens;
}TokenValue
interface TokenValue {
value: string | number | TokenState | TokenResponsive;
type?: 'color' | 'dimension' | 'fontFamily' | 'fontWeight' | 'duration' | 'custom';
description?: string;
deprecated?: boolean;
}TokenExportOptions
interface TokenExportOptions {
format: 'css' | 'js' | 'ts' | 'scss' | 'json';
selector?: string;
prefix?: string;
variables?: boolean;
}Error Classes
ThemeError
Base error for theme-related issues.
class ThemeError extends Error {
constructor(message: string, path?: string);
}ThemeNotFoundError
Thrown when theme doesn't exist.
class ThemeNotFoundError extends ThemeError {
constructor(themeName: string, availableThemes?: string[]);
}ParseError
Thrown when token file parsing fails.
class ParseError extends Error {
constructor(message: string, path?: string);
}ValidationError
Thrown when token validation fails.
class ValidationError extends Error {
constructor(message: string, path?: string);
}TokenVersioning
Track token versions and manage deprecations.
import { TokenVersioning } from '@tokiforge/core';
const tokens = {
color: {
primary: {
value: '#7C3AED',
version: {
version: '1.0.0',
introduced: '2024-01-01',
deprecated: '2024-06-01',
replacedBy: 'color.brand.primary',
migration: 'Use color.brand.primary instead'
}
}
}
};
const warnings = TokenVersioning.getDeprecatedTokens(tokens);
const activeTokens = TokenVersioning.filterDeprecated(tokens, false);ComponentTheming
Scoped themes for individual components.
import { ComponentTheming } from '@tokiforge/core';
const theming = new ComponentTheming();
theming.registerComponentTheme({
name: 'button',
scope: 'btn',
tokens: {
color: {
primary: { value: '#7C3AED' },
hover: { value: '#6D28D9' }
}
}
});
const buttonTokens = theming.getScopedTokens('button', globalTokens);
const css = theming.applyComponentTheme('button', '.btn', 'hf');PluginManager
Extend TokiForge with custom functionality.
import { pluginManager } from '@tokiforge/core';
pluginManager.register({
name: 'my-exporter',
exporter: (tokens, options) => {
return JSON.stringify(tokens, null, 2);
},
validator: (tokens) => {
return { valid: true, errors: [] };
}
});
const output = pluginManager.export(tokens, 'my-exporter');AccessibilityUtils
Built-in accessibility checking and utilities.
import { AccessibilityUtils } from '@tokiforge/core';
const contrast = AccessibilityUtils.calculateContrast('#000000', '#FFFFFF');
const metrics = AccessibilityUtils.checkAccessibility(tokens);
const report = AccessibilityUtils.generateAccessibilityReport(tokens);ResponsiveTokens
Breakpoint and state-aware tokens.
import { ResponsiveTokens } from '@tokiforge/core';
const tokens = {
spacing: {
padding: {
value: '16px',
responsive: {
sm: '8px',
md: '16px',
lg: '24px'
}
}
}
};
const responsive = ResponsiveTokens.process(tokens);FigmaDiff
Compare and sync tokens with Figma.
import { FigmaDiff } from '@tokiforge/core';
const diff = FigmaDiff.compare(localTokens, figmaTokens);
const sync = FigmaDiff.sync(localTokens, figmaTokens, { strategy: 'merge' });CICDValidator
Automated validation for CI/CD pipelines.
import { CICDValidator } from '@tokiforge/core';
const validator = new CICDValidator();
const result = await validator.validate(tokens);
if (!result.valid) {
console.error(result.errors);
process.exit(1);
}TokenAnalytics
Token usage tracking and bundle impact analysis.
import { TokenAnalytics } from '@tokiforge/core';
const analytics = new TokenAnalytics();
const usage = analytics.trackUsage(tokens);
const impact = analytics.analyzeBundleImpact(tokens);TokenRegistry
Multi-team design system support.
import { TokenRegistry } from '@tokiforge/core';
const registry = new TokenRegistry();
registry.register('team-a', tokensA);
registry.register('team-b', tokensB);
const merged = registry.merge();IDESupport
IDE autocomplete and hover previews.
import { IDESupport } from '@tokiforge/core';
IDESupport.generateTypes(tokens, './tokens.d.ts');
IDESupport.generateAutocomplete(tokens, './tokens.json');