An interface and API for constructing and evaluating dice rolls. The basic structure for a dice roll is a string formula and an object of data against which to parse it.

Example: Attack with advantage

// Construct the Roll instance
let r = new Roll("2d20kh + @prof + @strMod", {prof: 2, strMod: 4});

// The parsed terms of the roll formula
console.log(r.terms); // [Die, OperatorTerm, NumericTerm, OperatorTerm, NumericTerm]

// Execute the roll
await r.evaluate();

// The resulting equation after it was rolled
console.log(r.result); // 16 + 2 + 4

// The total resulting from the roll
console.log(r.total); // 22

Constructors

  • Parameters

    • formula: string

      The string formula to parse

    • data: object = {}

      The data object against which to parse attributes within the formula

    • Optional options: object = {}

      Options which modify or describe the Roll

    Returns Roll

Properties

data: object

The original provided data object which substitutes into attributes of the roll formula.

options: object

Options which modify or describe the Roll

terms: RollTerm[]

The identified terms of the Roll

_formula: string

Store the original cleaned formula for the Roll, prior to any internal evaluation or simplification

_dice: DiceTerm[] = []

An array of inner DiceTerms that were evaluated as part of the Roll evaluation

_evaluated: boolean = false

Track whether this Roll instance has been evaluated or not. Once evaluated the Roll is immutable.

_total: number

Cache the numeric total generated through evaluation of the Roll.

_root: Roll

A reference to the Roll at the root of the evaluation tree.

_resolver: RollResolver

A reference to the RollResolver app being used to externally resolve this Roll.

MATH_PROXY: Math = ...

A Proxy environment for safely evaluating a string using only available Math functions

CHAT_TEMPLATE: string = "templates/dice/roll.html"

The HTML template path used to render a complete Roll object to the chat log

TOOLTIP_TEMPLATE: string = "templates/dice/tooltip.html"

The HTML template used to render an expanded Roll tooltip to the chat log

RESOLVERS: Map<Roll, RollResolver> = ...

A mapping of Roll instances to currently-active resolvers.

Accessors

  • get dice(): DiceTerm[]
  • Return an Array of the individual DiceTerm instances contained within this Roll.

    Returns DiceTerm[]

  • get formula(): string
  • Return a standardized representation for the displayed formula associated with this Roll.

    Returns string

  • get result(): string
  • The resulting arithmetic expression after rolls have been evaluated

    Returns string

  • get total(): number
  • Return the total result of the Roll expression if it has been evaluated.

    Returns number

  • get product(): any
  • Return the arbitrary product of evaluating this Roll.

    Returns any

  • get isDeterministic(): boolean
  • Whether this Roll contains entirely deterministic terms or whether there is some randomness.

    Returns boolean

  • get defaultImplementation(): typeof Roll
  • Get the default configured Roll class.

    Returns typeof Roll

  • get resolverImplementation(): any
  • Retrieve the appropriate resolver implementation based on the user's configuration.

    Returns any

