Skip to content

Core API reference

Source information
  • Package: @pikacss/core
  • Generated from the exported surface and JSDoc in packages/core/src/index.ts.
  • Source files: packages/core/src/index.ts, packages/core/src/internal/engine.ts, packages/core/src/internal/plugin.ts, packages/core/src/internal/plugins/important.ts, packages/core/src/internal/plugins/keyframes.ts, packages/core/src/internal/plugins/selectors.ts, packages/core/src/internal/plugins/shortcuts.ts, packages/core/src/internal/plugins/variables.ts, packages/core/src/internal/types/autocomplete.ts, packages/core/src/internal/types/engine.ts, packages/core/src/internal/types/preflight.ts, packages/core/src/internal/types/resolved.ts, packages/core/src/internal/types/shared.ts, packages/core/src/internal/types/utils.ts, packages/core/src/internal/utils.ts, packages/core/src/types.ts

Package summary

Core engine, style definition helpers, and built-in plugin system

Use Usage guide when you need conceptual usage guidance instead of exact symbol lookup.

Functions

appendAutocomplete(config, contribution)

Merges an AutocompleteContribution or AutocompleteConfig into the resolved autocomplete state, returning whether any entry changed.

ParameterTypeDescription
configPick<ResolvedEngineConfig, 'autocomplete'>The resolved engine config (or a subset with the autocomplete field) to mutate.
contributionAutocompleteContribution | AutocompleteConfigThe autocomplete entries to merge in.

Remarks:

Called by engine.appendAutocomplete() and during initial config resolution. Each sub-field (selectors, shortcuts, etc.) is independently merged and the function returns true if any of them changed, which triggers an autocompleteConfigUpdated notification.

ts
const changed = appendAutocomplete(resolvedConfig, {
  selectors: 'dark',
  cssProperties: { color: 'primary' },
})


createEngine(config?)

Creates and initializes a PikaCSS engine with the given configuration.

ParameterTypeDescription
config?EngineConfigThe engine configuration, including plugins, selectors, shortcuts, variables, keyframes, preflights, and layer settings.

Returns: Promise<Engine> - A fully initialized Engine instance.

Remarks:

Core plugins (important, variables, keyframes, selectors, shortcuts) are prepended automatically. The function resolves plugins, runs all configuration hooks in sequence, and returns the ready-to-use engine.

ts
const engine = await createEngine({ prefix: 'pk-', plugins: [myPlugin()] })


createLogger(prefix)

Creates a scoped logger with configurable log-level functions and a toggleable debug mode.

ParameterTypeDescription
prefixstringLabel prepended to every log message (e.g. '[PikaCSS]').

Remarks:

Debug messages are suppressed by default. Call log.toggleDebug() to enable them. Each log level can be replaced with a custom implementation via the set*Fn methods, which is useful for redirecting output in non-browser environments.

ts
const log = createLogger('[MyPlugin]')
log.info('initialized')  // '[MyPlugin][INFO] initialized'
log.toggleDebug()
log.debug('verbose info') // '[MyPlugin][DEBUG] verbose info'


defineEngineConfig(config)

Identity helper that returns the engine configuration as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
configTThe engine configuration object.

Returns: T - The same configuration object, unchanged.

Remarks:

A compile-time-only helper with no runtime effect. Useful in pika.config.ts files for IDE support.

ts
export default defineEngineConfig({ prefix: 'pk-', plugins: [myPlugin()] })


defineEnginePlugin(plugin)

Identity helper that returns the plugin object as-is, providing TypeScript type inference for plugin definitions.

ParameterTypeDescription
pluginEnginePluginThe engine plugin definition.

Returns: EnginePlugin - The same plugin object, unchanged.

Remarks:

This is a compile-time-only helper; it has no runtime effect. Using it ensures type checking and IDE autocompletion for hook names and payloads.

ts
export default defineEnginePlugin({
  name: 'my-plugin',
  configureRawConfig: (config) => ({ ...config, important: true }),
})


defineKeyframes(keyframes)

Identity helper that returns the keyframes definition as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
keyframesTA keyframes definition: a name string, a tuple, or an object form.

Returns: T - The same keyframes definition, unchanged.

Remarks:

A compile-time-only helper with no runtime effect.

ts
const spin = defineKeyframes(['spin', { from: { transform: 'rotate(0deg)' }, to: { transform: 'rotate(360deg)' } }])


definePreflight(preflight)

Identity helper that returns the preflight as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
preflightTA preflight definition: a function, a static string/object, or a wrapper with layer/id metadata.

Returns: T - The same preflight, unchanged.

Remarks:

A compile-time-only helper with no runtime effect. Useful for defining reusable preflight values with type safety.

ts
const reset = definePreflight('*, *::before { box-sizing: border-box; }')


defineSelector(selector)

Identity helper that returns the selector definition as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
selectorTA selector definition: a string redirect, tuple, or object form.

Returns: T - The same selector definition, unchanged.

Remarks:

A compile-time-only helper with no runtime effect.

ts
const hover = defineSelector(['hover', '&:hover'])


defineShortcut(shortcut)

Identity helper that returns the shortcut definition as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
shortcutTA shortcut definition: a string redirect, tuple, or object form.

Returns: T - The same shortcut definition, unchanged.

Remarks:

A compile-time-only helper with no runtime effect.

ts
const btn = defineShortcut(['btn', { padding: '0.5rem 1rem', borderRadius: '0.25rem' }])


defineStyleDefinition(styleDefinition)

