Fragiola

API: core (@fragiola/flow)

The command bus

How the model runs commands with run, can, check and dispatch, the result and its error codes, middleware that vetoes or rewrites, and listeners.

Every change to a flow is a command run through one bus: a name, a JSON payload checked against the command's JSON Schema, a middleware chain, then one commit that every listener sees. The engine runs the same commands for the user's gestures (a drag is node.move steps, a dropped connection edge.add, the Delete key selection.remove), so a middleware you write applies to the mouse, the keyboard, your code and an assistant alike. The commands themselves are on Commands.

Running

const result = model.run("node.move", { nodeId: "review", position: { x: 240, y: 80 } });
if (!result.ok) console.warn(result.error.code, result.error.message);

model.can("edge.add", { source: "review", target: "publish" }); // boolean, nothing committed
model.check("node.remove", { nodeId: "review" }); // the result, nothing committed
model.dispatch({ command: "selection.clear", payload: {} }, { meta: { source: "assistant" } });
membersignaturedescription
run(command, payload?, options?: RunOptions) => CommandResult<R>runs a command, typed by your registry and your features
can(command, payload?, options?) => booleanwhether run would succeed now, middleware included
check(command, payload?, options?) => CommandResult<R>what run would return, without committing or emitting
dispatch(input: unknown, options?: DispatchOptions) => CommandResult<unknown>run for untrusted JSON { command, payload, transient? }, validated first
use(middleware: Middleware<T, F>) => () => voidadds a middleware (the first added runs outermost)
subscribe(listener: CommandListener<T>) => () => voidlistens to every committed command
get(key, payload?)reads; see Model
is(key, payload)asks; see Model

RunOptions:

optiontypedescription
transientbooleana step of a continuous gesture: listeners see it marked, so undo and persistence wait for the final step
metaReadonly<Record<string, unknown>>free-form information for middleware and listeners

DispatchOptions has meta only: it comes from your code, never from the untrusted input.

A dry run (can, check, and the engine asking model.can("edge.add", …) while a connection is drawn) never calls your createId, and a command a middleware issues during one is refused: a dry run causes nothing.

The result

Nothing on the bus throws on bad input. A CommandResult<R> is { ok: true, value } or { ok: false, error }, and a CommandError says why:

fieldtypedescription
codeCommandErrorCodeone of the codes below
messagestringa sentence for a log or an assistant
pathstringa JSON pointer into the payload (or the dispatched input), when the error has a place
issuesreadonly ValidationIssue[]every schema problem, for invalid_payload

CommandErrorCode:

codewhen
unknown_commandno command has this name
invalid_payloadthe payload does not match the command's schema, or names a field of a feature that is not installed
not_founda node or edge the payload names does not exist, or the command's feature is not installed (the message names it)
refuseda rule of the flow forbids it: a permission flag, a duplicate edge, a parent cycle, a command issued during a dry run
vetoeda middleware returned veto(), or returned nothing without calling next() (another failure a middleware returns keeps its own code)
queuedit was issued from a middleware while another command ran: it runs after that one
middleware_errora middleware threw

Middleware

A Middleware<T, F> is a function (ctx, next) => CommandResult | undefined that runs around every command, engine-issued or not. It can veto (return a failure without calling next: veto(message?) builds one with the code vetoed), rewrite (assign a new ctx.payload, which is validated again, then call next) or observe (call next and look at its result). Returning undefined passes on next's result when it was called. A middleware may veto a success but never turn a failed command into one.

import { type Middleware, veto } from "@fragiola/flow-react";

/** Connection rules: no self loop, and a "trigger" node takes no incoming edge. */
const rules: Middleware<Types, typeof features> = (ctx, next) => {
    if (ctx.command !== "edge.add") return next();
    const { source, target } = ctx.payload;
    if (source === target) return veto("an edge joins two different nodes");
    if (ctx.get("node-by", { id: target })?.type === "trigger") {
        return veto("a trigger starts a workflow: nothing connects into it");
    }
    return next();
};

const stop = model.use(rules);

The payload is a frozen copy: rewrite it by assigning a new object, never by writing into it. Because the engine asks model.can("edge.add", …) while a connection is drawn, a vetoed target is marked data-invalid before the drop (see Connection rules).

ctx is a CommandContext<T, F>: a union discriminated by command, so checking the command narrows the payload. What every command's context has, CommandContextBase<T>:

fieldtypedescription
commandCommandNamethe command (narrows payload)
payloadits payload typethe validated payload; assign a new object to rewrite it
dryRunbooleancan, check or a connection's hover: nothing will be committed, cause no side effects
transientbooleana step of a gesture
inBatchbooleanthe command runs inside a batch (the batch itself also passes the chain)
metaReadonly<Record<string, unknown>> | undefinedthe run's meta
stateFlowDocument<T>the committed document the command applies to
get(key, payload)"node-by" or "edge-by"reads a node or an edge as the command sees it: inside a batch, after its earlier commands

CommandContextGetMap<T> types what ctx.get reads, CommandContextGetKey its keys.

Batches

batch runs several commands as one: all or nothing, one commit, one event. It is transient only when every step may be. A middleware sees the batch, then each of its steps (inBatch: true).

model.run("batch", {
    commands: [
        { command: "node.add", payload: { id: "notify", type: "task", position: { x: 0, y: 200 }, data: { title: "Notify" } } },
        { command: "edge.add", payload: { source: "review", target: "notify" } },
    ],
});

BatchEntry<T> is one { command, payload }; the event reports the steps it ran as BatchSteps.

Listeners

subscribe gets one CommandEvent<T> per commit:

fieldtypedescription
commandCommandNamethe command, or batch
payloadunknownthe payload it ran with (after the middleware rewrote it)
resultunknownthe command's value
beforeFlowDocument<T>the document before
afterFlowDocument<T>the document after: unchanged entities are the same objects
transientbooleana step of a gesture; the gesture ends with a final, non-transient step
metaReadonly<Record<string, unknown>> | undefinedthe run's meta
commandsreadonly BatchStep[]for a batch: the commands it ran, flattened

BatchStep:

fieldtypedescription
commandCommandNamethe step's command
payloadunknownits payload
resultunknownits value
const stop = model.subscribe((event) => {
    if (event.transient) return; // a drag in progress: wait for its drop
    if (event.meta?.source === "controlled") return; // the root syncing controlled props
    save(model.get("flow-json"));
});

CommandListener<T> is the listener's type. What the React root runs to bring the model to controlled nodes / edges carries meta: { source: "controlled" }.

Describing the commands

model.get("commands") lists every installed command as a CommandInfo, ready to become an AI tool definition (see AI and automation):

fieldtypedescription
nameCommandNameits name
descriptionstringwhat it does, for an assistant
payloadSchemaJsonSchemaits payload's JSON Schema
resultSchemaJsonSchemaits result's JSON Schema
transientbooleanwhether it may run as a step of a gesture
featureFeatureNamethe feature it comes with; none for the core's

The types

CommandName (every command, the core's and the features'), CommandMap<T> (each one's payload and result), PayloadOf<T, C> and ResultOf<T, C>, CommandNameOf<F> (the commands of a model with the features F). Payload and result types named by the commands: NodeFlagsPayload, EdgeFlagsPayload, ConnectionPayload (source, target and their handles), NodeDataPatchOf<T> and EdgeDataPatchOf<T> (a shallow patch of one type's data), SelectionMode ("replace", "add", "toggle"), RemovedResult, SelectionResult.

A command is declared with a CommandDefinition (its name, description, schemas, transient and a reducer that returns a result or a Failure, receiving a ReduceContext): the shape a feature's commands have (see Features).