decision control
Reference

Rule engine formulas

Complete guide to formula syntax, operators, functions, contexts and execution limits.

A formula is an expression returning a JSON value: number, string, boolean, list, object or null. Use it in conditions, calculations, table rules and fields accepting expressions. It is not JavaScript and cannot run arbitrary code or access the network.

The editor calls parseFormula in packages/engine/src/expression/formula.ts and stores the resulting JSONLogic tree. createExpressionEngine, in packages/engine/src/expression/engine.ts, compiles and evaluates it with json-logic-engine; methods.ts registers the platform's functions. For example:

round(amount * 0.15, 2)
{ "round": [{ "dec_mul": [{ "var": "amount" }, 0.15] }, 2] }

When submitting a flow through the API, put that JSON tree in expression, rather than the text shown in the editor. See Executing decisions and Calculate.

Values and syntax

ElementExamples and behavior
Numbers42, 0.35, 1e3, 2.5E-2. A decimal point needs digits on both sides: use 0.5, not .5 or 5..
Negative numbers-5, -amount; the sign is a unary operator.
Text'APPROVED' or "APPROVED". Quotes must be closed.
Booleans and nulltrue, false, null.
Lists[], ['DO', 'US'], [amount, amount * 2]. Item expressions are evaluated.
Fieldsamount, customer.risk.level, items.0.price.
Grouping(amount + fee) * rate.
Functionsround(amount, 2); comma-separated arguments, with no trailing comma.

AND, OR, NOT, IN, BETWEEN, IF, THEN, ELSE, TRUE, FALSE and NULL are case-insensitive. Field and function names are case-sensitive: round exists, ROUND does not.

Identifiers start with an ASCII letter, _ or $, and may then contain digits. For paths with hyphens, spaces or reserved names, use var('nodes.calc-1.total') or var('input.in'). Text syntax has no bracket access (items[0]), method calls (name.trim()), object literals, local variables, assignments, comments, string interpolation, ** power, === comparison or ?? operator. Conditionals use the IF … THEN … ELSE form below, not the ? : ternary. Use functions or JSONLogic where appropriate.

Text escapes

A backslash takes the next character literally: \n becomes the letter n, not a newline. Double the backslash to preserve it. This formula matches AB followed by digits:

matches(code, '^AB\\d+$')

Transporting the formula string in JSON adds another escaping layer:

{ "formula": "matches(code, '^AB\\\\d+$')" }

That object only illustrates transport escaping; it is not a node contract. The equivalent JSONLogic AST is {"matches": [{"var": "code"}, "^AB\\d+$"]}.

Operators and precedence

From highest to lowest precedence:

LevelOperatorsExample
1Literals, paths, calls, lists and parenthesesround(amount, 2)
2Unary -, NOT, !-amount, NOT active, !!active
3*, /, %amount * rate, count % 2
4+, -amount + fee - discount
5>, >=, <, <=, =, ==, !=, <>, IN, BETWEEN … AND …amount >= 100, amount BETWEEN 100 AND 200
6AND, &&active AND amount > 0
7OR, ||active OR vip
8IF … THEN … ELSE …IF amount > 0 THEN amount ELSE 0

Arithmetic operators at the same level associate left to right: 10 - 2 - 3 returns 5; 20 / 5 / 2 returns 2. Chained comparisons such as 0 < amount < 100 are unsupported: write amount > 0 AND amount < 100.

NOT applies before comparison. Negate a complete comparison with NOT (amount > 100), rather than NOT amount > 100. The right side of IN is parsed as a unary expression: parenthesize a compound expression if needed. BETWEEN includes both endpoints; the AND separating its bounds belongs to the range.

IF condition THEN value ELSE value selects a branch; chain conditions with ELSE IF. The final ELSE is optional, and a missing one yields null. The condition is a full boolean expression, so IF amount > 0 AND active THEN … reads the way it is written. if(condition, a, b) is the same operator written as a call.

