UNPKG

2.01 kBMarkdownView Raw
1# static-eval
2
3evaluate statically-analyzable expressions
4
5[![testling badge](https://ci.testling.com/substack/static-eval.png)](https://ci.testling.com/substack/static-eval)
6
7[![build status](https://secure.travis-ci.org/browserify/static-eval.png)](http://travis-ci.org/browserify/static-eval)
8
9# security
10
11static-eval is like `eval`. It is intended for use in build scripts and code transformations, doing some evaluation at build time—it is **NOT** suitable for handling arbitrary untrusted user input. Malicious user input _can_ execute arbitrary code.
12
13# example
14
15``` js
16var evaluate = require('static-eval');
17var parse = require('esprima').parse;
18
19var src = process.argv[2];
20var ast = parse(src).body[0].expression;
21
22console.log(evaluate(ast));
23```
24
25If you stick to simple expressions, the result is statically analyzable:
26
27```
28$ node '7*8+9'
2965
30$ node eval.js '[1,2,3+4*5-(5*11)]'
31[ 1, 2, -32 ]
32```
33
34but if you use statements, undeclared identifiers, or syntax, the result is no
35longer statically analyzable and `evaluate()` returns `undefined`:
36
37```
38$ node eval.js '1+2+3*n'
39undefined
40$ node eval.js 'x=5; x*2'
41undefined
42$ node eval.js '5-4*3'
43-7
44```
45
46You can also declare variables and functions to use in the static evaluation:
47
48``` js
49var evaluate = require('static-eval');
50var parse = require('esprima').parse;
51
52var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
53var ast = parse(src).body[0].expression;
54
55console.log(evaluate(ast, {
56 n: 6,
57 foo: function (x) { return x * 100 },
58 obj: { x: { y: 555 } }
59}));
60```
61
62# methods
63
64``` js
65var evaluate = require('static-eval');
66```
67
68## evaluate(ast, vars={})
69
70Evaluate the [esprima](https://npmjs.org/package/esprima)-parsed abstract syntax
71tree object `ast` with an optional collection of variables `vars` to use in the
72static expression resolution.
73
74If the expression contained in `ast` can't be statically resolved, `evaluate()`
75returns undefined.
76
77# install
78
79With [npm](https://npmjs.org) do:
80
81```
82npm install static-eval
83```
84
85# license
86
87MIT