Registry / serialization / simple-eval

simple-eval

JSON →
library2.0.0jsnpmunverified

simple-eval is a focused JavaScript library designed for evaluating simple expressions safely, providing an alternative to the native `eval()` function with a controlled execution environment. The current stable version is 2.0.0. It aims for a moderate release cadence, primarily for maintenance, bug fixes, or minor feature additions. A key differentiator is its limited instruction set, which enhances security by disallowing declarations, assignments, and complex statements, making it safer than direct `eval` for untrusted input, though it does not provide a full sandbox. It uses `jsep` as the default AST parser but supports any ESTree compliant parser like `acorn`, `@babel/parser`, or `esprima`, offering flexibility in parsing logic. This makes it suitable for scenarios requiring lightweight, controlled expression evaluation.

npm install simple-eval
INSTALL
IMPORT
SIG · SIMPLE-EVAL
S
simple-eval
serializationjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

simpleEval
import simpleEval from 'simple-eval';
const simpleEval = require('simple-eval');
The library primarily uses ES Module syntax as shown in its documentation and ships TypeScript types. While CommonJS `require` might work in some transpiled environments, `import` is the recommended and modern approach.
SimpleEvalFunction
import type { SimpleEvalFunction } from 'simple-eval';
Type import for `simpleEval` function signature, useful when explicitly typing function parameters or variables in TypeScript projects.
CustomParserOptions
import type { CustomParserOptions } from 'simple-eval';
Type import for configuring a custom AST parser, allowing users to specify a different parser than the default `jsep`.

This quickstart demonstrates basic expression evaluation, passing a context object to allow access to `Math` functions, custom objects, and user-defined functions, and shows how to handle errors from undefined variables.

import simpleEval from 'simple-eval'; // Basic arithmetic evaluation const result1 = simpleEval('2 + 4 * 10 + -4'); console.log(`'2 + 4 * 10 + -4' evaluates to: ${result1}`); // Expected: 38 // Using a context object for external variables or functions const context = { Math, user: { name: 'Alice', age: 30, isAdmin: true }, greet: (name) => `Hello, ${name}!` }; const result2 = simpleEval('Math.floor(Math.PI * 10)', context); console.log(`'Math.floor(Math.PI * 10)' with Math context evaluates to: ${result2}`); // Expected: 31 const result3 = simpleEval('user.isAdmin ? greet(user.name) : \'Access Denied\'', context); console.log(`Conditional access with custom function and object: ${result3}`); // Expected: 'Hello, Alice!' // Attempting to use an undeclared variable (will throw if not in context) try { simpleEval('unknownVariable + 5'); } catch (e) { console.error(`Error evaluating 'unknownVariable + 5': ${e.message}`); // Expected: 'unknownVariable is not defined' }
Debug
Known issues
gotchasimple-eval is not a full replacement for `eval` and should not be treated as a general-purpose JavaScript interpreter. It intentionally limits supported language features to enhance safety and predictability.
fix
Always review the 'Caveats' section of the documentation to understand the supported language constructs. For complex script execution or full JavaScript runtime, consider dedicated sandboxing solutions or Node.js `vm` module.
affects: >=1.0.0
breakingDeclarations (e.g., `const`, `let`, `var`, `function`) and assignments (e.g., `x = 5`, `obj.prop = value`) are explicitly prohibited within the evaluated expressions. Attempting to use them will result in an error.
fix
Ensure that your expressions only contain valid evaluable constructs without altering scope or state. Pass all necessary variables and functions through the context object provided as the second argument to `simpleEval`.
affects: >=1.0.0
gotchaThe library does not provide a robust security sandbox. While it restricts many dangerous operations, it is not designed to run arbitrary untrusted code in a secure, isolated environment.
fix
For high-security use cases involving untrusted code, combine `simple-eval` with a proper sandbox solution (e.g., Node.js `vm` module with careful context configuration, or web workers for browser environments) rather than relying solely on its internal restrictions.
affects: >=1.0.0
gotchaBy default, `simple-eval` uses the `jsep` parser. If you encounter parsing issues with specific syntaxes or wish to leverage advanced parsing features (e.g., JSX, Flow, TypeScript), you may need to provide a different ESTree-compliant parser.
fix
To use a different parser, provide a `parser` option in the context object. For example: `simpleEval('...', { parser: customAcornParserInstance })`. Ensure the custom parser outputs an ESTree-compliant AST.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: <variable> is not defined
Attempting to access a variable or function within the evaluated expression that was not passed in the context object.
fix
Ensure all variables, objects, and functions required by the expression are explicitly provided in the second argument to `simpleEval`. Example: `simpleEval('myVar + 1', { myVar: 10 })`.
SyntaxError: Unexpected token
The evaluated string contains unsupported syntax like variable declarations (`const`, `let`, `var`), function declarations, or assignments (`=`).
fix
Remove all declarations and assignments from the expression. `simple-eval` is designed for expressions only. If you need to mutate state, do so outside the evaluation and pass the updated values in the context.
TypeError: Cannot read properties of undefined (reading 'prop')
An object or property within the expression is `undefined` at the time of evaluation.
fix
Check the context object and the expression logic to ensure all object paths are valid and defined. For optional chaining-like behavior, use ternary operators or logical AND (`&&`) within the expression: `user && user.profile && user.profile.name`.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
jseprequiredDefault AST parser for expression evaluation. Can be replaced with other ESTree-compliant parsers.
Agent activity
3 hits · last 30 days
node
2
OpenAI (training)
1
Resources