Skip to content

Runtime API

mica/runtime is the only supported import for hosts. It never imports editor code. mica/runtime.css is its stylesheet: every rule targets the element PackSurface renders or a .ui-* class inside it, and reads only the active theme’s --ui-* tokens. mica/editor exists as a source-only entry point that exports the designer’s App; it has no embedding API yet.

Export What it is
JSONUIProvider json-render’s provider: registry, store, handlers, directives. Reads handlers once, at mount.
Renderer json-render’s renderer: spec, registry.
useStateStore json-render’s hook for the store inside the provider.
createStateStore(initial) A simple in-memory store with get, set, update, getSnapshot, subscribe.
registerActionObserver({ onDispatch?, onSettle? }) Page-wide action observer; returns an unsubscribe function.
PackSurface A div carrying the pack’s default theme, or the theme prop’s (pack, optional theme, plus any div props). Render the document inside it; React Aria overlays its controls open portal into it, so they keep the tokens.
PageProvider spec, optional activePageKey. Selects the page by key; no key means the first page. Also resolves $label reads against the document’s Choices; outside it they show nothing.
goToPageHandler(spec, onNavigate?) The goToPage handler: validates the target and calls onNavigate(pageKey).
Types ComponentRegistry, Spec, StateStore, UIElement, PackTokens (a pack’s default theme tokens: ThemeTokens)
Export What it is
createListHandlers({ document, store }) { addRow, removeRow }, the handlers for a document’s local list actions, writing to store.
MAX_LIST_ROWS 500 — the most rows a list may hold, in document state and after an addRow.
MAX_ROW_SIZE 16384 — the most JSON characters one added row may take, key included, once its reads are resolved.
Type ListHandlers

Register the list handlers beside the others; they need no host code:

const lists = createListHandlers({ document, store });
const handlers = { ...lists, ...objectHandlers, goToPage: goToPageHandler(document, navigate) };

A host that leaves them out gets json-render’s No handler registered warning, and addRow and removeRow do nothing. The designer’s preview registers them.

Export What it is
createValidateHandler({ document, store, activePageKey }) { validate }, the handler for a document’s validate action. activePageKey is a live getter that must return the same key the host gives PageProvider (JSONUIProvider copies handlers at mount). A host that never navigates passes () => undefined (first page). It checks ruled controls visible on that page, writes each message to that control’s error $state path, and rejects if any of those fail. Hidden controls and other pages are left untouched; with none visible it succeeds.
preflightLocalActions(document, handlers) { ok, issues } — not-implemented when the document dispatches validate and handlers.validate is missing. Unlike addRow/removeRow, an unregistered validate must not fail open: later actions in the same event would run.
Types ValidateHandler, ValidateHandlerOptions

Register it beside the list handlers. Call preflightLocalActions with the same handlers object you pass to JSONUIProvider. The designer’s preview, the docs’ live examples and the mock host register the handler and run that preflight. In React, read the page from a ref so the getter stays live; see the embed guide.

const lists = createListHandlers({ document, store });
const validate = createValidateHandler({
document,
store,
activePageKey: () => pageRef.current, // same key as PageProvider
});
const handlers = { ...lists, ...validate, ...objectHandlers, goToPage: goToPageHandler(document, navigate) };
const local = preflightLocalActions(document, handlers);
Export What it is
micaDirectives Mica’s directives for JSONUIProvider’s directives prop, formatting in the browser’s locale: $format, the display-only calculation $calc, and $expr.
createMicaDirectives({ locale? }) The same directives formatting in locale, a BCP 47 tag or a list of them, best first. Throws on a malformed tag.
Type MicaDirectiveOptions

Pass them beside the handlers, created once (json-render rebuilds its directive registry whenever the array changes):

const directives = createMicaDirectives({ locale: "en-GB" }); // or micaDirectives
<JSONUIProvider registry={pack.runtimeRegistry} store={store} handlers={handlers} directives={directives}>

A host that leaves them out renders each $format, $calc or $expr value as raw JSON. A host that already registers them needs no change for $calc. Boolean $expr in visible and $cond is evaluated by Renderer from this entry. Render with Renderer from mica/runtime; json-render’s own Renderer treats a $expr condition as always true, so every $cond $expr stays on and every visible $expr is shown. visible is evaluated only by Mica’s registry wrapper. The designer’s canvas and preview register micaDirectives.

Export What it is
I18nProvider React Aria’s locale provider (locale prop, a BCP 47 tag). The date controls and the Slider read their locale from the nearest one, or the browser’s without it. Import it from mica/runtime, not from your own react-aria-components: the locale travels through React Aria’s context, and a provider from a separate copy of that package sets a context Mica’s controls never read.

A date’s parts follow the locale (day before month in "en-GB"), and so do the calendar, a Slider’s number and React Aria’s own validation messages; the stored value never does — a date is always "YYYY-MM-DD". Wrap the surface once, with the locale you give createMicaDirectives:

<I18nProvider locale="en-GB">
<PackSurface pack={pack}>
<Renderer spec={document} registry={pack.runtimeRegistry} />
</PackSurface>
</I18nProvider>

