TypeScript state machines with built-in persistence.
State machines are great for modeling complex workflows. But persisting them usually means gluing together a state machine library, a database layer, and custom sync logic.
machin handles both. Define your machine, pick a storage adapter, and your state transitions are automatically persisted. No manual saves, no sync bugs.
- Awaitable by design
- Postgres, SQLite, and Redis adapters included
- Full TypeScript inference for states, events, and context
- Inspect sendable events with
actor.nextEvents
npm install machinpnpm add machinyarn add machinimport { machine } from "machin";
import { withDrizzlePg } from "machin/drizzle/pg";
type Context = { customerId: string | null };
// Define your machine
const orderMachine = machine<Context>().define({
initial: "pending",
states: {
pending: {
on: { confirm: { target: "processing" } },
},
processing: {
entry: async (ctx, event: { customerId: string }) => {
// Do async work here
return { ...ctx, customerId: event.customerId };
},
onSuccess: { target: "completed" },
onError: { target: "failed" },
},
completed: {},
failed: {
on: { retry: { target: "processing" } },
},
},
});
// Bind to storage
const boundMachine = withDrizzlePg(orderMachine, { db, table: ordersTable });
// Create an actor and inspect what can be sent now
const actor = await boundMachine.createActor("order-123", { customerId: null });
console.log(actor.nextEvents); // ["confirm"]
// Actors are immutable, so keep the returned actor
const nextActor = await actor.send("confirm", { customerId: "customer-456" });
console.log(nextActor.state); // "completed"
console.log(nextActor.nextEvents); // []State is persisted automatically after each transition.
Each actor exposes nextEvents, which lists the event names available from its current state.
const actor = await boundMachine.getActor("order-123");
if (actor) {
console.log(actor.state);
console.log(actor.nextEvents);
}nextEvents returns names only. If an event targets a state with an entry payload, you still pass that payload when calling send().
Guards can be used in on, onSuccess, and onError. For entry states, onSuccess
guards run against the updated context returned by entry.
import { machine } from "machin";
type OrderContext = {
paymentStatus:
| "pending"
| "authorized"
| "requires_manual_review"
| "retryable_failure";
attempts: number;
};
const orderMachine = machine<OrderContext>().define({
initial: "awaiting_payment",
states: {
awaiting_payment: {
on: {
charge: [
{
guard: (ctx, payload) =>
ctx.attempts < 3 && payload.amount > 0,
target: "charging_card",
},
{ target: "payment_failed" },
],
},
},
charging_card: {
entry: async (
ctx,
event: {
amount: number;
outcome: "authorized" | "requires_manual_review" | "retryable_failure";
},
) => {
return {
...ctx,
attempts: ctx.attempts + 1,
paymentStatus: event.outcome,
};
},
onSuccess: [
{
guard: (ctx) => ctx.paymentStatus === "authorized",
target: "paid",
},
{
guard: (ctx) => ctx.paymentStatus === "requires_manual_review",
target: "awaiting_manual_review",
},
{
guard: (ctx) => ctx.paymentStatus === "retryable_failure",
target: "payment_failed",
},
],
onError: { target: "payment_failed" },
},
awaiting_manual_review: {},
paid: {},
payment_failed: {},
},
});import { withDrizzlePg } from "machin/drizzle/pg";
const machine = withDrizzlePg(machineConfig, { db, table: myTable });import { withDrizzleSQLite } from "machin/drizzle/sqlite";
const machine = withDrizzleSQLite(machineConfig, { db, table: myTable });import { createClient } from "redis";
import { withRedis } from "machin/redis";
const client = await createClient({ url: "redis://localhost:6379" }).connect();
const machine = withRedis(machineConfig, { client });Your table needs these columns:
id(text, primary key)state(text)createdAt(timestamp)updatedAt(timestamp)
Plus any columns for your context fields.
machin provides type inference utilities to extract types from your machine definitions. This is useful for typing database columns, API responses, or any other code that needs to work with machine states, events, or context.
import { machine, InferStates, InferEvents, InferContext } from "machin";
const myMachine = machine<{ count: number }>().define({
initial: "idle",
states: {
idle: { on: { start: { target: "running" } } },
running: { on: { stop: { target: "idle" } } },
},
});
// Infer types from the machine
type States = InferStates<typeof myMachine>; // "idle" | "running"
type Events = InferEvents<typeof myMachine>; // "start" | "stop"
type Context = InferContext<typeof myMachine>; // { count: number }The inference utilities are particularly useful for typing your database schema columns:
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { InferStates } from "machin";
import { orderMachine } from "./order-machine";
// Infer the state type from your machine
type OrderState = InferStates<typeof orderMachine>;
// → "pending" | "processing" | "completed" | "failed"
export const ordersTable = pgTable("orders", {
id: uuid().primaryKey(),
state: text().$type<OrderState>().notNull(),
createdAt: timestamp().notNull(),
updatedAt: timestamp().notNull(),
});This ensures your database schema stays in sync with your machine definition - if you add or remove states from your machine, TypeScript will catch any mismatches.
MIT