New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

eval5

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

eval5 - npm Package Compare versions

Comparing version 1.0.9 to 1.1.0

2

esm/Function.d.ts

@@ -1,1 +0,1 @@

export default function (...args: string[]): (...args: any[]) => any;
export default function (...args: string[]): (...args: string[]) => any;

@@ -16,2 +16,3 @@ import { MessageItem } from "./messages";

timeout?: number;
initEnv?: (inst: Interpreter) => void;
}

@@ -21,3 +22,6 @@ interface CollectDeclarations {

}
declare type ScopeData = {};
declare type ScopeData = {
[prop: string]: any;
[prop: number]: any;
};
declare class Scope {

@@ -30,5 +34,8 @@ name: string | undefined;

}
declare type Context = {};
declare type Context = {
[prop: string]: any;
[prop: number]: any;
};
export declare class Interpreter {
context: Context;
context: Context | Scope;
value: any;

@@ -49,10 +56,13 @@ rootContext: Context;

protected execEndTime: number;
static version: string;
static readonly version = "1.1.0";
static readonly eval: symbol;
static readonly Function: symbol;
static rootContext: undefined;
static global: any;
constructor(context?: Context, options?: Options);
constructor(context?: Context | Scope, options?: Options);
isInterruptThrow<T>(err: T): boolean;
getSuperScope(): Scope;
protected setCurrentContext(ctx: Context): void;
protected setCurrentScope(scope: Scope): void;
protected initEnvironment(ctx: Context): void;
protected initEnvironment(ctx: Context | Scope): void;
evaluate(code?: string, ctx?: Context): any;

@@ -59,0 +69,0 @@ evaluateNode(node: ESTree.Program, source?: string, ctx?: Context): any;

@@ -19,2 +19,4 @@ import _construct from "@babel/runtime/helpers/construct";

var EmptyStatementReturn = Symbol("EmptyStatementReturn");
var IEval = Symbol("IEval");
var IFunction = Symbol("IFunction");

@@ -50,22 +52,2 @@ function isFunction(func) {

function getGlobal() {
if (typeof self !== "undefined") {
return self;
}
if (typeof window !== "undefined") {
return window;
}
if (typeof global !== "undefined") {
return global;
}
if (typeof this !== "undefined") {
return this;
}
return {};
}
function createScope(parent, name) {

@@ -76,5 +58,3 @@ if (parent === void 0) {

return new Scope({}
/* or Object.create(null)? */
, parent, name);
return new Scope(Object.create(null), parent, name);
}

@@ -99,3 +79,4 @@

this.options = {
timeout: options.timeout || 0
timeout: options.timeout || 0,
initEnv: options.initEnv
};

@@ -112,2 +93,101 @@ this.context = context;

_proto.getSuperScope = function getSuperScope() {
var _this = this;
var data = {
NaN: NaN,
Infinity: Infinity,
undefined: undefined,
// null,
Object: Object,
Array: Array,
String: String,
Boolean: Boolean,
Number: Number,
Date: Date,
RegExp: RegExp,
Error: Error,
TypeError: TypeError,
Math: Math,
parseInt: parseInt,
parseFloat: parseFloat,
isNaN: isNaN,
isFinite: isFinite,
decodeURI: decodeURI,
decodeURIComponent: decodeURIComponent,
encodeURI: encodeURI,
encodeURIComponent: encodeURIComponent,
escape: escape,
unescape: unescape
};
data.eval = function (code, useGlobalScope) {
if (useGlobalScope === void 0) {
useGlobalScope = true;
}
if (typeof code !== "string") return code;
if (!code) return void 0;
var options = {
timeout: _this.options.timeout,
initEnv: function initEnv(inst) {
// set caller context
if (!useGlobalScope) {
inst.setCurrentContext(_this.getCurrentContext());
}
inst.execStartTime = _this.execStartTime;
inst.execEndTime = inst.execStartTime;
}
};
var currentScope = useGlobalScope ? _this.rootScope : _this.getCurrentScope();
var interpreter = new Interpreter(currentScope, options);
return interpreter.evaluate(code);
};
Object.defineProperty(data.eval, "__IS_EVAL_FUNC", {
value: true,
writable: false,
enumerable: false,
configurable: false
});
data.Function = function () {
for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
var code = params.pop();
var interpreter = new Interpreter(_this.rootScope, _this.options);
var wrapCode = "\n\t\t (function anonymous(" + params.join(",") + "){\n\t\t " + code + "\n\t\t });\n\t\t ";
return interpreter.evaluate(wrapCode);
};
Object.defineProperty(data.Function, "__IS_FUNCTION_FUNC", {
value: true,
writable: false,
enumerable: false,
configurable: false
}); // ES5 Object
if (typeof JSON !== "undefined") {
data.JSON = JSON;
} //ES6 Object
// if (typeof Promise !== "undefined") {
// data.Promise = Promise;
// }
// if (typeof Set !== "undefined") {
// data.Set = Set;
// }
// if (typeof Map !== "undefined") {
// data.Map = Map;
// }
// if (typeof Symbol !== "undefined") {
// data.Symbol = Symbol;
// }
return new Scope(data, null, "root");
};
_proto.setCurrentContext = function setCurrentContext(ctx) {

@@ -122,8 +202,24 @@ this.currentContext = ctx;

_proto.initEnvironment = function initEnvironment(ctx) {
//init global scope
this.rootScope = new Scope(ctx, null, "root");
var superScope = this.getSuperScope();
if (!(ctx instanceof Scope)) {
// replace Interpreter.eval and Interpreter.Function
Object.keys(ctx).forEach(function (key) {
if (ctx[key] === IEval) {
ctx[key] = superScope.data.eval;
}
if (ctx[key] === IFunction) {
ctx[key] = superScope.data.Function;
}
});
} //init global scope
var scope = ctx instanceof Scope ? ctx : new Scope(ctx, superScope, "global");
this.rootScope = scope;
this.currentScope = this.rootScope; //init global context == this
this.rootContext = ctx;
this.currentContext = ctx; // collect var/function declare
this.rootContext = scope.data;
this.currentContext = scope.data; // collect var/function declare

@@ -134,2 +230,7 @@ this.collectDeclVars = Object.create(null);

this.execEndTime = this.execStartTime;
var initEnv = this.options.initEnv;
if (initEnv) {
initEnv(this);
}
};

@@ -235,3 +336,3 @@

_proto.createClosure = function createClosure(node) {
var _this = this;
var _this2 = this;

@@ -389,7 +490,7 @@ var timeout = this.options.timeout;

return function () {
if (_this.checkTimeout()) {
throw _this.createInternalThrowError(Messages.ExecutionTimeOutError, timeout, node);
if (_this2.checkTimeout()) {
throw _this2.createInternalThrowError(Messages.ExecutionTimeOutError, timeout, node);
}
_this.lastExecNode = node;
_this2.lastExecNode = node;
return closure.apply(void 0, arguments);

@@ -400,3 +501,3 @@ };

return function () {
_this.lastExecNode = node;
_this2.lastExecNode = node;
return closure.apply(void 0, arguments);

@@ -408,3 +509,3 @@ };

_proto.binaryExpressionHandler = function binaryExpressionHandler(node) {
var _this2 = this;
var _this3 = this;

@@ -485,3 +586,3 @@ var leftExpression = this.createClosure(node.left);

default:
throw _this2.createInternalThrowError(Messages.BinaryOperatorSyntaxError, node.operator, node);
throw _this3.createInternalThrowError(Messages.BinaryOperatorSyntaxError, node.operator, node);
}

@@ -493,3 +594,3 @@ };

_proto.logicalExpressionHandler = function logicalExpressionHandler(node) {
var _this3 = this;
var _this4 = this;

@@ -507,3 +608,3 @@ var leftExpression = this.createClosure(node.left);

default:
throw _this3.createInternalThrowError(Messages.LogicalOperatorSyntaxError, node.operator, node);
throw _this4.createInternalThrowError(Messages.LogicalOperatorSyntaxError, node.operator, node);
}

@@ -515,3 +616,3 @@ };

_proto.unaryExpressionHandler = function unaryExpressionHandler(node) {
var _this4 = this;
var _this5 = this;

@@ -567,3 +668,3 @@ switch (node.operator) {

default:
throw _this4.createInternalThrowError(Messages.UnaryOperatorSyntaxError, node.operator, node);
throw _this5.createInternalThrowError(Messages.UnaryOperatorSyntaxError, node.operator, node);
}

@@ -576,3 +677,3 @@ };

_proto.updateExpressionHandler = function updateExpressionHandler(node) {
var _this5 = this;
var _this6 = this;

@@ -585,3 +686,3 @@ var objectGetter = this.createObjectGetter(node.argument);

_this5.assertVariable(obj, name, node);
_this6.assertVariable(obj, name, node);

@@ -596,3 +697,3 @@ switch (node.operator) {

default:
throw _this5.createInternalThrowError(Messages.UpdateOperatorSyntaxError, node.operator, node);
throw _this6.createInternalThrowError(Messages.UpdateOperatorSyntaxError, node.operator, node);
}

@@ -604,3 +705,3 @@ };

_proto.objectExpressionHandler = function objectExpressionHandler(node) {
var _this6 = this;
var _this7 = this;

@@ -631,3 +732,3 @@ var items = [];

properties[key][kind] = _this6.createClosure(property.value);
properties[key][kind] = _this7.createClosure(property.value);
items.push({

@@ -678,7 +779,7 @@ key: key,

_proto.arrayExpressionHandler = function arrayExpressionHandler(node) {
var _this7 = this;
var _this8 = this;
//fix: [,,,1,2]
var items = node.elements.map(function (element) {
return element ? _this7.createClosure(element) : element;
return element ? _this8.createClosure(element) : element;
});

@@ -706,3 +807,3 @@ return function () {

_proto.createCallFunctionGetter = function createCallFunctionGetter(node) {
var _this8 = this;
var _this9 = this;

@@ -717,8 +818,14 @@ switch (node.type) {

var func = _this8.safeObjectGet(obj, key, node);
var func = _this9.safeObjectGet(obj, key, node);
if (!func || !isFunction(func)) {
var name = _this8.source.slice(node.start, node.end);
var name = _this9.source.slice(node.start, node.end);
throw _this8.createInternalThrowError(Messages.FunctionUndefinedReferenceError, name, node);
throw _this9.createInternalThrowError(Messages.FunctionUndefinedReferenceError, name, node);
}
if (func.__IS_EVAL_FUNC) {
return function (code) {
return func(code, true);
};
} // method call

@@ -736,9 +843,30 @@ // tips:

default:
// test() or (0.test)() or a[1]() ...
var closure = this.createClosure(node);
return function () {
var name = node.name;
var name = "";
if (node.type === "Identifier") {
name = node.name;
} // const name: string = (<ESTree.Identifier>node).name;
var func = closure();
if (!func || !isFunction(func)) {
throw _this8.createInternalThrowError(Messages.FunctionUndefinedReferenceError, name, node);
throw _this9.createInternalThrowError(Messages.FunctionUndefinedReferenceError, name, node);
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
// calling eval scope check
// var geval = eval;
// geval("a+1");
if (node.type === "Identifier" && func.__IS_EVAL_FUNC) {
return function (code) {
var scope = _this9.getScopeFromName(name, _this9.getCurrentScope());
var isSuperScope = !scope.parent || _this9.rootScope === scope; // use local scope if calling eval in super scope
return func(code, !isSuperScope);
};
} // function call

@@ -757,7 +885,7 @@ // this = undefined

_proto.callExpressionHandler = function callExpressionHandler(node) {
var _this9 = this;
var _this10 = this;
var funcGetter = this.createCallFunctionGetter(node.callee);
var argsGetter = node.arguments.map(function (arg) {
return _this9.createClosure(arg);
return _this10.createClosure(arg);
});

@@ -773,3 +901,3 @@ return function () {

_proto.functionExpressionHandler = function functionExpressionHandler(node) {
var _this10 = this;
var _this11 = this;

@@ -784,3 +912,3 @@ var self = this;

var paramsGetter = node.params.map(function (param) {
return _this10.createParamNameGetter(param);
return _this11.createParamNameGetter(param);
}); // set scope

@@ -798,4 +926,4 @@

var func = function func() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}

@@ -846,3 +974,3 @@

value: function value() {
return _this10.source.slice(node.start, node.end);
return _this11.source.slice(node.start, node.end);
},

@@ -855,3 +983,3 @@ writable: true,

value: function value() {
return _this10.source.slice(node.start, node.end);
return _this11.source.slice(node.start, node.end);
},

@@ -868,7 +996,7 @@ writable: true,

_proto.newExpressionHandler = function newExpressionHandler(node) {
var _this11 = this;
var _this12 = this;
var expression = this.createClosure(node.callee);
var args = node.arguments.map(function (arg) {
return _this11.createClosure(arg);
return _this12.createClosure(arg);
});

@@ -881,5 +1009,5 @@ return function () {

var name = _this11.source.slice(callee.start, callee.end);
var name = _this12.source.slice(callee.start, callee.end);
throw _this11.createInternalThrowError(Messages.IsNotConstructor, name, node);
throw _this12.createInternalThrowError(Messages.IsNotConstructor, name, node);
}

@@ -906,6 +1034,6 @@

_proto.thisExpressionHandler = function thisExpressionHandler(node) {
var _this12 = this;
var _this13 = this;
return function () {
return _this12.getCurrentContext();
return _this13.getCurrentContext();
};

@@ -916,6 +1044,6 @@ } // var1,var2,...

_proto.sequenceExpressionHandler = function sequenceExpressionHandler(node) {
var _this13 = this;
var _this14 = this;
var expressions = node.expressions.map(function (item) {
return _this13.createClosure(item);
return _this14.createClosure(item);
});

@@ -948,10 +1076,10 @@ return function () {

_proto.identifierHandler = function identifierHandler(node) {
var _this14 = this;
var _this15 = this;
return function () {
var currentScope = _this14.getCurrentScope();
var currentScope = _this15.getCurrentScope();
var data = _this14.getScopeDataFromName(node.name, currentScope);
var data = _this15.getScopeDataFromName(node.name, currentScope);
_this14.assertVariable(data, node.name, node);
_this15.assertVariable(data, node.name, node);

@@ -964,3 +1092,3 @@ return data[node.name];

_proto.assignmentExpressionHandler = function assignmentExpressionHandler(node) {
var _this15 = this;
var _this16 = this;

@@ -986,3 +1114,3 @@ // var s = function(){}

// var1(undefined) += 1
_this15.assertVariable(data, name, node);
_this16.assertVariable(data, name, node);
}

@@ -1046,3 +1174,3 @@

default:
throw _this15.createInternalThrowError(Messages.AssignmentExpressionSyntaxError, node.type, node);
throw _this16.createInternalThrowError(Messages.AssignmentExpressionSyntaxError, node.type, node);
}

@@ -1084,3 +1212,3 @@

_proto.variableDeclarationHandler = function variableDeclarationHandler(node) {
var _this16 = this;
var _this17 = this;

@@ -1113,5 +1241,5 @@ var assignmentsClosure;

if (assignmentsClosure) {
_this16.isVarDeclMode = true;
_this17.isVarDeclMode = true;
assignmentsClosure();
_this16.isVarDeclMode = false;
_this17.isVarDeclMode = false;
}

@@ -1124,3 +1252,3 @@

_proto.assertVariable = function assertVariable(data, name, node) {
if (data === this.rootScope.data && name !== "undefined" && !(name in data)) {
if (data === this.rootScope.data && !(name in data)) {
throw this.createInternalThrowError(Messages.VariableUndefinedReferenceError, name, node);

@@ -1132,3 +1260,3 @@ }

_proto.programHandler = function programHandler(node) {
var _this17 = this;
var _this18 = this;

@@ -1138,3 +1266,3 @@ // const currentScope = this.getCurrentScope();

// if (stmt.type === "EmptyStatement") return null;
return _this17.createClosure(stmt);
return _this18.createClosure(stmt);
});

@@ -1147,3 +1275,3 @@ return function () {

var ret = _this17.setValue(stmtClosure()); // if (!stmtClosure) continue;
var ret = _this18.setValue(stmtClosure()); // if (!stmtClosure) continue;
// EmptyStatement

@@ -1206,3 +1334,3 @@

_proto.forStatementHandler = function forStatementHandler(node) {
var _this18 = this;
var _this19 = this;

@@ -1233,3 +1361,3 @@ var initClosure = noop;

var ret = _this18.setValue(bodyClosure()); // notice: never return Break or Continue!
var ret = _this19.setValue(bodyClosure()); // notice: never return Break or Continue!

@@ -1269,3 +1397,3 @@

_proto.forInStatementHandler = function forInStatementHandler(node) {
var _this19 = this;
var _this20 = this;

@@ -1300,3 +1428,3 @@ // for( k in obj) or for(o.k in obj) ...

// o.k = x
_this19.assignmentExpressionHandler({
_this20.assignmentExpressionHandler({
type: "AssignmentExpression",

@@ -1312,3 +1440,3 @@ operator: "=",

var ret = _this19.setValue(bodyClosure()); // Important: never return Break or Continue!
var ret = _this20.setValue(bodyClosure()); // Important: never return Break or Continue!

@@ -1339,3 +1467,3 @@

_proto.withStatementHandler = function withStatementHandler(node) {
var _this20 = this;
var _this21 = this;

@@ -1345,3 +1473,3 @@ var objectClosure = this.createClosure(node.object);

return function () {
var currentScope = _this20.getCurrentScope();
var currentScope = _this21.getCurrentScope();

@@ -1356,8 +1484,8 @@ var newScope = createScope(currentScope, "with");

_this20.setCurrentScope(newScope); // save last value
_this21.setCurrentScope(newScope); // save last value
var result = _this20.setValue(bodyClosure());
var result = _this21.setValue(bodyClosure());
_this20.setCurrentScope(currentScope);
_this21.setCurrentScope(currentScope);

@@ -1377,3 +1505,3 @@ return result;

_proto.tryStatementHandler = function tryStatementHandler(node) {
var _this21 = this;
var _this22 = this;

@@ -1384,9 +1512,9 @@ var blockClosure = this.createClosure(node.block);

return function () {
var currentScope = _this21.getCurrentScope();
var currentScope = _this22.getCurrentScope();
var currentContext = _this21.getCurrentContext();
var currentContext = _this22.getCurrentContext();
var labelStack = currentScope.labelStack.concat([]);
var callStack = _this21.callStack.concat([]);
var callStack = _this22.callStack.concat([]);

@@ -1398,6 +1526,6 @@ var result = EmptyStatementReturn;

var reset = function reset() {
_this21.setCurrentScope(currentScope); //reset scope
_this22.setCurrentScope(currentScope); //reset scope
_this21.setCurrentContext(currentContext); //reset context
_this22.setCurrentContext(currentContext); //reset context

@@ -1407,3 +1535,3 @@

_this21.callStack = callStack; //reset call stack
_this22.callStack = callStack; //reset call stack
};

@@ -1423,3 +1551,3 @@ /**

try {
result = _this21.setValue(blockClosure());
result = _this22.setValue(blockClosure());

@@ -1432,3 +1560,3 @@ if (result instanceof Return) {

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1439,3 +1567,3 @@ }

try {
result = _this21.setValue(handlerClosure(err));
result = _this22.setValue(handlerClosure(err));

@@ -1448,3 +1576,3 @@ if (result instanceof Return) {

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1472,3 +1600,3 @@ } // save catch throw error

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1498,3 +1626,3 @@ } // save finally throw error

_proto.catchClauseHandler = function catchClauseHandler(node) {
var _this22 = this;
var _this23 = this;

@@ -1506,3 +1634,3 @@ var paramNameGetter = this.createParamNameGetter(node.param);

var currentScope = _this22.getCurrentScope();
var currentScope = _this23.getCurrentScope();

@@ -1545,7 +1673,7 @@ var scopeData = currentScope.data; // get param name "e"

_proto.switchStatementHandler = function switchStatementHandler(node) {
var _this23 = this;
var _this24 = this;
var discriminantClosure = this.createClosure(node.discriminant);
var caseClosures = node.cases.map(function (item) {
return _this23.switchCaseHandler(item);
return _this24.switchCaseHandler(item);
});

@@ -1569,3 +1697,3 @@ return function () {

match = true;
ret = _this23.setValue(item.bodyClosure()); // notice: never return Break!
ret = _this24.setValue(item.bodyClosure()); // notice: never return Break!

@@ -1587,3 +1715,3 @@ if (ret === EmptyStatementReturn) continue;

if (!match && defaultCase) {
ret = _this23.setValue(defaultCase.bodyClosure());
ret = _this24.setValue(defaultCase.bodyClosure());
var isEBC = ret === EmptyStatementReturn || ret === Break || ret === Continue; // notice: never return Break or Continue!

@@ -1618,3 +1746,3 @@

_proto.labeledStatementHandler = function labeledStatementHandler(node) {
var _this24 = this;
var _this25 = this;

@@ -1626,3 +1754,3 @@ var labelName = node.label.name;

var currentScope = _this24.getCurrentScope();
var currentScope = _this25.getCurrentScope();

@@ -1685,3 +1813,3 @@ currentScope.labelStack.push(labelName);

_proto.createObjectGetter = function createObjectGetter(node) {
var _this25 = this;
var _this26 = this;

@@ -1691,3 +1819,3 @@ switch (node.type) {

return function () {
return _this25.getScopeDataFromName(node.name, _this25.getCurrentScope());
return _this26.getScopeDataFromName(node.name, _this26.getCurrentScope());
};

@@ -1737,5 +1865,5 @@

for (var _key2 in declVars) {
if (!(_key2 in scopeData)) {
scopeData[_key2] = void 0;
for (var _key3 in declVars) {
if (!(_key3 in scopeData)) {
scopeData[_key3] = void 0;
}

@@ -1758,3 +1886,4 @@ }

do {
if (hasOwnProperty.call(scope.data, name)) {
if (name in scope.data) {
//if (hasOwnProperty.call(scope.data, name)) {
return scope;

@@ -1792,4 +1921,8 @@ }

}();
Interpreter.version = "1.0.9";
Interpreter.version = "1.1.0";
Interpreter.eval = IEval;
Interpreter.Function = IFunction; // alert.call(rootContext, 1);
// But alert({}, 1); // Illegal invocation
Interpreter.rootContext = void 0;
Interpreter.global = getGlobal();
Interpreter.global = Object.create(null);
import { VMContext, CompileOptions, ScriptOptions } from "./types";
export declare function createContext(ctx?: VMContext): VMContext;
export declare function compileFunction(code: string, params?: string[], options?: CompileOptions): (...args: any[]) => any;
export declare function compileFunction(code: string, params?: string[], options?: CompileOptions): (...args: string[]) => any;
export declare function runInContext(code: string, ctx?: VMContext, options?: ScriptOptions): any;

@@ -5,0 +5,0 @@ export declare const runInNewContext: typeof runInContext;

@@ -1,1 +0,1 @@

export default function (...args: string[]): (...args: any[]) => any;
export default function (...args: string[]): (...args: string[]) => any;

@@ -16,2 +16,3 @@ import { MessageItem } from "./messages";

timeout?: number;
initEnv?: (inst: Interpreter) => void;
}

@@ -21,3 +22,6 @@ interface CollectDeclarations {

}
declare type ScopeData = {};
declare type ScopeData = {
[prop: string]: any;
[prop: number]: any;
};
declare class Scope {

@@ -30,5 +34,8 @@ name: string | undefined;

}
declare type Context = {};
declare type Context = {
[prop: string]: any;
[prop: number]: any;
};
export declare class Interpreter {
context: Context;
context: Context | Scope;
value: any;

@@ -49,10 +56,13 @@ rootContext: Context;

protected execEndTime: number;
static version: string;
static readonly version = "1.1.0";
static readonly eval: symbol;
static readonly Function: symbol;
static rootContext: undefined;
static global: any;
constructor(context?: Context, options?: Options);
constructor(context?: Context | Scope, options?: Options);
isInterruptThrow<T>(err: T): boolean;
getSuperScope(): Scope;
protected setCurrentContext(ctx: Context): void;
protected setCurrentScope(scope: Scope): void;
protected initEnvironment(ctx: Context): void;
protected initEnvironment(ctx: Context | Scope): void;
evaluate(code?: string, ctx?: Context): any;

@@ -59,0 +69,0 @@ evaluateNode(node: ESTree.Program, source?: string, ctx?: Context): any;

@@ -30,2 +30,4 @@ "use strict";

var EmptyStatementReturn = Symbol("EmptyStatementReturn");
var IEval = Symbol("IEval");
var IFunction = Symbol("IFunction");

@@ -61,22 +63,2 @@ function isFunction(func) {

function getGlobal() {
if (typeof self !== "undefined") {
return self;
}
if (typeof window !== "undefined") {
return window;
}
if (typeof global !== "undefined") {
return global;
}
if (typeof this !== "undefined") {
return this;
}
return {};
}
function createScope(parent, name) {

@@ -87,5 +69,3 @@ if (parent === void 0) {

return new Scope({}
/* or Object.create(null)? */
, parent, name);
return new Scope(Object.create(null), parent, name);
}

@@ -110,3 +90,4 @@

this.options = {
timeout: options.timeout || 0
timeout: options.timeout || 0,
initEnv: options.initEnv
};

@@ -123,2 +104,101 @@ this.context = context;

_proto.getSuperScope = function getSuperScope() {
var _this = this;
var data = {
NaN: NaN,
Infinity: Infinity,
undefined: undefined,
// null,
Object: Object,
Array: Array,
String: String,
Boolean: Boolean,
Number: Number,
Date: Date,
RegExp: RegExp,
Error: Error,
TypeError: TypeError,
Math: Math,
parseInt: parseInt,
parseFloat: parseFloat,
isNaN: isNaN,
isFinite: isFinite,
decodeURI: decodeURI,
decodeURIComponent: decodeURIComponent,
encodeURI: encodeURI,
encodeURIComponent: encodeURIComponent,
escape: escape,
unescape: unescape
};
data.eval = function (code, useGlobalScope) {
if (useGlobalScope === void 0) {
useGlobalScope = true;
}
if (typeof code !== "string") return code;
if (!code) return void 0;
var options = {
timeout: _this.options.timeout,
initEnv: function initEnv(inst) {
// set caller context
if (!useGlobalScope) {
inst.setCurrentContext(_this.getCurrentContext());
}
inst.execStartTime = _this.execStartTime;
inst.execEndTime = inst.execStartTime;
}
};
var currentScope = useGlobalScope ? _this.rootScope : _this.getCurrentScope();
var interpreter = new Interpreter(currentScope, options);
return interpreter.evaluate(code);
};
Object.defineProperty(data.eval, "__IS_EVAL_FUNC", {
value: true,
writable: false,
enumerable: false,
configurable: false
});
data.Function = function () {
for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
var code = params.pop();
var interpreter = new Interpreter(_this.rootScope, _this.options);
var wrapCode = "\n\t\t (function anonymous(" + params.join(",") + "){\n\t\t " + code + "\n\t\t });\n\t\t ";
return interpreter.evaluate(wrapCode);
};
Object.defineProperty(data.Function, "__IS_FUNCTION_FUNC", {
value: true,
writable: false,
enumerable: false,
configurable: false
}); // ES5 Object
if (typeof JSON !== "undefined") {
data.JSON = JSON;
} //ES6 Object
// if (typeof Promise !== "undefined") {
// data.Promise = Promise;
// }
// if (typeof Set !== "undefined") {
// data.Set = Set;
// }
// if (typeof Map !== "undefined") {
// data.Map = Map;
// }
// if (typeof Symbol !== "undefined") {
// data.Symbol = Symbol;
// }
return new Scope(data, null, "root");
};
_proto.setCurrentContext = function setCurrentContext(ctx) {

@@ -133,8 +213,24 @@ this.currentContext = ctx;

_proto.initEnvironment = function initEnvironment(ctx) {
//init global scope
this.rootScope = new Scope(ctx, null, "root");
var superScope = this.getSuperScope();
if (!(ctx instanceof Scope)) {
// replace Interpreter.eval and Interpreter.Function
Object.keys(ctx).forEach(function (key) {
if (ctx[key] === IEval) {
ctx[key] = superScope.data.eval;
}
if (ctx[key] === IFunction) {
ctx[key] = superScope.data.Function;
}
});
} //init global scope
var scope = ctx instanceof Scope ? ctx : new Scope(ctx, superScope, "global");
this.rootScope = scope;
this.currentScope = this.rootScope; //init global context == this
this.rootContext = ctx;
this.currentContext = ctx; // collect var/function declare
this.rootContext = scope.data;
this.currentContext = scope.data; // collect var/function declare

@@ -145,2 +241,7 @@ this.collectDeclVars = Object.create(null);

this.execEndTime = this.execStartTime;
var initEnv = this.options.initEnv;
if (initEnv) {
initEnv(this);
}
};

@@ -246,3 +347,3 @@

_proto.createClosure = function createClosure(node) {
var _this = this;
var _this2 = this;

@@ -400,7 +501,7 @@ var timeout = this.options.timeout;

return function () {
if (_this.checkTimeout()) {
throw _this.createInternalThrowError(_messages.Messages.ExecutionTimeOutError, timeout, node);
if (_this2.checkTimeout()) {
throw _this2.createInternalThrowError(_messages.Messages.ExecutionTimeOutError, timeout, node);
}
_this.lastExecNode = node;
_this2.lastExecNode = node;
return closure.apply(void 0, arguments);

@@ -411,3 +512,3 @@ };

return function () {
_this.lastExecNode = node;
_this2.lastExecNode = node;
return closure.apply(void 0, arguments);

@@ -419,3 +520,3 @@ };

_proto.binaryExpressionHandler = function binaryExpressionHandler(node) {
var _this2 = this;
var _this3 = this;

@@ -496,3 +597,3 @@ var leftExpression = this.createClosure(node.left);

default:
throw _this2.createInternalThrowError(_messages.Messages.BinaryOperatorSyntaxError, node.operator, node);
throw _this3.createInternalThrowError(_messages.Messages.BinaryOperatorSyntaxError, node.operator, node);
}

@@ -504,3 +605,3 @@ };

_proto.logicalExpressionHandler = function logicalExpressionHandler(node) {
var _this3 = this;
var _this4 = this;

@@ -518,3 +619,3 @@ var leftExpression = this.createClosure(node.left);

default:
throw _this3.createInternalThrowError(_messages.Messages.LogicalOperatorSyntaxError, node.operator, node);
throw _this4.createInternalThrowError(_messages.Messages.LogicalOperatorSyntaxError, node.operator, node);
}

@@ -526,3 +627,3 @@ };

_proto.unaryExpressionHandler = function unaryExpressionHandler(node) {
var _this4 = this;
var _this5 = this;

@@ -578,3 +679,3 @@ switch (node.operator) {

default:
throw _this4.createInternalThrowError(_messages.Messages.UnaryOperatorSyntaxError, node.operator, node);
throw _this5.createInternalThrowError(_messages.Messages.UnaryOperatorSyntaxError, node.operator, node);
}

@@ -587,3 +688,3 @@ };

_proto.updateExpressionHandler = function updateExpressionHandler(node) {
var _this5 = this;
var _this6 = this;

@@ -596,3 +697,3 @@ var objectGetter = this.createObjectGetter(node.argument);

_this5.assertVariable(obj, name, node);
_this6.assertVariable(obj, name, node);

@@ -607,3 +708,3 @@ switch (node.operator) {

default:
throw _this5.createInternalThrowError(_messages.Messages.UpdateOperatorSyntaxError, node.operator, node);
throw _this6.createInternalThrowError(_messages.Messages.UpdateOperatorSyntaxError, node.operator, node);
}

@@ -615,3 +716,3 @@ };

_proto.objectExpressionHandler = function objectExpressionHandler(node) {
var _this6 = this;
var _this7 = this;

@@ -642,3 +743,3 @@ var items = [];

properties[key][kind] = _this6.createClosure(property.value);
properties[key][kind] = _this7.createClosure(property.value);
items.push({

@@ -689,7 +790,7 @@ key: key,

_proto.arrayExpressionHandler = function arrayExpressionHandler(node) {
var _this7 = this;
var _this8 = this;
//fix: [,,,1,2]
var items = node.elements.map(function (element) {
return element ? _this7.createClosure(element) : element;
return element ? _this8.createClosure(element) : element;
});

@@ -717,3 +818,3 @@ return function () {

_proto.createCallFunctionGetter = function createCallFunctionGetter(node) {
var _this8 = this;
var _this9 = this;

@@ -728,8 +829,14 @@ switch (node.type) {

var func = _this8.safeObjectGet(obj, key, node);
var func = _this9.safeObjectGet(obj, key, node);
if (!func || !isFunction(func)) {
var name = _this8.source.slice(node.start, node.end);
var name = _this9.source.slice(node.start, node.end);
throw _this8.createInternalThrowError(_messages.Messages.FunctionUndefinedReferenceError, name, node);
throw _this9.createInternalThrowError(_messages.Messages.FunctionUndefinedReferenceError, name, node);
}
if (func.__IS_EVAL_FUNC) {
return function (code) {
return func(code, true);
};
} // method call

@@ -747,9 +854,30 @@ // tips:

default:
// test() or (0.test)() or a[1]() ...
var closure = this.createClosure(node);
return function () {
var name = node.name;
var name = "";
if (node.type === "Identifier") {
name = node.name;
} // const name: string = (<ESTree.Identifier>node).name;
var func = closure();
if (!func || !isFunction(func)) {
throw _this8.createInternalThrowError(_messages.Messages.FunctionUndefinedReferenceError, name, node);
throw _this9.createInternalThrowError(_messages.Messages.FunctionUndefinedReferenceError, name, node);
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
// calling eval scope check
// var geval = eval;
// geval("a+1");
if (node.type === "Identifier" && func.__IS_EVAL_FUNC) {
return function (code) {
var scope = _this9.getScopeFromName(name, _this9.getCurrentScope());
var isSuperScope = !scope.parent || _this9.rootScope === scope; // use local scope if calling eval in super scope
return func(code, !isSuperScope);
};
} // function call

@@ -768,7 +896,7 @@ // this = undefined

_proto.callExpressionHandler = function callExpressionHandler(node) {
var _this9 = this;
var _this10 = this;
var funcGetter = this.createCallFunctionGetter(node.callee);
var argsGetter = node.arguments.map(function (arg) {
return _this9.createClosure(arg);
return _this10.createClosure(arg);
});

@@ -784,3 +912,3 @@ return function () {

_proto.functionExpressionHandler = function functionExpressionHandler(node) {
var _this10 = this;
var _this11 = this;

@@ -795,3 +923,3 @@ var self = this;

var paramsGetter = node.params.map(function (param) {
return _this10.createParamNameGetter(param);
return _this11.createParamNameGetter(param);
}); // set scope

@@ -809,4 +937,4 @@

var func = function func() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}

@@ -857,3 +985,3 @@

value: function value() {
return _this10.source.slice(node.start, node.end);
return _this11.source.slice(node.start, node.end);
},

@@ -866,3 +994,3 @@ writable: true,

value: function value() {
return _this10.source.slice(node.start, node.end);
return _this11.source.slice(node.start, node.end);
},

@@ -879,7 +1007,7 @@ writable: true,

_proto.newExpressionHandler = function newExpressionHandler(node) {
var _this11 = this;
var _this12 = this;
var expression = this.createClosure(node.callee);
var args = node.arguments.map(function (arg) {
return _this11.createClosure(arg);
return _this12.createClosure(arg);
});

@@ -892,5 +1020,5 @@ return function () {

var name = _this11.source.slice(callee.start, callee.end);
var name = _this12.source.slice(callee.start, callee.end);
throw _this11.createInternalThrowError(_messages.Messages.IsNotConstructor, name, node);
throw _this12.createInternalThrowError(_messages.Messages.IsNotConstructor, name, node);
}

@@ -917,6 +1045,6 @@

_proto.thisExpressionHandler = function thisExpressionHandler(node) {
var _this12 = this;
var _this13 = this;
return function () {
return _this12.getCurrentContext();
return _this13.getCurrentContext();
};

@@ -927,6 +1055,6 @@ } // var1,var2,...

_proto.sequenceExpressionHandler = function sequenceExpressionHandler(node) {
var _this13 = this;
var _this14 = this;
var expressions = node.expressions.map(function (item) {
return _this13.createClosure(item);
return _this14.createClosure(item);
});

@@ -959,10 +1087,10 @@ return function () {

_proto.identifierHandler = function identifierHandler(node) {
var _this14 = this;
var _this15 = this;
return function () {
var currentScope = _this14.getCurrentScope();
var currentScope = _this15.getCurrentScope();
var data = _this14.getScopeDataFromName(node.name, currentScope);
var data = _this15.getScopeDataFromName(node.name, currentScope);
_this14.assertVariable(data, node.name, node);
_this15.assertVariable(data, node.name, node);

@@ -975,3 +1103,3 @@ return data[node.name];

_proto.assignmentExpressionHandler = function assignmentExpressionHandler(node) {
var _this15 = this;
var _this16 = this;

@@ -997,3 +1125,3 @@ // var s = function(){}

// var1(undefined) += 1
_this15.assertVariable(data, name, node);
_this16.assertVariable(data, name, node);
}

@@ -1057,3 +1185,3 @@

default:
throw _this15.createInternalThrowError(_messages.Messages.AssignmentExpressionSyntaxError, node.type, node);
throw _this16.createInternalThrowError(_messages.Messages.AssignmentExpressionSyntaxError, node.type, node);
}

@@ -1095,3 +1223,3 @@

_proto.variableDeclarationHandler = function variableDeclarationHandler(node) {
var _this16 = this;
var _this17 = this;

@@ -1124,5 +1252,5 @@ var assignmentsClosure;

if (assignmentsClosure) {
_this16.isVarDeclMode = true;
_this17.isVarDeclMode = true;
assignmentsClosure();
_this16.isVarDeclMode = false;
_this17.isVarDeclMode = false;
}

@@ -1135,3 +1263,3 @@

_proto.assertVariable = function assertVariable(data, name, node) {
if (data === this.rootScope.data && name !== "undefined" && !(name in data)) {
if (data === this.rootScope.data && !(name in data)) {
throw this.createInternalThrowError(_messages.Messages.VariableUndefinedReferenceError, name, node);

@@ -1143,3 +1271,3 @@ }

_proto.programHandler = function programHandler(node) {
var _this17 = this;
var _this18 = this;

@@ -1149,3 +1277,3 @@ // const currentScope = this.getCurrentScope();

// if (stmt.type === "EmptyStatement") return null;
return _this17.createClosure(stmt);
return _this18.createClosure(stmt);
});

@@ -1158,3 +1286,3 @@ return function () {

var ret = _this17.setValue(stmtClosure()); // if (!stmtClosure) continue;
var ret = _this18.setValue(stmtClosure()); // if (!stmtClosure) continue;
// EmptyStatement

@@ -1217,3 +1345,3 @@

_proto.forStatementHandler = function forStatementHandler(node) {
var _this18 = this;
var _this19 = this;

@@ -1244,3 +1372,3 @@ var initClosure = noop;

var ret = _this18.setValue(bodyClosure()); // notice: never return Break or Continue!
var ret = _this19.setValue(bodyClosure()); // notice: never return Break or Continue!

@@ -1280,3 +1408,3 @@

_proto.forInStatementHandler = function forInStatementHandler(node) {
var _this19 = this;
var _this20 = this;

@@ -1311,3 +1439,3 @@ // for( k in obj) or for(o.k in obj) ...

// o.k = x
_this19.assignmentExpressionHandler({
_this20.assignmentExpressionHandler({
type: "AssignmentExpression",

@@ -1323,3 +1451,3 @@ operator: "=",

var ret = _this19.setValue(bodyClosure()); // Important: never return Break or Continue!
var ret = _this20.setValue(bodyClosure()); // Important: never return Break or Continue!

@@ -1350,3 +1478,3 @@

_proto.withStatementHandler = function withStatementHandler(node) {
var _this20 = this;
var _this21 = this;

@@ -1356,3 +1484,3 @@ var objectClosure = this.createClosure(node.object);

return function () {
var currentScope = _this20.getCurrentScope();
var currentScope = _this21.getCurrentScope();

@@ -1367,8 +1495,8 @@ var newScope = createScope(currentScope, "with");

_this20.setCurrentScope(newScope); // save last value
_this21.setCurrentScope(newScope); // save last value
var result = _this20.setValue(bodyClosure());
var result = _this21.setValue(bodyClosure());
_this20.setCurrentScope(currentScope);
_this21.setCurrentScope(currentScope);

@@ -1388,3 +1516,3 @@ return result;

_proto.tryStatementHandler = function tryStatementHandler(node) {
var _this21 = this;
var _this22 = this;

@@ -1395,9 +1523,9 @@ var blockClosure = this.createClosure(node.block);

return function () {
var currentScope = _this21.getCurrentScope();
var currentScope = _this22.getCurrentScope();
var currentContext = _this21.getCurrentContext();
var currentContext = _this22.getCurrentContext();
var labelStack = currentScope.labelStack.concat([]);
var callStack = _this21.callStack.concat([]);
var callStack = _this22.callStack.concat([]);

@@ -1409,6 +1537,6 @@ var result = EmptyStatementReturn;

var reset = function reset() {
_this21.setCurrentScope(currentScope); //reset scope
_this22.setCurrentScope(currentScope); //reset scope
_this21.setCurrentContext(currentContext); //reset context
_this22.setCurrentContext(currentContext); //reset context

@@ -1418,3 +1546,3 @@

_this21.callStack = callStack; //reset call stack
_this22.callStack = callStack; //reset call stack
};

@@ -1434,3 +1562,3 @@ /**

try {
result = _this21.setValue(blockClosure());
result = _this22.setValue(blockClosure());

@@ -1443,3 +1571,3 @@ if (result instanceof Return) {

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1450,3 +1578,3 @@ }

try {
result = _this21.setValue(handlerClosure(err));
result = _this22.setValue(handlerClosure(err));

@@ -1459,3 +1587,3 @@ if (result instanceof Return) {

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1483,3 +1611,3 @@ } // save catch throw error

if (_this21.isInterruptThrow(err)) {
if (_this22.isInterruptThrow(err)) {
throw err;

@@ -1509,3 +1637,3 @@ } // save finally throw error

_proto.catchClauseHandler = function catchClauseHandler(node) {
var _this22 = this;
var _this23 = this;

@@ -1517,3 +1645,3 @@ var paramNameGetter = this.createParamNameGetter(node.param);

var currentScope = _this22.getCurrentScope();
var currentScope = _this23.getCurrentScope();

@@ -1556,7 +1684,7 @@ var scopeData = currentScope.data; // get param name "e"

_proto.switchStatementHandler = function switchStatementHandler(node) {
var _this23 = this;
var _this24 = this;
var discriminantClosure = this.createClosure(node.discriminant);
var caseClosures = node.cases.map(function (item) {
return _this23.switchCaseHandler(item);
return _this24.switchCaseHandler(item);
});

@@ -1580,3 +1708,3 @@ return function () {

match = true;
ret = _this23.setValue(item.bodyClosure()); // notice: never return Break!
ret = _this24.setValue(item.bodyClosure()); // notice: never return Break!

@@ -1598,3 +1726,3 @@ if (ret === EmptyStatementReturn) continue;

if (!match && defaultCase) {
ret = _this23.setValue(defaultCase.bodyClosure());
ret = _this24.setValue(defaultCase.bodyClosure());
var isEBC = ret === EmptyStatementReturn || ret === Break || ret === Continue; // notice: never return Break or Continue!

@@ -1629,3 +1757,3 @@

_proto.labeledStatementHandler = function labeledStatementHandler(node) {
var _this24 = this;
var _this25 = this;

@@ -1637,3 +1765,3 @@ var labelName = node.label.name;

var currentScope = _this24.getCurrentScope();
var currentScope = _this25.getCurrentScope();

@@ -1696,3 +1824,3 @@ currentScope.labelStack.push(labelName);

_proto.createObjectGetter = function createObjectGetter(node) {
var _this25 = this;
var _this26 = this;

@@ -1702,3 +1830,3 @@ switch (node.type) {

return function () {
return _this25.getScopeDataFromName(node.name, _this25.getCurrentScope());
return _this26.getScopeDataFromName(node.name, _this26.getCurrentScope());
};

@@ -1748,5 +1876,5 @@

for (var _key2 in declVars) {
if (!(_key2 in scopeData)) {
scopeData[_key2] = void 0;
for (var _key3 in declVars) {
if (!(_key3 in scopeData)) {
scopeData[_key3] = void 0;
}

@@ -1769,3 +1897,4 @@ }

do {
if (hasOwnProperty.call(scope.data, name)) {
if (name in scope.data) {
//if (hasOwnProperty.call(scope.data, name)) {
return scope;

@@ -1805,4 +1934,8 @@ }

exports.Interpreter = Interpreter;
Interpreter.version = "1.0.9";
Interpreter.version = "1.1.0";
Interpreter.eval = IEval;
Interpreter.Function = IFunction; // alert.call(rootContext, 1);
// But alert({}, 1); // Illegal invocation
Interpreter.rootContext = void 0;
Interpreter.global = getGlobal();
Interpreter.global = Object.create(null);
import { VMContext, CompileOptions, ScriptOptions } from "./types";
export declare function createContext(ctx?: VMContext): VMContext;
export declare function compileFunction(code: string, params?: string[], options?: CompileOptions): (...args: any[]) => any;
export declare function compileFunction(code: string, params?: string[], options?: CompileOptions): (...args: string[]) => any;
export declare function runInContext(code: string, ctx?: VMContext, options?: ScriptOptions): any;

@@ -5,0 +5,0 @@ export declare const runInNewContext: typeof runInContext;

{
"name": "eval5",
"version": "1.0.9",
"version": "1.1.0",
"description": "A JavaScript interpreter, written completely in JavaScript",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

@@ -5,3 +5,3 @@ # eval5

> 用于解决在不支持`eval`或`Function`的执行环境下执行 JavaScript 代码。例如:各种小程序。
> 解决在不支持`eval`或`Function`的执行环境下执行 JavaScript 代码。例如:微信小程序 [示例](https://github.com/bplok20010/eval5-wx-demo)。

@@ -42,4 +42,6 @@ ## Usage

### `static` global
### static `version`
### static `global`
设置默认作用域对象

@@ -54,2 +56,33 @@

### static `eval`
替代原有的`eval`占位符
> 如果执行环境支持 eval 函数建议使用原生的 eval,除非 eval 需要使用局部变量时,如下情况:
```
const ctx = Object.create(window);
ctx.eval = Interpreter.eval;
const interpreter = new Interpreter(ctx);
interpreter.evaluate(`
function test(){
var a = 1;
return eval('a+1')
}
test();
`); // output 2
```
### static `Function`
替代原有的`Function`占位符
作用同`Interpreter.eval`
> 除非不支持`Function`的环境,否则不建议使用
### `constructor`(ctx: {}, options?: { timeout?: number})

@@ -56,0 +89,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc