Skip to content

Implement business objects in a host

This guide continues Embed Mica in a host application for documents that declare business objects. Mica owns validation and projection on both sides of every call. It owns no transport, no credentials and no authorization: the host decides who may do what, on every call.

A binding maps each declared alias to an implementation for the person signed in right now. Each operation is a plain function; supply only the ones the document uses.

import { hostObjectError, type HostObjectBinding } from "mica/runtime";
export function createCustomerBinding(session: YourSession): HostObjectBinding {
return {
customer: {
type: "crm.customer", // must equal the declaration's `type`
fetch: async ({ customerId }) => api.customers.get(String(customerId), session),
update: async (identity, inputs) => api.customers.update(String(identity), inputs, session),
delete: async (identity) => {
await api.customers.close(String(identity), session);
},
},
};
}
Operation Called with Resolve with
fetch(inputs) the declared fetch inputs the record (for a collection, the list of records)
create(inputs) the declared create inputs the complete new record, including its identity
update(identity, inputs) the current record’s identity (for a collection, the row the binding names with row) and the declared update inputs the complete saved record
delete(identity, inputs) the current record’s identity (for a collection, the row the binding names with row) and the declared delete inputs anything (ignored)

For a collection, create and update answer with one row, which Mica merges into the current list by identity; see collection row writes.

Inputs arrive already checked against the declaration, with $state reads resolved. Return the record however your service shapes it: Mica keeps only the declared fields and refuses a response that is missing a required one.

Throw hostObjectError to tell the document what went wrong in terms it may show:

throw hostObjectError({
category: "conflict", // validation | permission | not-found | conflict | unavailable | cancelled | unknown
code: "customer.name-taken", // stable, machine-readable, up to 128 characters
message: "Another customer already uses that name.",
retryable: false,
fieldErrors: { displayName: "Another customer already uses that name." },
});

Only fieldErrors keys that name a declared input of that operation are kept. Anything else thrown — a network error, a stack trace — reaches the document only as The host could not complete this request.

Two optional members tell the document what the person may do, so it can hide or lock things. Neither is a security boundary: the host still refuses what it does not allow.

customer: {
type: "crm.customer",
// Per operation. An operation is "implemented" exactly when its function is
// supplied; an omitted entry means allowed.
availability: { delete: { allowed: false, reason: "Only account owners can delete customers." } },
// Per declared leaf field, dot-joined for nested ones. Fields left out follow
// the update capability. Read at seed, re-seed, and after every successful fetch.
fieldWritability: () => ({
"contact.email": { writable: false, reason: "Billing email changes go through identity verification." },
}),
// …operations
}

Before rendering, check that the binding can serve what the document actually dispatches:

const preflight = preflightObjectBinding(document, binding);
// { ok: false, issues: [{ alias: "customer", operation: "delete", code: "not-implemented", message: "…" }] }

Issue codes are missing-binding, type-mismatch and not-implemented. Only operations the document uses are required — a declared alias the document never dispatches needs no binding. Mica renders nothing for preflight: the host decides what an incompatible deployment looks like.

seedRuntimeObjectState merges each alias’s starting projection — data null (or a snapshot you pass), every phase idle, the capability and field writability answers — into the state you give it:

const [store] = useState(() =>
createStateStore(seedRuntimeObjectState({ ...document.state }, document.objects, { binding })),
);

Pass { binding, data: { customer: record } } to start from a record you already have; that alias’s fetch phase then starts as success (or error with host-contract if the record does not match the declared fields). A declaration’s design sample is never used at runtime.

4. Create the object runtime and run startup

Section titled “4. Create the object runtime and run startup”
const [confirmation] = useState(createObjectConfirmationGate);
const session = useRef<ObjectRuntime | null>(null);
useEffect(() => {
const runtime = createObjectRuntime({ document, store, binding, confirm: confirmation.request });
session.current = runtime;
if (preflight.ok) void runtime.runStartup().then(reportFailures);
return () => {
runtime.dispose();
if (session.current === runtime) session.current = null;
};
}, [document, store, binding, confirmation, preflight.ok]);
  • runStartup() runs lifecycle.startup in order, keeps going past a failed entry, and resolves with the failures. A second call does nothing, so an effect that runs twice cannot load twice.
  • dispose() ends the session: anything that settles afterwards is dropped and a phase left loading goes back to idle.
  • reseed(data?) puts every alias back to its starting projection and drops what is in flight. It is the only supported way to replace an alias’s data; do not write /objects/… or /meta/objects/… into the store yourself.
  • validate(alias, operation?) runs the declaration’s input rules over what the document would send now, without calling the host.

5. Register the verbs and the confirmation

Section titled “5. Register the verbs and the confirmation”

Because JSONUIProvider reads handlers once and the runtime is created in an effect, register stable functions that forward to the live session:

const [handlers] = useState(() => {
const objectHandlers = {} as Record<ObjectOperation, (params: Record<string, unknown>) => Promise<void>>;
for (const operation of OBJECT_OPERATIONS) {
objectHandlers[operation] = (params) => {
if (!session.current) throw new Error(`${operation}: no object runtime session is mounted.`);
return session.current.handlers[operation](params);
};
}
return { ...objectHandlers, goToPage: goToPageHandler(document, navigate) };
});

Forward synchronously, as above. One operation runs per object at a time and another is rejected as busy, except that a fetch a person’s press or commit dispatches supersedes a fetch still in flight that another press or commit dispatched (latest wins; the older one rejects as superseded). Each runtime handler learns whether an element event dispatched it at the moment it is called, so a wrapper that awaits anything first — or a host calling handlers itself — gets the busy rule.

Render the confirmation dialog inside the pack surface so it picks up the pack’s styling. Without a confirm function, delete never runs, and neither does a create or update that carries a confirmation.

<PackSurface pack={pack}>
<Renderer spec={document} registry={pack.runtimeRegistry} />
<ObjectConfirmationDialog gate={confirmation} />
</PackSurface>
  • examples/mock-host/src/host/objects.ts binds a crm.customer with all four verbs, per-principal field writability (?principal=support locks the name), a host rule that answers with field errors, and deliberately malformed responses to show how Mica rejects them.
  • The live examples on this site use small in-browser bindings in site/src/components/exampleHosts.ts, rendered by site/src/components/MicaExample.tsx with exactly the steps above.