Craft

The expression language

An expression is a small, safe part of JavaScript: one expression, no statements. It reads the file's fields and gives one value, which is checked against the field's declared type. Each section below stands on its own.

Declaring a computed field

Add expression to a field. Its type (with items or properties for a list or object) describes the value the expression gives:

{
  "proficiencyBonus": {
    "type": "number",
    "expression": "2 + floor(($self.level - 1) / 4)"
  }
}
  • Only top-level fields can be computed. An expression on a field inside an object or a list's items is refused.
  • A computed field can't be in required.
  • "type": "formula" fields, from the old formula system, are refused. Rewrite them as expressions.
  • Declaring the shape of a computed list or object is optional, but layouts and other expressions can then rely on its fields.

$self

$self is the file's own content: its stored fields, plus every computed field of the file. $self.level, $self.stats.strength. A field that isn't set reads as null.

The first step after $self must be a field name the schema declares: $self[key] is refused, and so is $self.notAField. Deeper steps can be worked out: $self.resourceState[r.key]. $self is the only name the language defines; besides it, an expression can use only the functions and the parameters of its own x => … functions.

Values

A value is always plain JSON: null, true or false, a number, text, a list or an object. There are no dates, no functions as values and no undefined. A result that isn't a finite number, such as dividing by zero, is null.

Write Example
Numbers, text, true/false, null 1, 2.5, "Alive", true, null
Text with values in it `Level ${$self.level}`
Lists [1, 2, ...$self.tags]
Objects { name: r.name, total: a + b, ...base }
Fields and items $self.class, list[0], obj[key]

Inside `…${}…`, null becomes empty text and a list or object becomes compact JSON.

Operators

Kind Operators
Arithmetic + - * / % ** and -x, +x
Comparison < <= > >= (two numbers, or two pieces of text)
Equality === !== (== and != mean the same)
Logic && || ?? and !x
Choice cond ? a : b
Grouping ( … )
  • + joins text when either side is text; otherwise it adds numbers.
  • Every other arithmetic operator works on numbers only. Text is never turned into a number for you: use number(x).
  • Equality is strict and compares lists and objects by their contents: [1, 2] === [1, 2] is true.
  • && and || give one of their sides, as in JavaScript.

Null handling

Reading a field of null gives null, not an error, so long paths are safe: $self.class.name is null when there is no class. ?. is allowed and means the same as ..

Arithmetic and ordering comparisons with a null side give null. Give a default with ??:

($self.hp ?? 0) + ($self.tempHp ?? 0)

False, 0, empty text and null count as false in &&, ||, ! and ? :. Everything else, empty lists and objects included, counts as true.

Functions passed to methods

Methods like map and filter, and the totals sum, avg and count, take a function written in place: a name for each item, an arrow and one expression.

$self.inventory.filter(e => e.equipped).map(e => e.name).join(", ")

The functions of map, filter, sum and the others that go item by item also get the item's position as a second parameter: map((e, i) => …). reduce passes the value so far, the item and its position; toSorted passes two items. The body is one expression; { … } bodies are refused. A function can only be written as an argument like this, never stored or returned, so every expression finishes.

load()

load(value) gives the content of the file a reference points at. Pass the reference field's value as it is:

load($self.class)?.hitDie
sum($self.inventory, e => (load(e.item)?.weight ?? 0) * (e.quantity ?? 1))
$self.knownSpells.map(s => load(s)?.school)
  • The result is the target's stored content with its own computed fields worked out, plus these keys:
Key What it holds
$id The file's id.
$name The file's name.
$title The file's display title, or its name when it has none.
$image The file's main picture, as an image object.
$coverImage The file's cover picture as an image object, or its main picture when it has none.
$fileTypeSlug The slug of the file's type.
  • A reference only says which file. $self.class.hitDie would always be null, so reading a field straight off a reference field is refused on save: read through load().
  • load() takes a stored reference or a reference id. A slug, an empty reference or a file that isn't there gives null, so guard with ?. and ??.
  • load() finds only the files this file's own reference fields point at. A reference read off a loaded file (load(load($self.class)?.feature)) gives null.
  • Reads go one level deep. A computed field of the loaded file is worked out, but if it uses load() itself (directly or through another of its fields), the schema that reads it is refused. If that field gains a load() later, its own load() gives null when read this way.
  • When the target type is known from the schema, each field you read off load() is checked on save: it must exist on every target type. Only the loaded file's top-level computed fields can be read.

