Validators & config merging

The Zod schemas, what validation checks, and the difference between validateThemeConfig, mergeThemeConfig, mergeWithDefaults and deepMerge.

Cortex validates every theme config through Zod before generating tokens. The schemas and helper functions below are exported so you can reuse the same gates in playgrounds, CLI tools, MCP servers, or your own pipelines.

ts
import {
  ThemeConfigSchema,
  ThemeSettingsSchema,
  SeedsSchema,
  LayoutConfigSchema,
  InteractionConfigSchema,
  validateThemeConfig,
  mergeThemeConfig,
  defaultThemeConfig,
  type ThemeConfig,
  type ThemeSettings,
  type Seeds,
} from "@flexpixels/cortex";

Schemas

SchemaCovers
ThemeConfigSchemaTop-level config — composes every other schema.
ThemeSettingsSchemasettings.prefix, accessibility (AA | AAA), contrastAlgorithm (apca | wcag2), schemes (both | light | dark).
SeedsSchemaprimary/secondary/neutral (required hex); success/danger/warning/info (optional hex, generated when null or absent); surface (optional dark-mode anchor).
LayoutConfigSchemabreakpoints, containerMaxWidths, columns, gutter, section.{paddingX,paddingY,paddingXCompact,paddingYCompact,gap}, stack.gap, gaps.{xs..xl}.
InteractionConfigSchemaopacityDisabled, durations.{xfast,fast,normal,slow,xslow}, animationDurations, easings, states, spring, stagger, focusRing.{width,offset,color}, scaleActive.

They are Zod 4 schemas, so they have .parse() (throws on failure) and .safeParse() (returns a result object) — handy when you want to show field-level errors in a UI instead of stopping the build. ThemeConfigSchema fills in defaults for every field except the three brand seeds, which it requires; it does not merge with defaultThemeConfig or apply scenarios (validateThemeConfig applies them).

ts
const result = ThemeConfigSchema.safeParse(userInput);
if (!result.success) {
  console.error(result.error.issues); // [{ path, message, code, ... }]
} else {
  const config = result.data; // typed ThemeConfig
}

validateThemeConfig(input)

ts
function validateThemeConfig(config: unknown): ThemeConfig;

ThemeConfigSchema.parse(input) plus the scenario bundles: a typography.scenario / elevation.scenario the input names fills the fields it leaves out (a bare ThemeConfigSchema.parse does not). Throws a ZodError when validation fails — wrap in try/catch (or use safeParse) when you need to recover gracefully.

ts
import { validateThemeConfig } from "@flexpixels/cortex";

try {
  const config = validateThemeConfig(rawInput);
} catch (err) {
  // err is a ZodError; inspect err.issues for path + message
}

The result is a complete ThemeConfig: Zod fills in every nested default. The input still needs seeds.primary, seeds.secondary and seeds.neutral, and a typography.scenario / elevation.scenario it names fills the fields of its bundle the input leaves out, so ThemeEngine and every generator render the scenario; use mergeThemeConfig when you start from a config without seeds.

What validation checks