Identity helper that returns the style definition as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
styleDefinitionTA style definition object.

Returns: T - The same style definition, unchanged.

Remarks:

A compile-time-only helper with no runtime effect. Useful for extracting a reusable style definition with full type safety.

ts
const card = defineStyleDefinition({ padding: '1rem', borderRadius: '0.5rem' })


defineVariables(variables)

Identity helper that returns the variables definition as-is, providing TypeScript type inference and autocompletion.

ParameterTypeDescription
variablesTA nested record of CSS custom property definitions.

Returns: T - The same variables definition, unchanged.

Remarks:

A compile-time-only helper with no runtime effect.

ts
const vars = defineVariables({ '--color-primary': '#3b82f6', '.dark': { '--color-primary': '#60a5fa' } })


extractUsedVarNames(input)

Extracts all CSS variable names referenced via var(--*) calls in a string.

ParameterTypeDescription
inputstringThe CSS value string to scan.

Returns: string[] - An array of variable names (including the -- prefix) found in var() expressions.

Remarks:

Uses a global regex to find all var(--name) occurrences. Nested var() calls are matched independently.

ts
extractUsedVarNames('color: var(--primary)')  // ['--primary']
extractUsedVarNames('var(--a) var(--b)')       // ['--a', '--b']


extractUsedVarNamesFromPreflightResult(result)

Recursively extracts all CSS variable names referenced in a preflight result.

ParameterTypeDescription
resultstring | PreflightDefinitionA preflight output: either a raw CSS string or a nested PreflightDefinition object.

Returns: string[] - A flat array of normalized variable names found in the result.

Remarks:

For string results, scans for var(--*) references. For object results, recursively traverses selector scopes and string/number values. All returned names are normalized with the -- prefix.

ts
extractUsedVarNamesFromPreflightResult({ ':root': { color: 'var(--primary)' } })
// ['--primary']


important()

Built-in engine plugin that appends !important to generated CSS declarations.

Remarks:

When EngineConfig.important.default is true, all property values receive !important unless the style definition explicitly sets __important: false. Individual style definitions can also opt-in with __important: true regardless of the default.

ts
createEngine({ plugins: [important()] })


keyframes()

Built-in engine plugin that provides CSS @keyframes registration, autocomplete integration, and smart pruning.

Remarks:

Reads EngineConfig.keyframes during rawConfigConfigured and attaches the engine.keyframes management interface during configureEngine. Unused keyframes are pruned from the output unless pruneUnused: false is set on the individual definition or globally.

ts
createEngine({ plugins: [keyframes()] })


normalizeVariableName(name)

Ensures a variable name has the -- prefix.

ParameterTypeDescription
namestringThe variable name, with or without the -- prefix.

Remarks:

A no-op when the name already starts with --.

ts
normalizeVariableName('color')     // '--color'
normalizeVariableName('--color')   // '--color'


renderCSSStyleBlocks(blocks, isFormatted, depth?)

Serializes a CSSStyleBlocks tree into a CSS string, optionally formatted with indentation and newlines.

ParameterTypeDescription
blocksCSSStyleBlocksThe CSS block tree to render.
isFormattedbooleanWhen true, output includes indentation and newlines for readability; when false, output is minified.
depth?unknownCurrent nesting depth for indentation (defaults to 0).

Remarks:

Recursively renders nested blocks (e.g. media queries wrapping selectors). Empty blocks (no properties and no children) are omitted from the output.

ts
const blocks: CSSStyleBlocks = new Map()
blocks.set('.pk-a', { properties: [{ property: 'color', value: 'red' }] })
renderCSSStyleBlocks(blocks, true)
// '.pk-a {\n  color: red;\n}'


resolveSelectorConfig(config)

Normalizes a Selector configuration into a ResolvedRuleConfig, a redirect string, or undefined.

ParameterTypeDescription
configSelectorThe selector rule configuration to resolve.

Remarks:

Delegates to the generic resolveRuleConfig with 'selector' as the key name.

ts
const resolved = resolveSelectorConfig(['hover', '&:hover'])


selectors()

Built-in engine plugin that provides the selector resolution system.

Remarks:

Reads EngineConfig.selectors during rawConfigConfigured, attaches a RecursiveResolver to engine.selectors during configureEngine, and resolves all selector strings in the transformSelectors hook.

ts
createEngine({ plugins: [selectors()] })


shortcuts()

Built-in engine plugin that provides the shortcut resolution system.

Remarks:

Reads EngineConfig.shortcuts during rawConfigConfigured, attaches a RecursiveResolver to engine.shortcuts during configureEngine, and expands shortcut references in both transformStyleItems (string style items) and transformStyleDefinitions (the __shortcut pseudo-property).

ts
createEngine({ plugins: [shortcuts()] })


sortLayerNames(layers)

Sorts layer names by their numeric weight, then alphabetically for ties.

ParameterTypeDescription
layersRecord<string, number>A record mapping layer names to numeric weights.

Returns: string[] - An array of layer names in ascending weight order.

Remarks:

Used to produce the @layer declaration order and to order layer group rendering.

ts
sortLayerNames({ utilities: 10, preflights: 1 })
// ['preflights', 'utilities']


variables()

Built-in engine plugin that provides CSS custom properties (variables) with smart pruning and autocomplete integration.

Remarks:

Reads EngineConfig.variables during rawConfigConfigured and attaches the engine.variables management interface during configureEngine. A preflight is registered that collects variable references from atomic styles and other preflights, transitively expands dependencies, and emits only used (or safe-listed) variables.

ts
createEngine({ plugins: [variables()] })


Constants

log

Default logger instance used throughout the PikaCSS core engine, prefixed with [PikaCSS].

Remarks:

Shared across all internal modules. Plugins and integration code can call log.toggleDebug() to enable verbose output during development.

ts
log.info('Engine created')
log.warn('Unknown layer detected')


Classes

Engine

The PikaCSS engine: manages atomic style resolution, rendering, preflights, and plugin hooks.

PropertyTypeDescriptionDefault
configResolvedEngineConfigThe fully resolved engine configuration.
pluginHooks``Reference to the plugin hook dispatcher for invoking lifecycle hooks.
extractExtractFnThe extraction function that decomposes style definitions into atomic style contents.
storeEngineStoreThe engine's runtime store holding registered atomic styles and their ID mappings.

Methods:

notifyPreflightUpdated()

Fires the preflightUpdated hook to notify plugins that preflight content has changed.

notifyAtomicStyleAdded(atomicStyle)

Fires the atomicStyleAdded hook to notify plugins that a new atomic style was registered.

ParameterTypeDescription
atomicStyleAtomicStyleThe atomic style that was just added to the store.

notifyAutocompleteConfigUpdated()

Fires the autocompleteConfigUpdated hook to notify plugins that autocomplete entries changed.

appendAutocomplete(contribution)

Merges an autocomplete contribution into the resolved autocomplete config.

ParameterTypeDescription
contributionAutocompleteContributionThe autocomplete entries to append (selectors, properties, CSS properties, etc.).

appendCssImport(cssImport)

Appends a CSS @import statement to the preflight output.

ParameterTypeDescription
cssImportstringThe raw @import string (a trailing semicolon is appended if missing).

addPreflight(preflight)

Registers a new preflight that will be rendered before atomic styles.

ParameterTypeDescription
preflightPreflightA preflight definition: a function, a static string/object, or a wrapper with layer/id metadata.

use(itemList)

Processes style items through the plugin pipeline and registers the resulting atomic styles in the store.

ParameterTypeDescription
itemListInternalStyleItem[]Style items to process: string references (shortcuts) and/or style definition objects.

Returns: Promise<string[]> - An array of atomic style IDs (and unresolved string references) in insertion order.

renderPreflights(isFormatted)

Renders all registered preflight definitions into a CSS string.

ParameterTypeDescription
isFormattedbooleanWhether to produce human-readable CSS with newlines and indentation.

renderAtomicStyles(isFormatted, options?)

Renders atomic styles into a CSS string, optionally filtered by ID and grouped by layer.

ParameterTypeDescription
isFormattedbooleanWhether to produce human-readable CSS with newlines and indentation.
options?{ atomicStyleIds?: string[], isPreview?: boolean }Optional filtering: atomicStyleIds to render a subset, isPreview to use placeholder IDs.

renderLayerOrderDeclaration()

Renders the CSS @layer order declaration for all configured layers.

Returns: string - A @layer statement listing layer names in weight order, or an empty string if no layers are configured.

Remarks:

Constructed via createEngine(). Holds the resolved configuration, the atomic style store, and exposes methods for processing style items (use), rendering CSS output (renderPreflights, renderAtomicStyles, renderLayerOrderDeclaration), and managing runtime extensions (addPreflight, appendAutocomplete, appendCssImport).

ts
const engine = await createEngine({ prefix: 'pk-' })
const ids = await engine.use({ color: 'red' })
const css = await engine.renderAtomicStyles(true)


Types

Arrayable

A value that can be either a single item or an array of items.

Remarks:

Used pervasively in configuration surfaces so consumers can pass a single value or an array without explicit wrapping.

ts
function normalize<T>(input: Arrayable<T>): T[] {
  return [input].flat() as T[]
}
normalize('a')     // ['a']
normalize(['a','b']) // ['a','b']


AutocompleteConfig

User-facing autocomplete configuration supplied in EngineConfig.autocomplete.

PropertyTypeDescriptionDefault
selectors?Arrayable<string>Selector name strings for autocomplete suggestions.undefined
shortcuts?Arrayable<string>Shortcut name strings for autocomplete suggestions.undefined
extraProperties?Arrayable<string>Extra non-CSS property names to surface in autocomplete.undefined
extraCssProperties?Arrayable<string>Extra CSS property names to surface in autocomplete.undefined
properties?[property: string, tsType: Arrayable<string>][] | Record<string, Arrayable<string>>Property-to-type mapping. Accepts either a record or an ordered array of [property, type] tuples.undefined
cssProperties?[property: string, value: Arrayable<string>][] | Record<string, Arrayable<string>>CSS property-to-value mapping. Accepts either a record or an ordered array of [property, value] tuples.undefined
patterns?AutocompletePatternsConfigPattern-based entries for generating expanded autocomplete suggestions.undefined

Remarks:

Accepts the same shape as AutocompleteContribution but additionally allows properties and cssProperties as tuple arrays for ordered definitions. Normalized into the resolved config during engine initialization.

ts
const config: AutocompleteConfig = {
  selectors: ['hover', 'focus'],
  properties: [['spacing', ['sm', 'md', 'lg']]],
}


AutocompleteContribution

A partial set of autocomplete entries contributed by a plugin or engine subsystem at runtime.

PropertyTypeDescriptionDefault
selectors?Arrayable<string>Selector name strings to add to the autocomplete suggestion pool.undefined
shortcuts?Arrayable<string>Shortcut name strings to add to the autocomplete suggestion pool.undefined
extraProperties?Arrayable<string>Extra non-CSS property names to register in the autocomplete type surface (e.g. __shortcut, __layer).undefined
extraCssProperties?Arrayable<string>Extra CSS property names (including custom properties) to register in the autocomplete type surface.undefined
properties?Record<string, Arrayable<string>>Map of property names to their accepted TypeScript type strings or literal value suggestions.undefined
cssProperties?Record<string, Arrayable<string>>Map of CSS property names to their accepted value suggestions.undefined
patterns?AutocompletePatternsConfigPattern-based entries that define how to generate expanded autocomplete suggestions.undefined

Remarks:

Plugins call engine.appendAutocomplete() with an AutocompleteContribution to incrementally register new completions for selectors, shortcuts, properties, and CSS properties. Contributions are merged additively into the resolved autocomplete config.

ts
engine.appendAutocomplete({
  selectors: 'dark',
  cssProperties: { color: ['red', 'blue'] },
})


AutocompletePatternsConfig

Configuration for pattern-based autocomplete suggestions that are expanded at code generation time.

PropertyTypeDescriptionDefault
selectors?Arrayable<string>Selector pattern strings expanded into autocomplete selector suggestions.undefined
shortcuts?Arrayable<string>Shortcut pattern strings expanded into autocomplete shortcut suggestions.undefined
properties?Record<string, Arrayable<string>>Property-to-values mapping whose keys are property names and values are the allowed value patterns.undefined
cssProperties?Record<string, Arrayable<string>>CSS property-to-values mapping whose keys are CSS property names and values are the allowed value patterns.undefined

Remarks:

Patterns define template strings or records that the code-generation layer uses to produce expanded autocomplete entries. Unlike direct entries, patterns describe how to generate completions rather than listing them explicitly.

ts
const patterns: AutocompletePatternsConfig = {
  selectors: ['hover', 'focus'],
  properties: { spacing: ['sm', 'md', 'lg'] },
}


Awaitable

A value that may be synchronous or wrapped in a Promise.

Remarks:

Hook callbacks and plugin functions use this so authors can return either synchronously or asynchronously without the engine caring which.

ts
async function run(fn: () => Awaitable<string>) {
  const result = await fn() // works whether fn is sync or async
}


CSSProperty

Union of all valid CSS property name strings, including standard properties, vendor-prefixed properties, and custom properties.

Remarks:

Extracted from the keys of CSSProperties. Useful for functions that accept a property name as a parameter.

ts
function getDefault(prop: CSSProperty): string { return '' }


CSSSelector

Union of valid CSS selector strings for nested style definitions, including CSS at-rules and pseudo-selectors (prefixed with $).

Type: "@container" | "@counter-style" | "@document" | "@font-face" | "@font-feature-values" | "@font-palette-values" | "@keyframes" | "@layer" | "@media" | "@page" | "@position-try" | "@property" | "@scope" | "@starting-style" | "@supports" | "@view-transition" | "$::-moz-progress-bar" | "$::-moz-range-progress" | "$::-moz-range-thumb" | "$::-moz-range-track" | "$::-ms-browse" | "$::-ms-check" | "$::-ms-clear" | "$::-ms-expand" | "$::-ms-fill" | "$::-ms-fill-lower" | "$::-ms-fill-upper" | "$::-ms-reveal" | "$::-ms-thumb" | "$::-ms-ticks-after" | "$::-ms-ticks-before" | "$::-ms-tooltip" | "$::-ms-track" | "$::-ms-value" | "$::-webkit-progress-bar" | "$::-webkit-progress-inner-value" | "$::-webkit-progress-value" | "$::-webkit-slider-runnable-track" | "$::-webkit-slider-thumb" | "$::after" | "$::backdrop" | "$::before" | "$::checkmark" | "$::cue" | "$::cue()" | "$::cue-region" | "$::cue-region()" | "$::details-content" | "$::file-selector-button" | "$::first-letter" | "$::first-line" | "$::grammar-error" | "$::highlight()" | "$::marker" | "$::part()" | "$::picker()" | "$::picker-icon" | "$::placeholder" | "$::scroll-marker" | "$::scroll-marker-group" | "$::selection" | "$::slotted()" | "$::spelling-error" | "$::target-text" | "$::view-transition" | "$::view-transition-group()" | "$::view-transition-image-pair()" | "$::view-transition-new()" | "$::view-transition-old()" | "$:active" | "$:active-view-transition" | "$:active-view-transition-type()" | "$:any-link" | "$:autofill" | "$:blank" | "$:buffering" | "$:checked" | "$:current" | "$:default" | "$:defined" | "$:dir()" | "$:disabled" | "$:empty" | "$:enabled" | "$:first" | "$:first-child" | "$:first-of-type" | "$:focus" | "$:focus-visible" | "$:focus-within" | "$:fullscreen" | "$:future" | "$:has()" | "$:has-slotted" | "$:host" | "$:host()" | "$:host-context()" | "$:hover" | "$:in-range" | "$:indeterminate" | "$:invalid" | "$:is()" | "$:lang()" | "$:last-child" | "$:last-of-type" | "$:left" | "$:link" | "$:local-link" | "$:modal" | "$:muted" | "$:not()" | "$:nth-child()" | "$:nth-last-child()" | "$:nth-last-of-type()" | "$:nth-of-type()" | "$:only-child" | "$:only-of-type" | "$:open" | "$:optional" | "$:out-of-range" | "$:past" | "$:paused" | "$:picture-in-picture" | "$:placeholder-shown" | "$:playing" | "$:popover-open" | "$:read-only" | "$:read-write" | "$:required" | "$:right" | "$:root" | "$:scope" | "$:seeking" | "$:stalled" | "$:state()" | "$:target" | "$:target-current" | "$:target-within" | "$:user-invalid" | "$:user-valid" | "$:valid" | "$:visited" | "$:volume-locked" | "$:where()" | "$:xr-overlay"

Remarks:

In PikaCSS, pseudo-selectors are prefixed with $ instead of : to avoid collisions with CSS property names in object keys (e.g. $hover instead of :hover).

ts
const selector: CSSSelector = '$hover'
const atRule: CSSSelector = '@media (min-width: 768px)'


CSSStyleBlockBody

Intermediate structure representing a CSS rule block body with its declarations and optional nested children.

PropertyTypeDescriptionDefault
properties{ property: string, value: string }[]Ordered list of CSS property-value declaration pairs within this block.
children?CSSStyleBlocksNested CSS blocks keyed by their selector string (e.g. at-rules, pseudo-selectors).undefined

Remarks:

Used during CSS rendering to incrementally build a tree of CSS blocks before serializing them to a string. Properties are declaration pairs, and children handle nested at-rules or pseudo-selectors.

ts
const body: CSSStyleBlockBody = {
  properties: [{ property: 'color', value: 'red' }],
  children: new Map(),
}


CSSStyleBlocks

A Map from CSS selector strings to their corresponding block bodies, representing the tree structure of a CSS stylesheet.

Remarks:

The map preserves insertion order, which is important for CSS specificity and cascade ordering. Used by the rendering pipeline to accumulate blocks before serializing to CSS text.

ts
const blocks: CSSStyleBlocks = new Map()
blocks.set('.pk-a', { properties: [{ property: 'color', value: 'red' }] })


DefineAutocomplete

Identity helper that constrains the type parameter to the _Autocomplete shape, used inside PikaAugment to define the autocomplete map for a plugin.

Remarks:

Provides compile-time validation that the augmented autocomplete map has all required members.

ts
declare module '@pikacss/core' {
  interface PikaAugment {
    Autocomplete: DefineAutocomplete<{
      Selector: 'hover' | 'focus'
      Shortcut: never
      Layer: 'base'
      PropertyValue: never
      CSSPropertyValue: never
    }>
  }
}


EngineConfig

User-facing configuration object for creating a PikaCSS engine instance via createEngine().

PropertyTypeDescriptionDefault
plugins?EnginePlugin[]Engine plugins that extend the engine with additional functionality (selectors, shortcuts, variables, etc.).[]
prefix?stringString prefix prepended to every generated atomic CSS class name.'pk-'
defaultSelector?stringDefault CSS selector template for atomic rules. The % placeholder is replaced with the generated class ID.'.%'
preflights?Preflight[]Global preflight styles injected before atomic rules. Accepts raw CSS strings, definition objects, functions, or wrapped variants with layer/id metadata.[]
cssImports?string[]CSS @import statements prepended to the generated stylesheet output.[]
layers?Record<string, number>Named CSS layers and their numeric sort order. Lower numbers appear first in the @layer declaration.{ preflights: 1, utilities: 10 }
defaultPreflightsLayer?stringName of the CSS @layer used for preflight styles that do not specify an explicit layer.'preflights'
defaultUtilitiesLayer?stringName of the CSS @layer used for atomic utility styles that do not specify an explicit layer.'utilities'
autocomplete?AutocompleteConfigAutocomplete configuration for IDE integration and code generation type narrowing.{}

Remarks:

All fields are optional and fall back to sensible defaults. Plugins can further modify this config through the configureRawConfig hook before resolution.

ts
const config: EngineConfig = {
  prefix: 'pk-',
  plugins: [myPlugin()],
  layers: { base: 0, components: 5, utilities: 10 },
}


EnginePlugin

Describes an engine plugin that can hook into the PikaCSS engine lifecycle.

PropertyTypeDescriptionDefault
namestringThe unique human-readable name identifying this plugin in logs and diagnostics.
order?'pre' | 'post'Controls plugin execution order relative to other plugins.undefined (normal order)

Remarks:

Plugins implement optional hook methods corresponding to engine lifecycle events. Hooks run in plugin registration order, optionally reordered by the order property.

ts
const myPlugin: EnginePlugin = {
  name: 'my-plugin',
  configureRawConfig: (config) => ({ ...config, important: true }),
}


FromKebab

Converts a kebab-case string literal type to camelCase at the type level.

Remarks:

The inverse of ToKebab. Used to reconcile CSS-native property names back to their JavaScript equivalents during autocomplete resolution.

ts
type A = FromKebab<'background-color'> // 'backgroundColor'
type B = FromKebab<'--my-var'>         // '--my-var'


GetValue

Safely extracts the value type at key K from object type Obj, returning never when Obj is never or K is not a key of Obj.

Remarks:

Wrapping Obj in a tuple prevents distributive collapse when Obj is never.

ts
type V = GetValue<{ a: number }, 'a'> // number
type N = GetValue<{ a: number }, 'b'> // never


IsEqual

Type-level strict equality check that resolves to true when X and Y are identical types.

Remarks:

Uses the double-conditional-inference trick to detect structural and modifier differences that extends alone would miss (e.g. readonly vs mutable).

ts
type A = IsEqual<string, string>  // true
type B = IsEqual<string, number>  // false


IsNever