Computed fields reading computed fields

An expression can read other computed fields of the same file. They are worked out in the order they depend on each other:

{
  "dexModifier": { "type": "number", "expression": "floor((($self.dexterity ?? 10) - 10) / 2)" },
  "armorClass": { "type": "number", "expression": "10 + $self.dexModifier + (load($self.armor)?.bonus ?? 0)" }
}

A loop (a field that depends on itself, directly or through others) is refused on save.

Computed lists

A whole list can be computed. This is how per-item values work, since fields inside a list can't have their own expression. Keep the definitions on a referenced file (or in a list written into the expression), keep what the player changes in a small stored map, and join them:

{
  "resourceState": {
    "type": "object",
    "additionalProperties": { "type": "object", "properties": { "current": { "type": "number" } } }
  },
  "resources": {
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "key": { "type": "string" },
        "name": { "type": "string" },
        "current": { "type": "number" },
        "maximum": { "type": "number" }
      }
    },
    "expression": "(load($self.class)?.resources ?? []).map(r => ({ key: r.key, name: r.name, current: $self.resourceState?.[r.key]?.current ?? 0, maximum: r.maximum }))"
  }
}

The file stores only resourceState, such as { "rage": { "current": 2 } }. Change the class and the list follows. Give each row a stable key and key the stored map by it. A layout can repeat a tracker over the computed list and send each edit to the stored map with an edit path (see the layout spec).

The same join replaces families of fields. Skills need no stored flag, modifier and display field each: store skillProficiencies (key to true or false) and compute one skills list from the skill definitions and $self.proficiencyBonus:

{
  "skillProficiencies": { "type": "object", "additionalProperties": { "type": "boolean" } },
  "skills": {
    "type": "array",
    "expression": "(load($self.ruleSet)?.skills ?? []).map(row => ({ key: row.key, name: row.name, proficient: $self.skillProficiencies?.[row.key] == true, modifier: floor((($self.abilityScores?.[row.ability] ?? 10) - 10) / 2) + ($self.skillProficiencies?.[row.key] == true ? ($self.proficiencyBonus ?? 2) : 0) }))"
  }
}

For a fixed set, write the definition rows into the expression as a list instead of loading them.

A table picked by level is a list of rows, read with filter and at:

(load($self.class)?.slotsTable ?? []).filter(r => r.level <= $self.level).at(-1)?.slots ?? 0

Not allowed

Refused on save: assignment of any kind, ++ and --, statements, function, class, new, this, regular expressions, tagged templates, the comma operator, await, yield, fn?.(), and every global name (Math, Object, JSON, Date, window). The names __proto__, constructor and prototype are refused anywhere. Names starting with $ are kept for Craft; only $self exists.

Errors while working out a value

A computed field never breaks a page. If its expression does too much work, gives a result that is too big, or gives a value that doesn't match the field's type, that field is null and the others still work. Smaller faults give null where they happen and the expression goes on: a method called on null or on the wrong kind of value (.map on a number), or a function given the wrong kind of value. So ?? after them still works.

Limits

Limit Value
Expression length 5,000 characters
Nesting depth 64 levels of brackets, calls and operators
Functions inside functions 8 deep
Work per field 100,000 steps; each step inside a function passed to a method counts again for every item it runs on
Size of a computed value 10,000 items and keys in all, and 262,144 characters as JSON

Checks on save

When a schema with expressions is saved, each expression is checked:

  1. It parses, and uses only what the language allows.
  2. Every name is $self, a function or one of its own parameters.
  3. Each method exists, gets a number of arguments it takes, and gets a function only where it takes one.
  4. The first step after $self is a declared field, and computed fields don't loop. No field is read straight off a reference field.
  5. Expressions are only on top-level fields, and none is in required.
  6. Fields read off load() exist on the target types, and reads go one level deep. A target type that doesn't exist yet is skipped, so the order you make types in doesn't matter.
  7. It is within the length and depth limits.