API Reference
createFormEngine
interface CreateFormEngineOptions<TElements, TRecipes, TActions, TLayout> {
elements?: TElements;
recipes?: TRecipes;
actions?: TActions;
/** Custom validation rules, after the built-in ones and the validations elements declare; the last `$type` wins. */
validations?: readonly ValidationRegistrationConstraint[];
/** Extra schema metadata entries; copied, with every registration's entry written over it. */
catalog?: SchemaMetadataCatalog;
/**
* The layout theme: a compiled theme from `createLayoutTheme`, or inline
* `{ grid, appearance }` options. `grid` holds breakpoint thresholds, gap tokens and the
* default min column width; `appearance` is the list of axes built with `defineAxis`
* (default `builtInAxes`: `size` and `surface`). The last axis of a `$type` wins.
*/
layout?: TLayout;
/** Turns an issue into the text to show: the one formatter both renderers read. Inherited by `extend()`. */
formatIssue?: FormIssueFormatter;
/** The request function every request the engine makes goes through; the global `fetch` by default. Inherited by `extend()`. */
fetch?: FormFetch;
/** Where a CSRF token comes from, from `csrf.fromMeta`, `csrf.fromCookie` or `csrf.custom`. Off unless set. Inherited by `extend()`. */
csrf?: CsrfPolicy;
}
function createFormEngine<
const TElements extends readonly ElementRegistrationConstraint[] = readonly [],
const TRecipes extends readonly RecipeRegistrationConstraint[] = readonly [],
const TActions extends readonly ActionRegistrationConstraint[] = readonly [],
const TLayout extends LayoutInput = Record<never, never>,
>(
options?: CreateFormEngineOptions<TElements, TRecipes, TActions, TLayout>,
): FormEngineFromOptions<TElements, TRecipes, TActions, TLayout>;FormEngineFromOptions is the FormEngine typed from the merged registration
lists. layout is accepted by createFormEngine and by
createRadiantFormEngine, which forwards it. Pass one theme compiled with
createLayoutTheme (from @schema-engine/layout) to several engines and they carry the same
data-se-theme and the same stylesheet content (React hoists one element; Radiant inlines an identical
copy per form, by design); inline options compile a theme of the engine's own.
engine.extend() does not take layout; extended engines inherit the source
engine's layout theme, which engine.getLayout() returns (id, grid, axes, appearance, css).
The grid and appearance engine options no longer exist.
Each array is structurally constrained: $type, a Standard Schema
(~standard.validate), and the registration's render/execute function.
Duplicate $type values follow last-wins at runtime. Tuples and inline arrays
use last-wins typing; open T[] values use a union of configs for the same
$type. Spread shared registration barrels and append overrides when needed.
formatIssue is the engine's issue formatter, engine.getIssueFormatter(). engine.fetch is the
request function with the CSRF policy applied, and engine.getCsrf() returns the policy.
engine.getValidationRegistry() is the registry a state container is made with.
engine.getSchemaCatalog() returns the metadata the JSON Schema export reads (title, description and category by id, such as
element:input), not a list of what is registered. Read what is registered with engine.getAllElements(),
getAllRecipes(), getAllActions() and engine.getValidationRegistry() (Registries).
validations takes validation registrations ($type, schema, metadata, category, handler)
and is not typed per engine: field rules keep their type string. See
Custom Validations.
Authors supply schema input. After validation, render functions receive
schema output. Register elements with defineInput / defineStatic so the
schema input/output relationship is preserved.
defineInput / defineStatic
import { defineInput, elementChildrenSchema } from '@schema-engine/forms';
export const FieldSetRegistration = defineInput({
$type: 'fieldSet',
schema: FieldSetConfigSchema,
metadata: { name: 'FieldSet', category: 'input' },
render: FormFieldSet,
});defineInput keeps the concrete schema type. Container schemas should use
elementChildrenSchema for elements; the engine validates those children
against its registrations. The render function then receives frozen,
normalized children — not authoring JSON.
FormEngine
FormEngine retrieves registered elements, recipes, and actions; validates
form configuration; and generates JSON Schema and authoring catalog artifacts.
defineForm and validateForm return NormalizedFormConfig. Use
validateElement for a standalone field that is not already inside a form.
engine.getElement('text');
engine.getRecipe('card');
engine.getAllRecipes();
engine.defineForm(config);
engine.validateForm(json);
engine.safeValidateForm(json);
engine.validateElement(field);
engine.extend({ actions: [extraAction] });
engine.getFormConfigStandardSchema();
engine.describeViewCatalog();validateForm throws a FormValidationError when the form is invalid.
safeValidateForm runs the same validation and returns a result instead:
type FormValidationIssue = {
message: string;
path: ReadonlyArray<PropertyKey>; // ['steps', 0, 'elements', 2, 'grid', 'width']
code?: string; // the schema's code on a schema issue, such as 'too_small'
params?: Readonly<Record<string, unknown>>; // its details, such as { origin: 'string', minimum: 3, inclusive: true }
};
type FormValidationResult<T> = { success: true; data: T } | { success: false; issues: FormValidationIssue[] };params holds the details a code reports and only those that are set: values, expected, origin, minimum, maximum, inclusive, format, pattern and keys. error.issues on a FormValidationError has the same shape. See
Form configuration errors
for the paths and a copy-pasteable example.
JSON Schema conversion is backed by Zod Mini for first-party schemas. Use
io: 'input' for authoring input (where defaulted fields are optional) or
io: 'output' for parsed output. Every generator defaults to 'input', since the export describes
what authors write. An element whose schema pipes a transform (Radiant's input-otp) has no
JSON Schema for its output side, so io: 'output' throws for an engine that registers one.
The collection also holds the validation-rule entry: the union of every registered rule, which the form config schema defines once and each element's rules refers to.
engine.generateJSONSchemaCollection(); // io: 'input'
engine.generateFormConfigSchema(); // io: 'input'
engine.generateActionConfigSchema('submit', { io: 'output' });In these schemas an appearance pick is closed over the axes its owner declares. The form and
each step list every axis of the layout theme; an element lists the axes in its appearanceAxes
and a recipe slot the axes in the recipe's appearanceAxes, each as an enum of the axis's
values. Any other axis is rejected, as it is by validateForm. The export checks elements, the
children of a fieldset or an array row (typed as a union of every element's schema) and the recipe
slots. It does not check the appearance of an element whose schema is lazy; validateForm does.
getFormConfigStandardSchema() and getActionConfigStandardSchema() expose
the same input/output converters through the Standard JSON Schema contract.
Consumer schemas from other Standard Schema providers remain fully supported
for runtime validation. Their provider-specific JSON Schema is not introspected
in this iteration; mixed form config exports retain the registered $type
envelope for those schemas.
createFormRuntime
One framework-free instance per rendered form, shared by React and Radiant. It builds the form's state container and
owns the submission, the wizard's steps and navigation, form_mount and form_change, and every action dispatch. A
renderer supplies only what it alone can do, as the host. The Wizard and runtime guide has the
options, the host, the navigation rules and a run of every command.
import { createFormRuntime } from '@schema-engine/forms';
const runtime = createFormRuntime({ engine, config, host: { focus: (paths) => {} }, onSubmit });
const unmount = runtime.mount(); // form_mount once, and the change watch; the cleanup revokes anything in flight
runtime.container; // the form state
runtime.getSnapshot(); // { submission: { status, failures, submitCount }, current, navigating, steps }
runtime.subscribe(listener);
await runtime.next();
await runtime.back();
await runtime.goTo('payment');
await runtime.submit();
runtime.clearSubmission();Every command returns one string of a single union; why a submission failed is read from
snapshot.submission.failures, never from the return value.
type FormRuntimeOutcome = 'moved' | 'submitted' | 'failed' | 'invalid' | 'overtaken' | 'refused' | 'busy' | 'cancelled';
type NavigationOutcome = Extract<
FormRuntimeOutcome,
'moved' | 'failed' | 'invalid' | 'overtaken' | 'refused' | 'busy' | 'cancelled'
>;
type SubmitOutcome = FormRuntimeOutcome;
interface FormStepState {
id: string;
skipped: boolean; // the step's constraints hide it
visited: boolean;
complete: boolean; // next() validated it and moved on
invalid: boolean; // an error is recorded at one of its fields
reachable: boolean; // goTo can move there
}- One lock covers navigation and submission: a command made while another runs is
'busy', and a reset or an unmount revokes a command whose values were not yet captured, which is'cancelled'and writes nothing. container.reset()is the only reset. The container snapshot'sgenerationgoes up with it, and the runtime then returns the submission to idle with a count of 0 and the steps to the first, firing no step trigger. A submission whose values were already captured is committed: it runs to its end and publishes its outcome after the reset.next()validates the current step and moves to the next active step ('refused'on the last);back()never validates;goTo(id)refuses a skipped or unknown step, always allows going back and, going forward, follows the form'snavigation('linear': visited steps only, validating every step on the way;'free': any active step).submit()before the last active step acts asnext(). On the last it validates every active step, runs the actions andonSubmit, and on'invalid'moves to the first step with an error and focuses it. A server error thatonSubmitsets on an earlier step moves there too.- A step takes
constraintsrestricted toshowandhide, on non-row fields of earlier steps; a step they hide is skipped, and its fields take no part in validation or in the submitted values.
State container, server errors and CSRF
| Entry | Exports | Guide |
|---|---|---|
@schema-engine/forms/state-container | createFormStateContainer, the FormStateContainer, FormStateSnapshot and FormIssueFormatter types, selectFieldState, selectValue, toFieldArrayValue, toHydration, FORM_ROOT and FormValidationFailure | Form state |
@schema-engine/forms/server-errors | fromProblemDetails, fromJsonApiErrors and ServerErrorsInputError | Server errors |
@schema-engine/forms/csrf | csrf (fromMeta, fromCookie, custom), csrfFieldFor and the CsrfPolicy type | CSRF |
@schema-engine/forms/testing | formStateContainerConformance | Form state |
RecipeRegistration
interface RecipeRegistration<TType, TSchema, TRender = unknown> {
$type: TType;
kind: 'single-step' | 'wizard';
slots: Array<'shell' | 'header' | 'progress' | 'actions'>;
schema: TSchema;
metadata: RecipeMetadata;
/** Slot config applied beneath the view's own slot config. */
slotDefaults?: Partial<Record<'shell' | 'header' | 'progress' | 'actions', Record<string, unknown>>>;
/** Appearance axes each slot supports, for example `{ shell: ['size', 'surface'] }`. */
appearanceAxes?: Partial<Record<'shell' | 'header' | 'progress' | 'actions', readonly string[]>>;
render: TRender;
}The recipe protocol (the slots, the kinds, the rules that check them) is declared once per domain with
defineRecipeProtocol from @schema-engine/layout; forms declares shell | header | progress | actions and
single-step | wizard. See Recipes.
See Form engine setup for adapter factories and composition rules.