Skip to main content

Embed the TypeScript engine

Use @getriebe/workflow when your application will own persistence, identity, and the execution of human and service work. The engine accepts a typed workflow definition and advances an instance against that definition.

Use Node.js 26.13.1. In a new directory, create a TypeScript consumer and install the package for this release:

Terminal window
npm init -y
npm pkg set type=module
npm install --save-exact @getriebe/workflow@0.1.0

Save the following program as example.ts.

import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, rmdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Workflow, type WorkflowDefinition } from "@getriebe/workflow";
const definition: WorkflowDefinition = {
id: "register-document",
nodes: [
{ id: "start", kind: "start" },
{ id: "review", kind: "userTask" },
{ id: "registered", kind: "end" },
],
flows: [
{ id: "begin", source: "start", target: "review" },
{ id: "finish", source: "review", target: "registered" },
],
};
const before = new Workflow(definition);
const started = before.advance(before.start()).instance;
const waiting = before.advance(started);
const occurrence = waiting.activatedActivity;
assert.ok(occurrence && occurrence.kind === "userTask");
console.log("Waiting for", occurrence.nodeId);
const directory = await mkdtemp(join(tmpdir(), "getriebe-engine-"));
const file = join(directory, "snapshot.json");
try {
await writeFile(file, waiting.instance.snapshot());
const after = new Workflow(definition);
const restored = after.restore(await readFile(file, "utf8"));
assert.equal(restored.activities[0]?.id, occurrence.id);
// The embedding application has recorded the reviewer's decision.
const resumed = after.completeActivity(restored, occurrence.id).instance;
const result = after.advance(resumed).instance;
assert.equal(result.status, "completed");
assert.deepEqual(result.reachedEnds, ["registered"]);
console.log("Reached", result.reachedEnds.join(", "));
} finally {
await rm(file, { force: true });
await rmdir(directory);
}

Run node example.ts from the consumer directory. Expect Waiting for review followed by Reached registered.

advance returns the next immutable instance. The User Task activation carries an occurrence ID. The embedding can record an action and use that ID to complete the exact occurrence, including when a loop re-enters the same task. A snapshot also retains active occurrence IDs.

Treat snapshots as opaque and retain the identity of the exact model definition and application release used to create each one. When storing a workflow in an application, commit its snapshot, task and process data, and audit records consistently. The example stores only the snapshot and removes it when done. Read the embedded-execution contract and persistence contracts for those boundaries.

Find the declarations in the workflow package reference.

The embedding supplies UTC epoch milliseconds when advance activates timed work. Use the returned nextTimer to schedule a wake-up. Pass the current time and the intended activation ID to fireDueTimer. After firing, call advance to continue along the timeout flow. This example uses the imports from the first example and a clock you can set explicitly.

const timed = new Workflow({
id: "timed-review",
nodes: [
{ id: "start", kind: "start" },
{ id: "review", kind: "userTask" },
{ id: "deadline", kind: "boundaryTimer", attachedTo: "review", durationMs: 500 },
{ id: "accepted", kind: "end" },
{ id: "expired", kind: "end" },
],
flows: [
{ id: "begin", source: "start", target: "review" },
{ id: "normal", source: "review", target: "accepted" },
{ id: "timeout", source: "deadline", target: "expired" },
],
});
const now = 1_800_000_000_000;
const beforeReview = timed.advance(timed.start()).instance;
const pending = timed.advance(beforeReview, {}, { now }).instance;
const restored = timed.restore(pending.snapshot());
const deadline = restored.nextTimer;
assert.ok(deadline);
assert.equal(deadline.dueAt, now + 500);
assert.equal(timed.fireDueTimer(restored, deadline.dueAt - 1).status, "ignored");
const fired = timed.fireDueTimer(restored, deadline.dueAt, deadline.activityId);
assert.equal(fired.status, "fired");
assert.deepEqual(timed.advance(fired.instance).instance.reachedEnds, ["expired"]);

Use one transaction or serialized command path for completion and interruption. Read the current committed snapshot before deciding either operation. An early or stale timer leaves the instance unchanged. The deadline contract defines the time range and race semantics.

The embedding passes a typed string-list to advance and receives one activity per item. For each activity, use the ID for completion and the member metadata to offer the item in the appropriate role. Keep the inputs relevant to the round stable until it finishes. The embedding owns the role membership check, durable state and audit.

