{"id":10853,"library":"eval-estree-expression","title":"Safely Evaluate ESTree Expressions","description":"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.","status":"active","version":"3.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jonschlinkert/eval-estree-expression","tags":["javascript","@babel","@babel/parser","6to5","abstract","analysis","ast","babel","babel-cli"],"install":[{"cmd":"npm install eval-estree-expression","lang":"bash","label":"npm"},{"cmd":"yarn add eval-estree-expression","lang":"bash","label":"yarn"},{"cmd":"pnpm add eval-estree-expression","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Commonly used to parse JavaScript code into an ESTree-compatible AST, which is then consumed by `eval-estree-expression`.","package":"@babel/parser","optional":true}],"imports":[{"note":"While CommonJS `require` is still supported, ESM `import` is the preferred and more modern approach for Node.js 14+ environments. The `evaluate` function itself returns a Promise for asynchronous evaluation.","wrong":"const { evaluate } = require('eval-estree-expression');","symbol":"evaluate","correct":"import { evaluate } from 'eval-estree-expression';"},{"note":"The synchronous evaluation method is a property of the main `evaluate` export. No separate named export exists for `evaluate.sync`.","symbol":"evaluate.sync","correct":"import { evaluate } from 'eval-estree-expression';\nconst result = evaluate.sync(ast, context);"},{"note":"`eval-estree-expression` consumes ASTs, it does not parse strings itself. You need an external parser like `@babel/parser` to convert expression strings into an AST first.","wrong":"import { parse } from '@babel/parser'; // parseExpression is typically more suitable for expressions than general `parse`","symbol":"parseExpression (from @babel/parser)","correct":"import { parseExpression } from '@babel/parser';"}],"quickstart":{"code":"import { evaluate } from 'eval-estree-expression';\nimport { parseExpression } from '@babel/parser';\n\nasync function runEvaluation() {\n  const expressionString = 'user.age > 18 && user.status === \"active\" ? \"Eligible\" : \"Not Eligible\"';\n  const context = {\n    user: {\n      name: 'Alice',\n      age: 25,\n      status: 'active'\n    }\n  };\n\n  try {\n    // Parse the expression string into an ESTree AST\n    const ast = parseExpression(expressionString, {\n      sourceType: 'script', // or 'module'\n      plugins: ['estree'] // Ensure Babel outputs ESTree-compatible AST\n    });\n\n    // Synchronous evaluation\n    const syncResult = evaluate.sync(ast, context);\n    console.log('Synchronous result:', syncResult); // Expected: Eligible\n\n    // Asynchronous evaluation (returns a Promise)\n    const asyncResult = await evaluate(ast, { ...context, functions: true }); // functions option enabled for example\n    console.log('Asynchronous result:', asyncResult); // Expected: Eligible\n\n    // Example with a different context\n    const anotherContext = {\n      user: {\n        name: 'Bob',\n        age: 16,\n        status: 'inactive'\n      }\n    };\n    const syncResult2 = evaluate.sync(ast, anotherContext);\n    console.log('Synchronous result (Bob):', syncResult2); // Expected: Not Eligible\n\n  } catch (error) {\n    console.error('Evaluation error:', error.message);\n  }\n}\n\nrunEvaluation();","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js environment to version 14 or higher. If you must support older Node.js, consider using an earlier major version of the library (e.g., v2.x).","message":"Version 3.x and later of `eval-estree-expression` requires Node.js version 14 or greater. This may break existing applications running on older Node.js runtimes.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Avoid enabling `functions: true` or `generate: true` when evaluating untrusted user-supplied expressions or when context objects can contain malicious functions. Carefully sanitize or whitelist any user input before parsing or evaluating.","message":"Enabling the `functions: true` or `generate: true` options can introduce security vulnerabilities by allowing arbitrary function calls or function expressions/statements to be evaluated. This can lead to remote code execution if expressions or contexts originate from untrusted user input.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that the input AST represents only pure expressions. If you need to allow specific assignments or statements, consider alternative, more powerful (and potentially less safe) evaluation mechanisms or pre-process the AST to remove/transform unsupported nodes.","message":"The library is designed for expressions and does not support JavaScript assignment operators (e.g., `=`, `+=`, `--`) or general statements by default. Attempting to evaluate code with these constructs will result in an error.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always validate and sanitize the `context` object when it's populated by untrusted sources. Ensure that context values are primitive types or objects whose properties are strictly controlled and do not expose system-level APIs or sensitive operations.","message":"While `eval-estree-expression` avoids direct `eval()`, it does not inherently provide a secure sandbox against all forms of malicious code execution. If user-controlled data is passed in the `context` object, especially if it contains objects with malicious getters or methods, it could potentially be exploited.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure all variables referenced in the expression are explicitly provided as properties in the `context` object passed to `evaluate` or `evaluate.sync`.","cause":"An expression attempts to access a variable or property ('myVariable') that is not present in the provided `context` object.","error":"ReferenceError: 'myVariable' is not defined"},{"fix":"The library is designed for pure expressions. Do not attempt to evaluate JavaScript statements or expressions that modify state. Remove assignment operators or convert them to pure expressions where possible.","cause":"The input AST (from the parsed expression) contains an assignment operation (e.g., `x = 10`) or a statement not supported by the evaluator.","error":"SyntaxError: Assign expression is not supported"},{"fix":"If you intend to allow function calls, enable the `functions: true` option in the `evaluate` options. If you need to evaluate full function expressions or statements, use `generate: true` (with extreme caution due to security implications).","cause":"An expression attempts to call a function (`myFunction`) when the `functions` option is not explicitly enabled, or a function expression/statement is present without the `generate` option.","error":"TypeError: 'myFunction' is not a function"}],"ecosystem":"npm"}