Methods

  • Alter the Roll expression by adding or multiplying the number of dice which are rolled

    Parameters

    • multiply: number

      A factor to multiply. Dice are multiplied before any additions.

    • add: number

      A number of dice to add. Dice are added after multiplication.

    • Optional multiplyNumeric: boolean = {}

      Apply multiplication factor to numeric scalar terms

    Returns Roll

    The altered Roll expression

  • Clone the Roll instance, returning a new Roll instance that has not yet been evaluated.

    Returns Roll

  • Execute the Roll asynchronously, replacing dice and evaluating the total result

    Parameters

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          allowStrings: boolean;
          allowInteractive: boolean;
      } = {}

      Options which inform how the Roll is evaluated

      • minimize: boolean

        Minimize the result, obtaining the smallest possible value.

      • maximize: boolean

        Maximize the result, obtaining the largest possible value.

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

      • allowInteractive: boolean

        If false, force the use of non-interactive rolls and do not prompt the user to make manual rolls.

    Returns Promise<Roll>

    The evaluated Roll instance

    Example: Evaluate a Roll expression

    let r = new Roll("2d6 + 4 + 1d4");
    await r.evaluate();
    console.log(r.result); // 5 + 4 + 2
    console.log(r.total); // 11
  • Execute the Roll synchronously, replacing dice and evaluating the total result.

    Parameters

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          strict: boolean;
          allowStrings: boolean;
      } = {}
      • minimize: boolean

        Minimize the result, obtaining the smallest possible value.

      • maximize: boolean

        Maximize the result, obtaining the largest possible value.

      • strict: boolean

        Throw an Error if the Roll contains non-deterministic terms that cannot be evaluated synchronously. If this is set to false, non-deterministic terms will be ignored.

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

    Returns Roll

    The evaluated Roll instance.

  • Alias for evaluate.

    Parameters

    • options: object = {}

      Options passed to Roll#evaluate

    Returns Promise<Roll>

    See

  • Create a new Roll object using the original provided formula and data. Each roll is immutable, so this method returns a new Roll instance using the same data.

    Parameters

    • Optional options: object = {}

      Evaluation options passed to Roll#evaluate

    Returns Promise<Roll>

    A new Roll object, rolled using the same formula and data

  • Recompile the formula string that represents this Roll instance from its component terms.

    Returns string

    The re-compiled formula

  • Propagate flavor text across all terms that do not have any.

    Parameters

    • flavor: string

      The flavor text.

    Returns void

  • Returns string

  • Render the tooltip HTML for a Roll instance

    Returns Promise<string>

    The rendered HTML tooltip as a string

  • Render a Roll instance to HTML

    Parameters

    • Optional options: {
          flavor: string;
          template: string;
          isPrivate: boolean;
      } = {}

      Options which affect how the Roll is rendered

      • flavor: string

        Flavor text to include

      • template: string

        A custom HTML template path

      • isPrivate: boolean

        Is the Roll displayed privately?

    Returns Promise<string>

    The rendered HTML template as a string

  • Transform a Roll instance into a ChatMessage, displaying the roll result. This function can either create the ChatMessage directly, or return the data object that will be used to create.

    Parameters

    • messageData: object = {}

      The data object to use when creating the message

    • Optional options: options = {}

      Additional options which modify the created message.

    Returns Promise<any>

    A promise which resolves to the created ChatMessage document if create is true, or the Object of prepared chatData otherwise.

  • Construct an inline roll link for this Roll.

    Parameters

    • Optional options: {
          label: string;
          attrs: Record<string, string>;
          dataset: Record<string, string>;
          classes: string[];
          icon: string;
      } = {}

      Additional options to configure how the link is constructed.

      • label: string

        A custom label for the total.

      • attrs: Record<string, string>

        Attributes to set on the link.

      • dataset: Record<string, string>

        Custom data attributes to set on the link.

      • classes: string[]

        Additional classes to add to the link. The classes inline-roll and inline-result are added by default.

      • icon: string

        A font-awesome icon class to use as the icon instead of a d20.

    Returns HTMLAnchorElement

  • Represent the data of the Roll as an object suitable for JSON serialization.

    Returns object

    Structured data which can be serialized into JSON

  • Protected

    Prepare the data structure used for the Roll. This is factored out to allow for custom Roll classes to do special data preparation using provided input.

    Parameters

    • data: object

      Provided roll data

    Returns object

    The prepared data object

  • Protected

    Evaluate the roll asynchronously.

    Parameters

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          allowStrings: boolean;
          allowInteractive: boolean;
      } = {}

      Options which inform how evaluation is performed

      • minimize: boolean

        Force the result to be minimized

      • maximize: boolean

        Force the result to be maximized

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

      • allowInteractive: boolean

        If false, force the use of digital rolls and do not prompt the user to make manual rolls.

    Returns Promise<Roll>

  • Protected

    Evaluate an AST asynchronously.

    Parameters

    • node: any

      The root node or term.

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          allowStrings: boolean;
      } = {}

      Options which inform how evaluation is performed

      • minimize: boolean

        Force the result to be minimized

      • maximize: boolean

        Force the result to be maximized

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

    Returns Promise<string | number>

  • Protected

    Evaluate the roll synchronously.

    Parameters

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          strict: boolean;
          allowStrings: boolean;
      } = {}

      Options which inform how evaluation is performed

      • minimize: boolean

        Force the result to be minimized

      • maximize: boolean

        Force the result to be maximized

      • strict: boolean

        Throw an error if encountering a term that cannot be synchronously evaluated.

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

    Returns Roll

  • Protected

    Evaluate an AST synchronously.

    Parameters

    • node: any

      The root node or term.

    • Optional options: {
          minimize: boolean;
          maximize: boolean;
          strict: boolean;
          allowStrings: boolean;
      } = {}

      Options which inform how evaluation is performed

      • minimize: boolean

        Force the result to be minimized

      • maximize: boolean

        Force the result to be maximized

      • strict: boolean

        Throw an error if encountering a term that cannot be synchronously evaluated.

      • allowStrings: boolean

        If true, string terms will not cause an error to be thrown during evaluation.

    Returns string | number

  • Protected

    Safely evaluate the final total result for the Roll using its component terms.

    Returns number

    The evaluated total

  • A factory method which constructs a Roll instance using the default configured Roll class.

    Parameters

    • formula: string

      The formula used to create the Roll instance

    • Optional data: object = {}

      The data object which provides component data for the formula

    • Optional options: object = {}

      Additional options which modify or describe this Roll

    Returns Roll

    The constructed Roll instance

  • Transform an array of RollTerm objects into a cleaned string formula representation.

    Parameters

    • terms: RollTerm[]

      An array of terms to represent as a formula

    Returns string

    The string representation of the formula

  • A sandbox-safe evaluation function to execute user-input code with access to scoped Math methods.

    Parameters

    • expression: string

      The input string expression

    Returns number

    The numeric evaluated result

  • After parenthetical and arithmetic terms have been resolved, we need to simplify the remaining expression. Any remaining string terms need to be combined with adjacent non-operators in order to construct parsable terms.

    Parameters

    • terms: RollTerm[]

      An array of terms which is eligible for simplification

    Returns RollTerm[]

    An array of simplified terms

  • Simulate a roll and evaluate the distribution of returned results

    Parameters

    • formula: string

      The Roll expression to simulate

    • n: number = 10000

      The number of simulations

    Returns Promise<number[]>

    The rolled totals

  • Register an externally-fulfilled result with an active RollResolver.

    Parameters

    • method: string

      The fulfillment method.

    • denomination: string

      The die denomination being fulfilled.

    • result: number

      The obtained result.

    Returns boolean | void

    Whether the result was consumed. Returns undefined if no resolver was available.

  • Parse a formula expression using the compiled peggy grammar.

    Parameters

    • formula: string

      The original string expression to parse.

    • data: object

      A data object used to substitute for attributes in the formula.

    Returns RollTerm[]

  • Instantiate the nodes in an AST sub-tree into RollTerm instances.

    Parameters

    • ast: any

      The root of the AST sub-tree.

    Returns RollTerm[]

  • Replace referenced data attributes in the roll formula with values from the provided data. Data references in the formula use the

    Parameters

    • formula: string

      The original formula within which to replace

    • data: object

      The data object which provides replacements

    • Optional options: {
          missing: string;
          warn: boolean;
      } = {}

      Options which modify formula replacement

      • missing: string

        The value that should be assigned to any unmatched keys. If null, the unmatched key is left as-is.

      • warn: boolean

        Display a warning notification when encountering an un-matched key.

    Returns string

    Attr

    syntax and would reference the corresponding attr key.

    Static

  • Validate that a provided roll formula can represent a valid

    Parameters

    • formula: string

      A candidate formula to validate

    Returns boolean

    Is the provided input a valid dice formula?

  • Determine which of the given terms require external fulfillment.

    Parameters

    Returns DiceTerm[]

  • Internal

    Classify a remaining string term into a recognized RollTerm class

    Parameters

    • term: string

      A remaining un-classified string

    • Optional options: {
          intermediate: boolean;
          prior: string | RollTerm;
          next: string | RollTerm;
      } = {}

      Options which customize classification

      • intermediate: boolean

        Allow intermediate terms

      • prior: string | RollTerm

        The prior classified term

      • next: string | RollTerm

        The next term to classify

    Returns RollTerm

    A classified RollTerm instance

  • Expand an inline roll element to display its contained dice result as a tooltip.

    Parameters

    • a: HTMLAnchorElement

      The inline-roll button

    Returns Promise<void>

  • Collapse an expanded inline roll to conceal its tooltip.

    Parameters

    • a: HTMLAnchorElement

      The inline-roll button

    Returns void

  • Recreate a Roll instance using a provided data object

    Parameters

    • data: object

      Unpacked data representing the Roll

    Returns Roll

    A reconstructed Roll instance

  • Recreate a Roll instance using a provided JSON string

    Parameters

    • json: string

      Serialized JSON data representing the Roll

    Returns Roll

    A reconstructed Roll instance

  • Manually construct a Roll object by providing an explicit set of input terms

    Parameters

    • terms: RollTerm[]

      The array of terms to use as the basis for the Roll

    • Optional options: object = {}

      Additional options passed to the Roll constructor

    Returns Roll

    The constructed Roll instance

    Example: Construct a Roll instance from an array of component terms

    const t1 = new Die({number: 4, faces: 8};
    const plus = new OperatorTerm({operator: "+"});
    const t2 = new NumericTerm({number: 8});
    const roll = Roll.fromTerms([t1, plus, t2]);
    roll.formula; // 4d8 + 8