Evaluates to true when T is the never type, false otherwise.

Remarks:

Wrapping T in a tuple prevents distributive conditional behavior that would otherwise collapse never before the check runs.

ts
type A = IsNever<never>  // true
type B = IsNever<string> // false


Keyframes

User-facing keyframes configuration. Accepts a name-only string, a tuple shorthand, or an object form.

Remarks:

  • String: registers the name for autocomplete without defining animation frames.
  • Tuple [name, frames?, autocomplete?, pruneUnused?]: concise shorthand.
  • Object { name, frames?, autocomplete?, pruneUnused? }: explicit form.
ts
const kf: Keyframes[] = [
  'spin',
  ['fade-in', { from: { opacity: '0' }, to: { opacity: '1' } }],
]


KeyframesConfig

Configuration object for the keyframes engine option.

PropertyTypeDescriptionDefault
keyframesKeyframes[]Array of keyframes definitions to register.
pruneUnused?booleanDefault pruning policy for keyframes that are not referenced by any animation or animation-name atomic style.true

Remarks:

Passed via EngineConfig.keyframes to register @keyframes definitions at engine creation time.

ts
const config: KeyframesConfig = {
  keyframes: [['spin', { from: { transform: 'rotate(0deg)' }, to: { transform: 'rotate(360deg)' } }]],
  pruneUnused: true,
}


KeyframesProgress

Describes the progress stops of a CSS @keyframes animation.

PropertyTypeDescriptionDefault
from?ResolvedCSSPropertiesCSS properties applied at the start of the animation.undefined
to?ResolvedCSSPropertiesCSS properties applied at the end of the animation.undefined

Remarks:

Accepts the named stops from and to, plus any percentage-based stop in the form "N%". Each stop maps to a set of CSS properties applied at that point in the animation.

ts
const progress: KeyframesProgress = {
  from: { opacity: '0' },
  '50%': { opacity: '0.5' },
  to: { opacity: '1' },
}


Nullish

Represents null or undefined, used throughout the engine to express optional absence.

Remarks:

Prefer this alias over inlining null | undefined for consistency across the codebase.

ts
function process(value: string | Nullish) {
  if (value == null) return // handles both null and undefined
}


PikaAugment

Module augmentation interface that plugins extend to inject type-level information (autocomplete maps, property unions, selector unions) into the core type system.

Remarks:

Plugins declare module '@pikacss/core' { interface PikaAugment { ... } } to contribute types. At resolution time, the engine reads members such as Autocomplete, Properties, Selector, StyleDefinition, and StyleItem to narrow the public API type signatures.

ts
declare module '@pikacss/core' {
  interface PikaAugment {
    Autocomplete: DefineAutocomplete<{ Selector: 'dark' | 'light', Shortcut: never, Layer: never, PropertyValue: never, CSSPropertyValue: never }>
  }
}


Preflight

User-facing preflight input that accepts raw CSS strings, definition objects, functions, or wrapped variants with layer and id metadata.

Remarks:

The engine normalizes all Preflight variants into ResolvedPreflight via resolvePreflight(). Wrapping with { layer, preflight } scopes the output to a specific @layer; wrapping with { id, preflight } enables replacement by ID.

ts
// Raw string
const a: Preflight = '* { margin: 0; }'
// Definition object
const b: Preflight = { ':root': { fontSize: '16px' } }
// Function with layer wrapper
const c: Preflight = { layer: 'base', preflight: (engine) => '...' }


PreflightDefinition

An object-based preflight definition that maps CSS selectors to property maps, allowing nested selectors for at-rules and pseudo-elements.

Remarks:

Preflight definitions are resolved into CSS text at render time. Keys can be any valid CSS selector string or a custom selector name registered via the selectors plugin. Values are CSS property maps or further nested PreflightDefinition objects.

ts
const reset: PreflightDefinition = {
  '*, *::before, *::after': { boxSizing: 'border-box', margin: '0' },
  ':root': { fontSize: '16px' },
}


PreflightFn

A function that receives the engine instance and formatting flag, returning CSS text or a PreflightDefinition object.

Remarks:

Preflight functions are invoked at render time, after all atomic styles have been resolved. This allows them to inspect the engine store (e.g. which variables or keyframes are actually used) and prune unused declarations.

ts
const fn: PreflightFn = (engine, isFormatted) => {
  return { ':root': { '--color': 'red' } }
}


Properties

The full property map accepted in pika() style definitions, combining standard CSS (camelCase and hyphen-case), custom properties, plugin-injected CSS properties, and extra non-CSS properties.

Remarks:

This interface merges five sub-property types: camelCase CSS, hyphen-case CSS, --* custom properties, extra CSS properties from plugins, and extra non-CSS properties (like __shortcut, __layer, __important). Each property value can be a plain string, a [value, fallback[]] tuple, or nullish.

ts
const props: Properties = {
  color: 'red',
  'font-size': '16px',
  '--my-color': 'blue',
}


PropertyValue

A CSS property value that supports single values, [value, fallback[]] tuples for multi-value fallbacks, or nullish to unset/remove the property.

Remarks:

When passed as a tuple, the first element is the primary value and the second is an array of fallback values rendered before it (for CSS fallback ordering). Passing null or undefined removes the property during optimization.

ts
const single: PropertyValue<string> = 'red'
const withFallback: PropertyValue<string> = ['oklch(0.5 0.2 240)', ['blue']]
const remove: PropertyValue<string> = null


ResolvedLayerName

