Safely Evaluate ESTree Expressions

3.0.1 · active · verified Sun Apr 19

eval-estree-expression is a JavaScript library designed for the safe, synchronous, and asynchronous evaluation of ESTree-compliant Abstract Syntax Trees (ASTs). It is currently at version 3.0.1, with development active and a 4.0.0-beta release available, indicating a steady release cadence. This package differentiates itself by focusing specifically on expressions, avoiding the inherent dangers of direct `eval()` usage by operating on ASTs from parsers like `@babel/parser`, `esprima`, or `acorn`. It provides a controlled environment, requiring explicit context for variables and offering options to enable potentially unsafe features like arbitrary function calls with caution. The library strictly operates on Node.js version 14 or greater and does not support JavaScript statements or assignment operators by default, ensuring a higher degree of security when evaluating untrusted expressions compared to general-purpose JavaScript evaluators. Its design choice to work with ASTs makes it a robust alternative to libraries like `expr-eval` which have faced critical remote code execution vulnerabilities due to insufficient validation of evaluation contexts.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a JavaScript expression string using `@babel/parser` and then evaluating it both synchronously and asynchronously with `eval-estree-expression`, providing a custom context object. It also highlights the flexibility of changing context for different evaluations.

import { evaluate } from 'eval-estree-expression';
import { parseExpression } from '@babel/parser';

async function runEvaluation() {
  const expressionString = 'user.age > 18 && user.status === "active" ? "Eligible" : "Not Eligible"';
  const context = {
    user: {
      name: 'Alice',
      age: 25,
      status: 'active'
    }
  };

  try {
    // Parse the expression string into an ESTree AST
    const ast = parseExpression(expressionString, {
      sourceType: 'script', // or 'module'
      plugins: ['estree'] // Ensure Babel outputs ESTree-compatible AST
    });

    // Synchronous evaluation
    const syncResult = evaluate.sync(ast, context);
    console.log('Synchronous result:', syncResult); // Expected: Eligible

    // Asynchronous evaluation (returns a Promise)
    const asyncResult = await evaluate(ast, { ...context, functions: true }); // functions option enabled for example
    console.log('Asynchronous result:', asyncResult); // Expected: Eligible

    // Example with a different context
    const anotherContext = {
      user: {
        name: 'Bob',
        age: 16,
        status: 'inactive'
      }
    };
    const syncResult2 = evaluate.sync(ast, anotherContext);
    console.log('Synchronous result (Bob):', syncResult2); // Expected: Not Eligible

  } catch (error) {
    console.error('Evaluation error:', error.message);
  }
}

runEvaluation();

view raw JSON →