Formula operatorStored operatorMeaning
+, -, *, /, %dec_add, dec_sub, dec_mul, dec_div, dec_modDecimal arithmetic; % is remainder, not percentage.
-valuedec_negNegation.
=, ==dec_eqDecimal equality or comparison of representations.
!=, <>dec_neqInequality.
>, >=, <, <=dec_gt, dec_gte, dec_lt, dec_lteOrdering between two values.
BETWEENdec_betweenInclusive range.
INinList membership or substring search.
AND, OR, NOTand, or, !Logic with JSONLogic truthiness.
IF … THEN … ELSEifConditional; ELSE IF adds condition/value pairs.

AND and OR return an operand, which need not be a boolean: 0 OR 42 returns 42; 'OK' AND 7 returns 7. Use !!(expression) for a boolean. IN distinguishes list item types: 1 IN ['1'] returns false. Text matching is case-sensitive.

Context: where fields come from

PathContents
amountComputed variable with that name, if present; otherwise the input field.
input.amountOriginal payload.
vars.totalVariables computed by earlier nodes.
nodes.<id>.<field>Stored node output; use var('nodes.calc-1.total') for hyphenated IDs.
global.rateProject constants resolved before execution.
$nowInjected execution timestamp, also available through now().
table.amountMapped table inputs within the table context. Mapped inputs are also exposed by bare name.
item, indexCurrent item and index in a For Each child flow.
response.status, response.headers, response.body, response.attemptsOnly in API Call response mapping.
resultAlias for the response body in that mapping.

Reserved roots are injected over the payload. A computed variable shadows an input field with the same name: use input.amount to always read the original. List functions change the context to the current item; see the list examples below.

A missing field returns null. This does not mean all its comparisons return false: absent = null and absent < 0 return true. Require data explicitly with not_blank(amount) AND amount > 0 or NOT is_null(amount), depending on the business rule.

Truthiness, blanks and comparison

Conditions treat null, false, 0, '', [] and {} as false. '0', ' ' and [0] are true. This differs from blankness: is_blank(' ') returns true, while is_blank(0), is_blank(false) and is_blank({}) return false.

dec_* comparisons convert to decimals when both operands are numbers or numeric strings matching forms such as -12.34 or 1e3; surrounding whitespace is ignored. Thus '1500' = 1500 is true. Otherwise, they first compare identity; null/missing values sort before non-null values; then text or JSON serialization is compared lexicographically. Do not use this ordering as type validation. ISO dates with consistent formatting can be ordered as text; use date functions for time intervals.

Every function available in formulas

The parser checks that a function name exists, but does not validate every argument type or count. A formula that can be saved may still fail for invalid inputs.

Decimal arithmetic

FunctionAliasResult
dec_add(a, b, ...)addSum; no arguments returns 0.
dec_sub(a, b, ...)subSubtracts following operands from the first; no arguments returns 0.
dec_mul(a, b, ...)mulProduct; no arguments returns 1.
dec_div(a, b, ...)divSuccessive division; a zero divisor throws.
dec_mod(a, b)modRemainder; a zero divisor throws.
dec_round(value, places)roundRounds halves away from zero; places defaults to 0.
dec_abs(value)absAbsolute value.
dec_neg(value)negNegation.
dec_min(a, b, ...)—Decimal minimum; no arguments returns 0.
dec_max(a, b, ...)—Decimal maximum; no arguments returns 0.
dec_sum(list)sumList sum; null/missing means an empty list; a scalar becomes one item.
dec_pct(value, percent)pctvalue * percent / 100.
dec_fixed(value, places)fixedText with fixed decimals; defaults to 2 places.
dec_to_number(value)to_numberConverts a numeric value to a JSON number.

Arithmetic uses decimal.js with its default configuration (20 significant digits). 0.1 + 0.2 returns 0.3, but precision is not unlimited: numeric results are converted back to JavaScript/JSON numbers. Preserve large decimal operands as strings when comparing: '10000000000000000.02' > '10000000000000000.01'. fixed returns text.