A config validation accepts is one every generator accepts. Each problem is a Zod issue with the field’s path:

  • Unknown keys are errors (seeds.primay), so a typo cannot fall back to a default. A top-level $schema is allowed for editors.
  • Numbers in range: opacities and state layers in 0–1, durations ≥ 0, layout.columns a whole number ≥ 1, font weights 1–1000, typography.fluid.maxViewport above minViewport, a spring that settles within 5 s, and no number past ±1,000,000. A scale is written smallest first: typography.scale, radius.scale, border.scale and the brutalism offsetMultipliers must not go down. A range has its ends the right way round: a per-role fluid.min at most its max, a variable axis [min, max, default] with the default inside. Font metrics have a positive unitsPerEm and a capHeight no higher than the ascent.
  • CSS names: settings.prefix and record keys (breakpoints, letter spacings, easings, type-style roles) are letters, digits and single hyphens.
  • Safe CSS values: font stacks, a custom gradient, scrollbar colours and other free text cannot end their declaration — no ;, {, }, comments, or unbalanced quotes, ( or [, and a url() must quote its address. A letter spacing is a length in em, rem or px, 0 or normal; typography.comfort.lineLength and minSize are CSS lengths. Colour fields may use {primary.9}-style references, and the scrollbar colours must be such a reference or a CSS colour.
  • Rules across fields: typography.base is 16; a strict grid wants even sizes; type styles name steps, weights and letter spacings that exist; size tiers and typography.fluid.roles name text roles that exist; a layout.containerMaxWidths key names a breakpoint; frosted glass keeps glassOpacity at 0.4 or more whatever the elevation style, since the glass tokens are emitted with every style (glass: "clear" lifts that floor).

The parsed config shares no objects with other parses, and defaultThemeConfig is frozen.

mergeThemeConfig(partial)

ts
function mergeThemeConfig(
  partial: DeepPartial<ThemeConfig> | null | undefined,
  base?: ThemeConfig, // defaultThemeConfig
): ThemeConfig;

The right entry point when you have a partial config and want a fully resolved one. Pipeline:

  1. Apply typography.scenario defaults on top of base (defaultThemeConfig unless you pass one), if the partial names a scenario the base does not already have.
  2. Apply elevation.scenario defaults the same way. A new elevation scenario starts its fields over (style, shadowIntensity, tintChroma, neumorphicDepth, glassOpacity, brutalismOffset), so the previous bundle’s values do not ride along.
  3. Deep-merge your partial on top.
  4. Re-validate through ThemeConfigSchema.parse(...).

It works in the browser and in Node. Use it wherever you start from a partial object (a playground, a request body, a test fixture). null or undefined gives the base; anything else that is not an object (a string, an array) is a ZodError.

Objects merge key by key and arrays replace, with one exception: layout.breakpoints is a named set and replaces whole, so a config that names its breakpoints gets those and no others, and the containerMaxWidths of the breakpoints it drops go with them (containerMaxWidths itself merges key by key). null takes a key out: a named entry is removed ({ typography: { letterSpacings: { huge: null } } }) and a field returns to its default ({ radius: { base: null } }); for a seed, null is the value “derive this one”. { elevation: { scenario: null } } and { typography: { scenario: null } } remove the scenario and return the fields its bundle set to their defaults, under anything the same change states. A null on a key that does not exist ({ radius: { bsae: null } }) is an error, like any unknown key.

Merging and validating read a config differently

mergeThemeConfig and ThemeEngine.updateConfig take a change: what you state is laid over what is there, so a named set (letterSpacings, typeStyles) keeps its other entries. validateThemeConfig, new ThemeEngine, setConfig and every generator take a whole config: a named set you state is the whole set, and the entries you leave out are gone. { seeds, typography: { letterSpacings: { huge: "0.2em" } } } is therefore valid as a change and an error as a whole config (the default type styles name spacings it no longer has). Two things are the same through both: a scenario fills the fields you leave out, nested ones included, and elevation.levelAliases always keeps rest, lifted, overlay and modal.

Both apply the same guards before anything else, and report them as a ZodError: a config nested more than 32 levels deep or holding more than 100,000 values, a Map, Set, Date or other non-plain object where a section belongs, and a key JavaScript objects reserve (constructor, prototype, __proto__) wherever it appears.

ts
import { mergeThemeConfig, generateFullThemeCSS } from "@flexpixels/cortex";

const config = mergeThemeConfig({
  seeds: { primary: "#4f46e5", secondary: "#c026d3", neutral: "#94a3b8" },
  typography: { scenario: "editorial" },
});

const css = generateFullThemeCSS(config);

mergeWithDefaults(partial) and the Node-only loader

ts
function mergeWithDefaults(partial: DeepPartial<ThemeConfig>): ThemeConfig;

Lives in the Node-only config loader (@flexpixels/cortex root export — not in the /browser entry). It is mergeThemeConfig under its older name: scenarios, deep merge, validation.

Use it (and its companions loadUserConfig / loadConfigFromPath) from build scripts. See Config loader for the full pipeline.

deepMerge(target, source)

The merge mergeThemeConfig uses, exported for your own config layering. Plain objects merge key by key; arrays and other values from source replace the target’s; undefined in source changes nothing. The result shares no objects with either input. It does not validate.

ts
import { deepMerge, defaultThemeConfig, validateThemeConfig } from "@flexpixels/cortex";

const config = validateThemeConfig(deepMerge(defaultThemeConfig, { radius: { base: 8 } }));

defaultThemeConfig

The complete ThemeConfig Zod produces from the default seeds (primary: "#4f46e5", secondary: "#c026d3", neutral: "#94a3b8", and null for the four semantic roles). It is deep-frozen: copy it before changing anything (structuredClone(defaultThemeConfig)). Useful as:

  • The starting point for mergeThemeConfig({ ...overrides }).
  • A structural reference when exploring the schema interactively.
  • The fallback ThemeEngine uses when constructed without arguments.

Type re-exports

ThemeConfig, ThemeSettings, Seeds, GradientPreset, LineHeightFormula, TypeStyleDef, ThemeWarning, WarningSeverity, FontMetrics, and ColorRole are all exported types from the root entry — z.infer<typeof ThemeConfigSchema> is exposed as a named type so you don’t have to recompute it. DeepPartial<ThemeConfig>, the partial-input type for mergeThemeConfig / mergeWithDefaults, is exported from both entries.