const reviews = new Workflow({
id: "review-order",
fields: { reviewKinds: "string-list", reviewVotes: "boolean-list" },
nodes: [
{ id: "start", kind: "start" },
{ id: "review", kind: "userTask", multiInstance: {
inputField: "reviewKinds",
outputField: "reviewVotes",
roleByItem: { budget: "budget-reviewer", einkauf: "purchasing-reviewer" },
} },
{ id: "end", kind: "end" },
],
flows: [
{ id: "enter", source: "start", target: "review" },
{ id: "leave", source: "review", target: "end" },
],
});
const input = { reviewKinds: { kind: "string-list", value: ["budget", "einkauf"] } } as const;
const readyToReview = reviews.advance(reviews.start(), input).instance;
const round = reviews.advance(readyToReview, input);
const [budget, purchasing] = round.activatedActivities ?? [];
assert.ok(budget && purchasing);
assert.equal(purchasing.multiInstance?.resourceId, "purchasing-reviewer");
const partial = reviews.completeActivity(round.instance, purchasing.id, false);
assert.equal(partial.dataUpdates, undefined);
const recovered = reviews.restore(partial.instance.snapshot());
assert.equal(recovered.activities[0]?.id, budget.id);
const finished = reviews.completeActivity(recovered, budget.id, true);
assert.deepEqual(finished.dataUpdates?.reviewVotes, { kind: "boolean-list", value: [true, false] });
const processData = { ...input, ...finished.dataUpdates };
assert.equal(reviews.advance(finished.instance, processData).instance.status, "completed");

Store the final dataUpdates and the resulting snapshot in the same transaction. Use that data on the next advance call, including when the next step evaluates all(reviewVotes). Restoring a partial snapshot preserves voters’ activity identities and the votes already recorded in it.

In a Node application, register the JavaScript evaluator explicitly. The definition below uses the same input and result as the JavaScript BPMN example.

import assert from "node:assert/strict";
import { Workflow, type WorkflowDefinition } from "@getriebe/workflow";
import { createJavaScriptEvaluator } from "@getriebe/workflow/node";
const scriptDefinition: WorkflowDefinition = {
id: "count-votes",
fields: { reviewVotes: "boolean-list", approved: "boolean" },
nodes: [
{ id: "start", kind: "start" },
{
id: "evaluateVotes",
kind: "scriptTask",
scriptFormat: "text/javascript",
script: "return inputs.reviewVotes.every(vote => vote === true);",
inputs: [{ name: "reviewVotes", kind: "boolean-list", source: "reviewVotes" }],
outputs: [{ name: "approval", kind: "boolean", target: "approved" }],
},
{ id: "end", kind: "end" },
],
flows: [
{ id: "evaluate", source: "start", target: "evaluateVotes" },
{ id: "finish", source: "evaluateVotes", target: "end" },
],
};
const scriptOptions = { scriptEvaluators: [createJavaScriptEvaluator({ timeoutMs: 100 })] };
const scriptWorkflow = new Workflow(scriptDefinition, scriptOptions);
for (const [votes, expected] of [[[true, true], true], [[true, false], false]] as const) {
const data = { reviewVotes: { kind: "boolean-list", value: votes } } as const;
const started = scriptWorkflow.advance(scriptWorkflow.start(), data).instance;
const snapshot = started.snapshot();
const calculated = scriptWorkflow.advance(scriptWorkflow.restore(snapshot), data);
assert.deepEqual(calculated.dataUpdates?.approved, { kind: "boolean", value: expected });
assert.equal(calculated.script?.nodeId, "evaluateVotes");
const committed = scriptWorkflow.restore(calculated.instance.snapshot());
const done = scriptWorkflow.advance(committed, { ...data, ...calculated.dataUpdates });
assert.equal(done.instance.status, "completed");
assert.equal(done.script, undefined);
}
const wrongResult: WorkflowDefinition = {
...scriptDefinition,
nodes: scriptDefinition.nodes.map(node => node.kind === "scriptTask"
? { ...node, script: 'return "yes";' }
: node),
};
const invalidWorkflow = new Workflow(wrongResult, scriptOptions);
const invalidStart = invalidWorkflow.advance(invalidWorkflow.start()).instance;
const problem = invalidWorkflow.advance(invalidStart, {
reviewVotes: { kind: "boolean-list", value: [true] },
});
assert.equal(problem.instance.failure?.code, "script-task-error");
assert.equal(problem.dataUpdates, undefined);

Persist the model version, updated data and new snapshot together. On restore, use the same definition and pass the committed data to advance. The evaluator receives HTTP-encoded copies of declared input values, including exact numeric strings. Use a synchronous, repeatable function body. Approve the model as application code. Script Task contract.