places must be a number: it is truncated and clamped to 0…20; nonnumeric values use the default. Arithmetic rejects booleans, nulls and nonnumeric text. Native min(a, b, ...) and max(a, b, ...) also exist and require numbers; use dec_min and dec_max for decimal behavior.

Comparison

FunctionEquivalent
dec_gt(a, b)a > b
dec_gte(a, b)a >= b
dec_lt(a, b)a < b
dec_lte(a, b)a <= b
dec_eq(a, b)a = b
dec_neq(a, b)a != b
dec_between(value, lower, upper)value BETWEEN lower AND upper

The JSONLogic alias between is registered, but between(...) cannot be written as a call because it is a reserved keyword. Use dec_between(...) or infix syntax. Likewise, in, and, or and not must use their formula operators.

Text and regular expressions

FunctionBehavior
cat(a, b, ...)Concatenates values as text.
substr(text, from, length)Slice starting at a zero-based index; negative start counts from the end; negative length excludes trailing characters.
len(value)Text/list length or object key count; null and non-text scalars return 0.
length(value)Native length variant; rejects nulls and unsupported types.
matches(value, pattern)Searches for a match; use ^ and $ to validate the whole string.

matches converts its subject to text (null means '') and returns false for a non-text pattern. It supports literals, ., classes, \\d, \\w, \\s and their negations, anchors, word boundaries, groups, alternation and *, +, ?, {n,m} quantifiers. It does not accept a third flags argument or /pattern/i syntax, and does not extract captures. Backreferences, lookahead, lookbehind and Unicode properties \\p{…} are rejected. Invalid patterns throw.

Nulls, presence and data access

FunctionBehavior
coalesce(a, b, ...)First nonblank argument; null if none. Preserves 0 and false.
is_blank(value)Null/missing, empty or whitespace-only text, or an empty list.
not_blank(value)Negation of is_blank.
is_null(value)Null or missing.
var(path, fallback)Reads a dotted context path; default fallback is null. var('') returns the current context.
get(object, path, fallback)Reads a dotted path within an object.
val('customer', 'age')Reads path segments from context; it does not take an object and path like get.
exists('customer', 'age')Tests path existence, even when the final value is null. Takes segments, not the resolved value.
keys(object)Object key list; requires a valid non-null object.
missing('a', 'b', ...)Missing path list; a present field holding null is not missing.
missing_some(count, ['a', 'b'])[] if at least count paths exist; otherwise the missing path list.

coalesce evaluates arguments before selecting: coalesce(1, 1 / 0) throws. Distinguish existence from value with exists('amount') and is_null(amount) separately.

Lists and context changes

FunctionBehavior
map(list, expression)Evaluates an expression per item and returns a list.
filter(list, condition)Keeps items whose condition is truthy.
reduce(list, expression, initial)Accumulates a result; expression receives current and accumulator. Include an initial value for empty lists.
all(list, condition)All match; an empty list returns false.
every(list, condition)Alias of all.
some(list, condition)Any matches; an empty list returns false.
none(list, condition)None match; an empty list returns true.
merge(listA, listB, ...)Joins lists one level deep; scalar arguments become items.

In map, filter, all, every, some and none, fields are read from the current item. For scalar lists use var(''); for objects, read fields directly:

map([1, 2, 3], var('') * 2)
filter(items, price > 100)
sum(map(items, price * quantity))
reduce([10, 20, 30], accumulator + current, 0)
all(items, not_blank(code))

The first expression returns [2, 4, 6]; the reduction returns 60. Formulas can transform lists. Relative var paths such as ../ can access outer contexts, but their depth depends on the operator; verify them with test cases when nesting iterations.

Dates

FunctionBehavior
now()Execution timestamp $now when it is text; otherwise null.
days_between(from, to)(to - from) in 24-hour blocks, rounded with Math.round; can be negative.
add_days(date, days)Adds 24-hour blocks and returns a UTC ISO timestamp; accepts negative and fractional offsets.

Dates accept strings interpretable by Date or numeric timestamps in milliseconds. Prefer ISO with an explicit time zone. These functions do not count local calendar days or adjust for daylight saving changes. Invalid dates throw. now() does not read the system clock: the runner injects execution time to make replay reproducible.

