Expression Parser
A non-visual Web Component for safely parsing and evaluating user-defined expressions.
It renders nothing so importing it is enough to make it available via customElements.get.
Instead of relying on eval() or new Function(), this component builds an Abstract Syntax Tree (AST) from the input string and walks it in a controlled environment.
This gives you full introspection over what an expression does before and after running it.
Security
Sandboxed Evaluation
Expressions are never executed as JavaScript source. The AST evaluator controls every operation explicitly.
Allowed Globals
Expressions can only reference the following built-ins directly:
(Math, JSON, Date, Object, Array, String, Number, Boolean, Symbol);Everything else is resolved through the variable getter you supply.
Blocked Property Names
Accessing any of the following properties throws at evaluation time, regardless of the object:
(__proto__, prototype, constructor, __defineGetter__, __defineSetter__);Supported Literals
| Type | Examples |
|---|---|
| String | "hello", 'world' |
| Number | 42, 3.14 |
| Boolean | true, false |
| Nullish | null, undefined |
| Numeric constants | Infinity, NaN |
Supported Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / % |
| Comparison | < <= > >= |
| Equality | == != === !== |
| Logical | && || ?? |
| Unary | ! + - ~ |
| Ternary | a ? b : c |
Access Patterns
- Variables: resolved through the getter:
price - Dot access:
user.name - Computed access:
items[0],record[key] - Calls:
Math.round(x),fn(a, b)
Expression Chaining
Comma-separated expressions are all evaluated left to right. The result of the last one is returned, matching JavaScript’s comma operator semantics.
Parser.parse("x * 2, y * 2, x + y");// evaluates all three, returns the value of x + yUsage
Parsing
const Parser = customElements.get("wcp-expression-parser") as typeof ExpressionParser;const ast = Parser.parse("quantity * unitPrice");Evaluating
Supply a getter function that receives a variable name and its parent node, and returns its value.
const result = Parser.evaluate(ast, (name, parentNode) => context[name]);Extracting Dependencies
Get every variable name referenced in an expression, useful for building reactive systems.
const ast = Parser.parse("a + b * c");const deps = Parser.usedVariables(ast); // Set(["a", "b", "c"])AST Node Reference
| Node | Represents |
|---|---|
Literal | A fixed value — string, number, boolean, null |
Variable | An identifier looked up via the getter |
Member | Property access, dot or computed |
Call | A function or method invocation |
Unary | A single-operand operation |
Binary | A two-operand operation |
Ternary | A conditional expression |
Sequence | A comma-separated chain of expressions |