Union of known CSS @layer names, falling back to UnionString when no plugin augments the Layer dimension.

Remarks:

When plugins define layer names via DefineAutocomplete, this type narrows to those names while still accepting arbitrary strings. Used in the __layer property autocomplete.

ts
type LN = ResolvedLayerName // 'base' | 'components' | ... or UnionString


ResolvedPreflight

Normalized preflight entry after resolution, with an optional layer scope and a stable identifier for deduplication.

PropertyTypeDescriptionDefault
layer?stringCSS @layer name that wraps this preflight output. When omitted, the preflight falls into the default preflights layer.undefined
id?stringStable identifier for this preflight, used for deduplication and replacement by plugins.undefined
fnPreflightFnThe preflight function invoked at render time to produce CSS text or a definition object.

Remarks:

Produced by resolvePreflight() which peels off WithLayer and WithId wrappers from the user-facing Preflight input. The id allows plugins to identify and replace specific preflights, and layer controls which @layer block the output lands in.

ts
const resolved: ResolvedPreflight = {
  layer: 'base',
  id: 'my-reset',
  fn: (engine, isFormatted) => '* { margin: 0; }',
}


ResolveFrom

Conditionally resolves T[Key] when the key exists and its value extends I; otherwise falls back to Fallback.

Remarks:

Used extensively to resolve augmented types from PikaAugment, falling back to internal defaults when no augmentation is provided.

ts
type R = ResolveFrom<{ Foo: string }, 'Foo', string, 'default'> // string
type D = ResolveFrom<{}, 'Foo', string, 'default'>              // 'default'


Selector

User-facing selector rule configuration. Accepts string redirects, tuple shorthands, or object forms.

Remarks:

  • String: a redirect to another named selector.
  • Tuple [string, value]: a static rule mapping an exact selector name to one or more resolved CSS selectors.
  • Tuple [RegExp, fn, autocomplete?]: a dynamic rule matching a pattern and lazily computing resolved CSS selectors.
  • Object { selector, value, autocomplete? }: an explicit form of either static or dynamic rule.
ts
const rules: Selector[] = [
  ['hover', '&:hover'],
  [/^media-(\d+)$/, m => `@media (min-width: ${m[1]}px)`, 'media-${breakpoint}'],
]


SelectorsConfig

Configuration object for the selectors engine option.

PropertyTypeDescriptionDefault
selectorsSelector[]Array of selector rule definitions to register.

Remarks:

Passed via EngineConfig.selectors to register selector rules at engine creation time.

ts
const config: SelectorsConfig = {
  selectors: [['hover', '&:hover'], ['focus', '&:focus']],
}


Shortcut

User-facing shortcut rule configuration. Accepts string redirects, tuple shorthands, or object forms.

Remarks:

Shortcuts expand a single name into one or more style items, allowing reusable composition of atomic styles. The configuration shapes mirror Selector: string redirect, [string, value] static, [RegExp, fn, autocomplete?] dynamic, or object equivalents.

ts
const rules: Shortcut[] = [
  ['btn', [{ padding: '0.5rem 1rem' }, { borderRadius: '0.25rem' }]],
  [/^btn-(.+)$/, m => ({ backgroundColor: m[1] }), 'btn-${color}'],
]


ShortcutsConfig

Configuration object for the shortcuts engine option.

PropertyTypeDescriptionDefault
shortcutsShortcut[]Array of shortcut rule definitions to register.

Remarks:

Passed via EngineConfig.shortcuts to register shortcut rules at engine creation time.

ts
const config: ShortcutsConfig = {
  shortcuts: [['btn', { padding: '0.5rem 1rem' }]],
}


Simplify

Flattens an intersection type into a single object type for improved readability in IDE tooltips.

Remarks:

Mapped types re-enumerate all keys so the resulting hover preview shows a flat { ... } shape instead of A & B & C.

ts
type Merged = Simplify<{ a: 1 } & { b: 2 }> // { a: 1; b: 2 }


StyleDefinition

A style definition passed to pika(), representing either a flat CSS property map or a nested selector-keyed structure (or both).

Remarks:

This is the primary input type for the pika() function. A flat Properties map defines atomic styles directly. A StyleDefinitionMap nests properties under selector keys for conditional styling.

ts
// Flat
const flat: StyleDefinition = { color: 'red', fontSize: '16px' }
// Nested
const nested: StyleDefinition = { '$hover': { color: 'blue' } }


StyleDefinitionMap

A nested style definition where keys are selector strings and values are property values, property maps, nested definitions, or arrays of style items.

Remarks:

Enables nesting selectors within a style definition to express pseudo-classes, media queries, and other combinators. The engine recursively walks this structure during extraction.

ts
const map: StyleDefinitionMap = {
  '$hover': { color: 'blue' },
  '@media (min-width: 768px)': { fontSize: '18px' },
}


StyleItem

An individual item in a style item list: either a string reference (shortcut name or raw class), a style definition object, or a combination of shortcut union strings.

Remarks:

When pika() receives an array of style items, string items are resolved via the shortcuts resolver while object items are treated as inline style definitions. Unresolved strings are passed through as class names.

ts
const item: StyleItem = 'btn-primary'      // shortcut reference
const itemDef: StyleItem = { color: 'red' } // inline style


ToKebab

Converts a camelCase or PascalCase string literal type to kebab-case at the type level.

Remarks:

Used to map JavaScript-style property names to their CSS kebab-case equivalents during style extraction and rendering.

ts
type A = ToKebab<'backgroundColor'> // 'background-color'
type B = ToKebab<'--my-var'>        // '--my-var'