Control and advanced functions

FunctionBehavior
if(condition, onTrue, onFalse)Selects a branch; accepts additional condition/result pairs and a final fallback. Also written IF … THEN … ELSE ….
try(expression, fallback, ...)Tries expressions until one succeeds. After an error the fallback context contains type, rather than the original context.
throw(type)Throws an explicit error, for example throw('INVALID_INPUT').
pipe(expression, next, ...)Each result becomes the next step's context; var('') reads that result.
preserve(value)Returns its argument without evaluation; useful for literal data in JSON ASTs.
IF amount >= 1000 THEN 'REVIEW' ELSE 'APPROVE'
if(amount >= 1000, 'REVIEW', 'APPROVE')
try(to_number(amount), 0)
pipe([1, 2, 3], sum(var('')))

Compilation can evaluate constant subexpressions before selecting a branch. Do not place an invalid constant operation in a branch you expect to skip: if(false, 1 / 0, 42) throws in the current engine. try(1 / 0, 0) does recover from this error and returns 0.

Operators available only as JSONLogic AST

The engine also registers operators whose names or argument structures cannot be expressed directly through the text parser. This inventory completes the functions above:

JSONLogic operatorsUse
+, -, *, /, %, min, maxNative arithmetic. Formula symbols translate to dec_*; native JSON has different coercion and precision rules.
>, >=, <, <=, ==, !=, ===, !==Native comparison; three-character variants distinguish types. Not equivalent to decimal formula comparisons.
!, !!, not, and, orNegation, boolean conversion and logic; formulas use !, !!, NOT, AND, OR.
in, betweenJSON membership and range forms; formulas use IN, BETWEEN or dec_between.
?:JSON alias of if.
??First non-null/non-missing operand; preserves empty text and lists. Unlike coalesce, which skips blanks.
eachKeyBuilds an object by evaluating an expression per key. Formulas cannot write the required object literal.
{
  "eachKey": {
    "total": { "dec_mul": [{ "var": "amount" }, 1.15] },
    "status": { "if": [{ "dec_gt": [{ "var": "amount" }, 1000] }, "REVIEW", "APPROVE"] }
  }
}

The parser recognizes eachKey(...), but calls produce an argument list; to build an object use the JSON structure above. preserve can retain literal JSON objects without treating them as operators.

Limits, errors and execution

CaseBehavior
Unknown name, unsupported symbol, unclosed quotes/parenthesesParse error with message and zero-based position.
Empty formula in parseFormulaError; the editor handles empty fields using that field's default value.
Unknown JSON operatorCompilation/evaluation error.
Null or nonnumeric text in arithmetic, division/remainder by zeroEvaluation error. Use validation or try where appropriate.
Configured engine limitsDepth 64, list length 32,768, text length 65,536, subject to the underlying engine's checks.
RegexPattern up to 500 characters, subject up to 20,000, program up to 2,000 instructions and repetition up to 1,000.
External dependenciesNo network or side effects; external data arrives through flow nodes.

The engine caches up to 500 compiled expressions; this does not limit a decision's rule count. Nodes are also subject to the runner's execution budget: see Security. Expression evaluation errors can fail a node; use test cases with missing data, zero, empty lists and out-of-range values before publishing.

Recipes

GoalFormula
Require a positive amountnot_blank(amount) AND amount > 0
Ratio with error recoverytry(round(totalMonthlyDebt / monthlyIncome, 2), 0)
15% rounded to two decimalsround(pct(amount, 15), 2)
Allowed country and high amountcountry IN ['DO', 'US'] AND amount > 10000
Default valuecoalesce(segment, 'STANDARD')
Total from object listsum(map(items, price * quantity))
Required valid codenot_blank(code) AND matches(code, '^AB\\d+$')
Older than a 365-day yeardays_between(openedAt, now()) > 365
Access a hyphenated node IDvar('nodes.calc-1.total')

See also Expression reference and Expressions are pure.

On this page