DateField and DateRange load their visuals — React Aria’s date parts and calendars, @internationalized/date and their translated strings — from a separate chunk the first time one renders; until it arrives the control shows its label over an empty field. A bundler that splits dynamic imports (Vite, Rollup, webpack, esbuild) does this with no setup, so a host whose documents show no date control never downloads them. Measured in examples/mock-host’s Vite build, that chunk is about 45 KB gzipped.

React Aria ships its strings for more than 30 locales, and most of them sit in that chunk. A host that supports fewer can strip the rest at build time with React Aria’s own plugin, @react-aria/optimize-locales-plugin, listing the locales it serves; with English alone the date chunk drops to about 32 KB:

vite.config.ts
import optimizeLocales from "@react-aria/optimize-locales-plugin";
export default defineConfig({
plugins: [react(), optimizeLocales.vite({ locales: ["en-US", "en-GB"] })],
});

The same package exports optimizeLocales.webpack, .rollup and .esbuild. Keep "en-US" in the list: for a locale whose strings were stripped, React Aria falls back to another of the same language, then to US English (“Calendar”, “Start date must be before end date.”). Dates and numbers still format in the person’s locale, which comes from Intl, not from those strings.

Export What it is
packs The curated packs: Signal, then Nocturne.
corePack Signal (mica.core).
getPack(id) The pack with that id, or undefined.
Types MicaPack (id, version, name, tagline, components, descriptors, visuals, templates, starterTemplateId, tokens, runtimeRegistry, sampleSpec), MicaDocument, PackReference

Render a document with pack.runtimeRegistry of the pack parseDocument returned. That registry is what fires a Button’s press and an Input’s commit, and tells the object runtime which event dispatched each action; another registry fires neither.

See theme a micro-app and, for host code, apply a theme. None of these does I/O.