UnionString

Branded string type that preserves literal union autocompletion while still accepting arbitrary strings.

Remarks:

TypeScript narrows string to only known literals when a union is used. Intersecting with {} keeps the union suggestions in IDE autocomplete without rejecting unknown strings at the type level.

ts
type Color = 'red' | 'blue' | UnionString
const c: Color = 'red'    // autocomplete suggests 'red' | 'blue'
const d: Color = 'green'  // still valid


UnionToIntersection

Converts a union type into an intersection of all its members.

Remarks:

Leverages contra-variant inference on function parameter positions. Useful internally for merging augmented module declarations into a single combined type.

ts
type U = { a: 1 } | { b: 2 }
type I = UnionToIntersection<U> // { a: 1 } & { b: 2 }


Variable

A CSS variable value, either a plain CSS value string/number or a VariableObject with metadata.

Remarks:

Use the short form for simple values. Use VariableObject when semantic typing, autocomplete control, or pruning opt-out is needed.

ts
const simple: Variable = '#fff'
const rich: Variable = { value: '#fff', semanticType: 'color' }


VariableAutocomplete

Controls how a CSS variable participates in the autocomplete type surface.

PropertyTypeDescriptionDefault
asValueOf?Arrayable<UnionString | '*' | '-' | ResolvedCSSProperty>CSS properties (or '*' for all, '-' for none) where this variable should appear as a var() value suggestion.undefined (inferred from semanticType, or '*' if neither is set)
asProperty?booleanWhether this variable name should appear as an extra CSS property in the autocomplete surface.true

Remarks:

When asValueOf includes '*', the variable appears as a value option for every CSS property. Use '-' to suppress value-of suggestions entirely.

ts
const auto: VariableAutocomplete = { asValueOf: ['color', 'background-color'], asProperty: true }


VariableObject

Expanded object form of a CSS variable definition with optional metadata.

PropertyTypeDescriptionDefault
value?ResolvedCSSProperties[--${string}]The CSS value assigned to this variable.undefined (variable is registered for autocomplete only, no value emitted)
semanticType?Arrayable<VariableSemanticType>Semantic family labels controlling which CSS properties this variable auto-completes as a value for.undefined (all properties when autocomplete.asValueOf is also unset)
autocomplete?VariableAutocompleteFine-grained control over this variable's autocomplete behaviour.undefined (inferred from semanticType)
pruneUnused?booleanWhether this variable should be pruned from the output when it is not referenced by any atomic style or preflight.true (inherits from VariablesConfig.pruneUnused)

Remarks:

Use this form when the variable needs semantic typing, custom autocomplete behaviour, or opt-out of unused-pruning.

ts
const v: VariableObject = {
  value: '#3b82f6',
  semanticType: 'color',
  autocomplete: { asValueOf: '*' },
  pruneUnused: false,
}


VariablesConfig

Configuration object for the variables engine option.

PropertyTypeDescriptionDefault
variablesArrayable<VariablesDefinition>One or more variable definition objects to register.
pruneUnused?booleanDefault pruning policy for variables that are not referenced by any atomic style or preflight.true
safeList?(--${string} & {})[]Variable names that should always be emitted regardless of usage.[]

Remarks:

Passed via EngineConfig.variables to define CSS custom properties, control pruning, and specify a safe list.

ts
const config: VariablesConfig = {
  variables: { '--color-primary': '#3b82f6' },
  pruneUnused: true,
  safeList: ['--color-primary'],
}


VariablesDefinition

A nested record mapping CSS variable names (--*) and optional selector scopes to variable definitions.

Remarks:

Non--- keys are treated as selector scopes (e.g. '.dark', '@media ...') that nest the enclosed variables under that selector. Keys starting with -- define actual CSS variables.

ts
const def: VariablesDefinition = {
  '--color-primary': '#3b82f6',
  '.dark': { '--color-primary': '#60a5fa' },
}


VariableSemanticType

Semantic type label for a CSS variable, used to derive which CSS properties it can auto-complete as a value for.

Remarks:

Accepts any known VariableSemanticFamily (e.g. 'color', 'length') or an arbitrary string. Known families are expanded to their associated CSS property list at registration time.

ts
const type: VariableSemanticType = 'color'


Module augmentations

Engine (@pikacss/core)

PropertyTypeDescriptionDefault
selectors{ resolver: SelectorResolver add: (...list: Selector[]) => void }Runtime selector management: resolver instance and add method for registering selectors after engine creation.
shortcuts{ resolver: ShortcutResolver add: (...list: Shortcut[]) => void }Runtime shortcut management: resolver instance and add method for registering shortcuts after engine creation.
variables{ store: Map<string, ResolvedVariable[]> add: (variables: VariablesDefinition) => void }Runtime variable management: resolved variable store and add method for registering variables after engine creation.
keyframes{ store: Map<string, ResolvedKeyframesConfig> add: (...list: Keyframes[]) => void }Runtime keyframes management: resolved keyframes store and add method for registering keyframes after engine creation.

EngineConfig (@pikacss/core)

PropertyTypeDescriptionDefault
selectors?SelectorsConfigSelector rules configuration.undefined
shortcuts?ShortcutsConfigShortcut rules configuration.undefined
variables?VariablesConfigCSS custom properties (variables) configuration.undefined
important?ImportantConfigControls the !important modifier on generated CSS declarations.undefined (no !important appended by default)
keyframes?KeyframesConfigKeyframes definitions configuration.undefined