Safe expression evaluator that prevents arbitrary code execution while supporting common boolean expressions and property access patterns.

Supported operations:

  • Comparison: ==, ===, !=, !==, <, >, <=, >=
  • Logical: &&, ||, !
  • Property access: dot notation (e.g., payload.customer.name)
  • Array access: bracket notation (e.g., items[0])
  • Safe methods: .length, .includes(), .startsWith(), .endsWith()
  • Array methods: .some(), .every(), .find(), .filter()
  • Type checking: typeof, instanceof (limited to safe types)

SafeExpressionEvaluator

Example

const evaluator = new SafeExpressionEvaluator();

// Simple comparison
const result1 = evaluator.evaluate(
"status == 'active'",
{ status: 'active' }
);

// Nested property access
const result2 = evaluator.evaluate(
"payload.customer.tier == 'premium' && payload.order.total > 1000",
{ payload: { customer: { tier: 'premium' }, order: { total: 1500 } } }
);

// Array methods
const result3 = evaluator.evaluate(
"items.some(item => item.price > 100)",
{ items: [{ price: 50 }, { price: 150 }] }
);

Constructors

Properties

DANGEROUS_PATTERNS: RegExp[] = ...

Patterns that indicate potentially dangerous code

SAFE_METHODS: string[] = ...

Safe methods that can be called on objects

Methods

  • Private

    Safely clones a value for use in evaluation context

    Parameters

    • value: any

      The value to clone

    Returns any

    The cloned value

  • Private

    Creates a safe context object with only allowed properties

    Parameters

    • context: Record<string, any>

      The original context

    Returns Record<string, any>

    The safe context

  • Evaluates a boolean expression against a context object

    Parameters

    • expression: string

      The boolean expression to evaluate

    • context: Record<string, any>

      The context object containing variables

    • Optional enableDiagnostics: boolean = false

      Whether to include diagnostic information

    Returns ExpressionEvaluationResult

    The evaluation result

  • Evaluates multiple expressions and returns all results

    Parameters

    • expressions: {
          expression: string;
          name?: string;
      }[]

      Array of expressions to evaluate

    • context: Record<string, any>

      The context object

    Returns Record<string, ExpressionEvaluationResult>

    Map of results by name or index

  • Private

    Checks if a property name is potentially dangerous

    Parameters

    • name: string

      The property name

    Returns boolean

    True if dangerous

  • Private

    Validates an expression for safety

    Parameters

    • expression: string

      The expression to validate

    Returns string

    Error message if invalid, null if valid