Export What it is
createTheme(source) A MicaTheme built from a ThemeSource. Throws an Error naming the first value it refuses. Every theme it returns meets the contrast floors.
parseTheme(json) { ok: true, theme } or { ok: false, error }: stored theme JSON, checked as strictly as a document.
themeIssue(theme) Why a theme object in memory can’t be used, or null: the checks parseTheme runs.
themeCss(theme) The theme as CSS text for a host that also wants it as a file: the [data-mica-theme="<key>"] token rule, then a rule for each scheme an opaque container restores. The key is the theme’s id and a hash of its tokens. Serve the whole string; a stylesheet insert takes one rule. PackSurface needs no file, except in browsers without constructable stylesheets under a policy refusing inline styles, where it writes no rule (see Content Security Policy). Throws for a theme themeIssue refuses.
themeKey(theme) The data-mica-theme value themeCss’s rules match, which PackSurface sets when passed the theme, for a host that names a served file.
THEME_FONT_STACKS The stack names a font role may use instead of a family, and the stack each one writes.
THEME_TOKEN_NAMES Every token a theme carries, in the order themeCss writes them.
exportThemeDtcg(theme) The theme as DTCG 2025.10 JSON ($value / $type). Every token is a group path taken from its name (--ui-page-paper-bg → ui.page.paper.bg; a name that is a prefix of another stays one token, so --ui-eyebrow-on-ink → ui.eyebrow-on-ink) with $type color, fontFamily, dimension or shadow. source and id are under $extensions["farm.lola.mica"] (MICA_DTCG_EXTENSION), so the same theme always produces the same text and imports back as the same theme. Throws when themeIssue refuses it.
parseThemeDtcg(json) A Mica DTCG file: { ok: true, theme } or { ok: false, error }, checked with parseTheme (grammar, id matches source, contrast floors); a token that is not a theme token and no theme token aliases is refused, and $description, $deprecated and other $extensions are not kept. A file without Mica’s extension: { ok: true, suggestions } of colours, plain font families and, when a corner dimension is recognisable, a radius — not a theme; a token Mica cannot hold (a radius outside whole px, a non-sRGB colour, a font name that is not a plain family) is skipped, and nothing usable gives empty suggestions. Aliases ({group.token}) resolve up to eight deep; a cycle, a missing name, $extends, $ref, an unknown $ property and a token that is also a group are refused by name; a group’s $root token is read like any other. Nothing is taken as CSS.
MICA_THEME_VERSION 1
MAX_THEME_SIZE 32000: the most characters of JSON parseTheme reads.
MAX_DTCG_SIZE 256000: the most characters of JSON parseThemeDtcg reads.
Types MicaTheme (micaTheme, id, source, tokens), ThemeSource (brand, mode, optional accent, fonts, radius, neutralHue, name), ParseThemeResult, ParseThemeDtcgResult, DtcgSuggestions, DtcgColourSuggestion, DtcgFontSuggestion, ThemeTokens, ThemeTokenName, ThemeMode, ThemeRadius, ThemeFontStack
Export What it is
parseDocument(json) { ok: true, spec, pack } or { ok: false, error } — the designer’s import.
listDocumentIssues(json) Every reason import refuses the document, as DocumentIssues (message, kind, elementKey?, path); empty when it imports. The first is always what parseDocument reports. See document format.
serializeDocument(document) The envelope as pretty-printed JSON — the designer’s export.
MICA_ENVELOPE_VERSION 1
Type ParseDocumentResult, DocumentIssue
Export What it is
OBJECT_OPERATIONS ["fetch", "create", "update", "delete"]
OBJECT_WRITE_OPERATIONS ["create", "update", "delete"]
isObjectWriteOperation(operation) Whether operation is one of OBJECT_WRITE_OPERATIONS
COLLECTION_OPERATIONS The operations a collection may enable: all four
IDENTITY_OPERATIONS ["update", "delete"] — the ones that act on one record by identity: a record’s current one, or the collection row a binding names with row
OBJECT_FIELD_KINDS, OBJECT_FIELD_FORMATS The allowed kind and format values
OBJECT_DATA_ROOT, OBJECT_META_ROOT /objects, /meta/objects
objectDataPath, objectPhasePath, objectErrorPath, objectFieldErrorPath, objectCapabilityPath, objectFieldWritabilityPath, objectCountPath Path builders
referencedObjectOperations(document) Map<alias, Set<operation>> of what the document dispatches
referencedHostActions(document) Set<name> of declared host actions the document dispatches
MAX_OBJECT_DECLARATIONS, MAX_HOST_ACTIONS, MAX_OBJECT_FIELDS, MAX_OBJECT_FIELD_DEPTH, MAX_FIELD_PATTERN_LENGTH, MAX_CONFIRMATION_LENGTH 32, 32, 64, 6, 256, 240
Types ObjectAwareSpec, ObjectDeclaration, ObjectDeclarationMap, HostActionDeclaration, HostActionDeclarationMap, ObjectFieldSpec, ObjectFieldKind, ObjectFieldFormat, ObjectFieldCondition, ObjectCapabilitySpec, ObjectOperation, ObjectWriteOperation, DocumentLifecycle, InteractionBinding
Export What it is
preflightObjectBinding(document, binding) { ok, issues } — see the host contract.
preflightHostActions(document, handlers) { ok, issues } — every declared host action the document dispatches is a function on handlers.
preflightLocalActions(document, handlers) { ok, issues } — not-implemented when the document dispatches validate and the handler is missing. See Local form validation.
parseHostActionCatalog(source) { ok, catalog } or { ok: false, error } — the session catalogue a future live host fetches (catalogVersion + actions).
seedRuntimeObjectState(state, declarations, { binding?, data? }) state with every alias’s starting projection merged in.
createObjectRuntime({ document, store, binding?, confirm? }) An ObjectRuntime (below).
hostObjectError(envelope) The error a host function throws to report a safe failure.
objectRejectionReason(error) "busy", "cancelled", "failed", "stale", "superseded" or null.
OBJECT_ERROR_CATEGORIES The seven error categories.
createObjectConfirmationGate() { request, pending, answer, subscribe }; pass request as confirm. One question at a time; a second is declined.
ObjectConfirmationDialog Renders the gate’s open question (gate prop) as a modal alert dialog, inside PackSurface.
Member What it does
handlers { fetch, create, update, delete } for JSONUIProvider (forward to them synchronously; see the guide). One operation per alias at a time, others rejected as busy — except a fetch from a press or commit, which supersedes an in-flight fetch another press or commit dispatched; the older one rejects as superseded. Latest wins applies only between fetches a person’s element events dispatched: startup and host-called fetches are neither superseded nor superseding. A collection’s update and delete take the row’s identity from params.row ({ <identity>: value }, as the event resolved it) and fail with no-row without one; a successful collection write merges into the list by identity, with the count, as the host contract describes.
runStartup() Runs lifecycle.startup once, in order; resolves with StartupFailure[] (index, action, message).
validate(alias, operation?) ObjectFieldIssue[] (operation, field, message) for the inputs the document would send now. No host call, no store write.
reseed(data?) Re-seed every alias (from data, else null) and drop in-flight results.
dispose() End the session; later results are dropped and loading phases return to idle.

Types: HostObjectBinding, HostObjectImplementation, HostFetchCapability, HostCreateCapability, HostUpdateCapability, HostDeleteCapability, HostFieldWritability, ObjectFieldWritability, ObjectOperationAvailability, ObjectIdentity, ObjectPhase, ObjectErrorCategory, ObjectErrorEnvelope, ObjectRejectionReason, ObjectConfirm, ObjectConfirmationRequest, ObjectConfirmationGate, ObjectFieldIssue, ObjectRuntime, ObjectRuntimeOptions, PreflightIssue, PreflightIssueCode, PreflightResult, RuntimeObjectSeedOptions, StartupFailure.

Condition mica/runtime resolves to
types src/runtime.ts (no .d.ts files are emitted)
development src/runtime.ts — used by vite dev and vitest
import dist-lib/runtime.js — run npm run build:lib in the Mica repository first

mica/runtime.css maps straight to src/styles/runtime.css.