`eval` the given source as a CommonJS module, using properties found in `context` as top-level variables.

Based on `vm.runInContext` found in Node.js, this is a cross-env solution.
973252
function evalModule( source, context ) {

    const argumentKeys = Object.keys( context );
    const argumentValues = argumentKeys.map( argument => context[ argument ] );

    const sandbox = { exports: {} };
    argumentKeys.push( "module", "exports", source );
    argumentValues.push( sandbox, sandbox.exports );

    Function( ...argumentKeys )( ...argumentValues );

    return sandbox.exports;

}
1228897
@Override
    public <T> T runScript(final Reader reader, final String sourceName) throws IOException {
        return runWithContext(new RhinoCallable<T, IOException>() {
            @SuppressWarnings("unchecked")
            @Override
            protected T doCall(Context cx, Scriptable scope) throws IOException {
                Object val = cx.evaluateReader(scope, reader, sourceName, 1, null);
                val = unwrappedValue(val);
                return (T) val;
            }
        });
    }
315008
function createJsModule(source) {
    var compilerOptions = {
        compilerOptions: {
            target: ts.ScriptTarget.ES5,
            module: ts.ModuleKind.CommonJS,
            alwaysStrict: false
        }
    };
    var transpiled = ts.transpileModule(source, compilerOptions);
    return transpiled.outputText;
}
1087636
function tryEval (func, context) {
    try {
        return func(context);
    } catch(e) {
        log('warn',
            `Property function in layer '${context.layers[context.layers.length-1]}' failed with\n`,
            `error ${e.stack}\n`,
            `function '${func.source}'\n`,
            context.feature, context);
    }
}
415895
async function _evaluateContexts(contexts = []) {
  const c = Array.isArray(contexts) ? contexts : [contexts]
  const ep = c.map(evaluateContext)
  const res = await Promise.all(ep)
  return res
}
643147
function evaluateAst(tree, context){

  var safeFunction = FunctionFactory(context)
  var primitives = Primitives(context)

  // block scoped context for catch (ex) and 'let'
  var blockContext = context

  return walk(tree)

  // recursively walk every node in an array
  function walkAll(nodes){
    var result = undefined
    for (var i=0;i<nodes.length;i++){
      var childNode = nodes[i]
      if (childNode.type === 'EmptyStatement') continue
      result = walk(childNode)
      if (result instanceof ReturnValue){
        return result
      }
    }
    return result
  }

  // recursively evalutate the node of an AST
  function walk(node){
    if (!node) return

    switch (node.type) {

      case 'Program':
        return walkAll(node.body )

      case 'BlockStatement':
        enterBlock()
        var result = walkAll(node.body)
        leaveBlock()
        return result

      case 'SequenceExpression':
        return walkAll(node.expressions)

      case 'FunctionDeclaration':
        var params = node.params.map(getName)
        var value = getFunction(node.body, params, blockContext)
        return context[node.id.name] = value

      case 'FunctionExpression':
        var params = node.params.map(getName)
        return getFunction(node.body, params, blockContext)

      case 'ReturnStatement':
        var value = walk(node.argument)
        return new ReturnValue('return', value)

      case 'BreakStatement':
        return new ReturnValue('break')

      case 'ContinueStatement':
        return new ReturnValue('continue')

      case 'ExpressionStatement':
        return walk(node.expression)

      case 'AssignmentExpression':
        return setValue(blockContext, node.left, node.right, node.operator)

      case 'UpdateExpression':
        return setValue(blockContext, node.argument, null, node.operator)

      case 'VariableDeclaration':
        node.declarations.forEach(function(declaration){
          var target = node.kind === 'let' ? blockContext : context
          if (declaration.init){
            target[declaration.id.name] = walk(declaration.init)
          } else {
            target[declaration.id.name] = undefined
          }
        })
        break

      case 'SwitchStatement':
        var defaultHandler = null
        var matched = false
        var value = walk(node.discriminant)
        var result = undefined

        enterBlock()

        var i = 0
        while (result == null){
          if (i<node.cases.length){
            if (node.cases[i].test){ // check or fall through
              matched = matched || (walk(node.cases[i].test) === value)
            } else if (defaultHandler == null) {
              defaultHandler = i
            }
            if (matched){
              var r = walkAll(node.cases[i].consequent)
              if (r instanceof ReturnValue){ // break out
                if (r.type == 'break') break
                result = r
              }
            }
            i += 1 // continue
          } else if (!matched && defaultHandler != null){
            // go back and do the default handler
            i = defaultHandler
            matched = true
          } else {
            // nothing we can do
            break
          }
        }

        leaveBlock()
        return result

      case 'IfStatement':
        if (walk(node.test)){
          return walk(node.consequent)
        } else if (node.alternate) {
          return walk(node.alternate)
        }

      case 'ForStatement':
        var infinite = InfiniteChecker(maxIterations)
        var result = undefined

        enterBlock() // allow lets on delarations
        for (walk(node.init); walk(node.test); walk(node.update)){
          var r = walk(node.body)

          // handle early return, continue and break
          if (r instanceof ReturnValue){
            if (r.type == 'continue') continue
            if (r.type == 'break') break
            result = r
            break
          }

          infinite.check()
        }
        leaveBlock()
        return result

      case 'ForInStatement':
        var infinite = InfiniteChecker(maxIterations)
        var result = undefined

        var value = walk(node.right)
        var property = node.left

        var target = context
        enterBlock()

        if (property.type == 'VariableDeclaration'){
          walk(property)
          property = property.declarations[0].id
          if (property.kind === 'let'){
            target = blockContext
          }
        }

        for (var key in value){
          setValue(target, property, {type: 'Literal', value: key})
          var r = walk(node.body)

          // handle early return, continue and break
          if (r instanceof ReturnValue){
            if (r.type == 'continue') continue
            if (r.type == 'break') break
            result = r
            break
          }

          infinite.check()
        }
        leaveBlock()

        return result

      case 'WhileStatement':
        var infinite = InfiniteChecker(maxIterations)
        while (walk(node.test)){
          walk(node.body)
          infinite.check()
        }
        break

      case 'TryStatement':
        try {
          walk(node.block)
        } catch (error) {
          enterBlock()
          var catchClause = node.handlers[0]
          if (catchClause) {
            blockContext[catchClause.param.name] = error
            walk(catchClause.body)
          }
          leaveBlock()
        } finally {
          if (node.finalizer) {
            walk(node.finalizer)
          }
        }
        break

      case 'Literal':
        return node.value

      case 'UnaryExpression':
        var val = walk(node.argument)
        switch(node.operator) {
          case '+': return +val
          case '-': return -val
          case '~': return ~val
          case '!': return !val
          case 'void': return void val
          case 'typeof': return typeof val
          default: return unsupportedExpression(node)
        }

      case 'ArrayExpression':
        var obj = blockContext['Array']()
        for (var i=0;i<node.elements.length;i++){
          obj.push(walk(node.elements[i]))
        }
        return obj

      case 'ObjectExpression':
        var obj = blockContext['Object']()
        for (var i = 0; i < node.properties.length; i++) {
          var prop = node.properties[i]
          var value = (prop.value === null) ? prop.value : walk(prop.value)
          obj[prop.key.value || prop.key.name] = value
        }
        return obj

      case 'NewExpression':
        var args = node.arguments.map(function(arg){
          return walk(arg)
        })
        var target = walk(node.callee)
        return primitives.applyNew(target, args)


      case 'BinaryExpression':
        var l = walk(node.left)
        var r = walk(node.right)

        switch(node.operator) {
          case '==':  return l === r
          case '===': return l === r
          case '!=':  return l != r
          case '!==': return l !== r
          case '+':   return l + r
          case '-':   return l - r
          case '*':   return l * r
          case '/':   return l / r
          case '%':   return l % r
          case '<':   return l < r
          case '<=':  return l <= r
          case '>':   return l > r
          case '>=':  return l >= r
          case '|':   return l | r
          case '&':   return l & r
          case '^':   return l ^ r
          case 'in':  return l in r
          case 'instanceof': return l instanceof r
          default: return unsupportedExpression(node)
        }

      case 'LogicalExpression':
        switch(node.operator) {
          case '&&':  return walk(node.left) && walk(node.right)
          case '||':  return walk(node.left) || walk(node.right)
          default: return unsupportedExpression(node)
        }

      case 'ThisExpression':
        return blockContext['this']

      case 'Identifier':
        if (node.name === 'undefined'){
          return undefined
        } else if (hasProperty(blockContext, node.name, primitives)){
          return finalValue(blockContext[node.name])
        } else {
          throw new ReferenceError(node.name + ' is not defined')
        }

      case 'CallExpression':

        var args = node.arguments.map(function(arg){
          return walk(arg)
        })
        var object = null
        var target = walk(node.callee)

        if (node.callee.type === 'MemberExpression'){
          object = walk(node.callee.object)
        }
        return target.apply(object, args)

      case 'MemberExpression':
        var obj = walk(node.object)
        if (node.computed){
          var prop = walk(node.property)
        } else {
          var prop = node.property.name
        }
        obj = primitives.getPropertyObject(obj, prop)
        return checkValue(obj[prop]);

      case 'ConditionalExpression':
        var val = walk(node.test)
        return val ? walk(node.consequent) : walk(node.alternate)

      case 'EmptyStatement':
        return

      default:
        return unsupportedExpression(node)
    }
  }

  // safely retrieve a value
  function checkValue(value){
    if (value === Function){
      value = safeFunction
    }
    return finalValue(value)
  }

  // block scope context control
  function enterBlock(){
    blockContext = Object.create(blockContext)
  }
  function leaveBlock(){
    blockContext = Object.getPrototypeOf(blockContext)
  }

  // set a value in the specified context if allowed
  function setValue(object, left, right, operator){
    var name = null

    if (left.type === 'Identifier'){
      name = left.name
      // handle parent context shadowing
      object = objectForKey(object, name, primitives)
    } else if (left.type === 'MemberExpression'){
      if (left.computed){
        name = walk(left.property)
      } else {
        name = left.property.name
      }
      object = walk(left.object)
    }

    // stop built in properties from being able to be changed
    if (canSetProperty(object, name, primitives)){
      switch(operator) {
        case undefined: return object[name] = walk(right)
        case '=':  return object[name] = walk(right)
        case '+=': return object[name] += walk(right)
        case '-=': return object[name] -= walk(right)
        case '++': return object[name]++
        case '--': return object[name]--
      }
    }

  }

}
1352559
private Object evalSource(Object source, ScriptContext scriptContext) throws ScriptException {
        try {
            Interpreter bsh = getInterpreter();
            NameSpace contextNameSpace = getEngineNameSpace(scriptContext);
            bsh.setNameSpace(contextNameSpace);

            bsh.setOut(toPrintStream(scriptContext.getWriter()));
            bsh.setErr(toPrintStream(scriptContext.getErrorWriter()));


            if (source instanceof Reader) {
                return bsh.eval((Reader) source);
            } else {
                return bsh.eval((String) source);
            }
        } catch (ParseException e) {
            // explicit parsing error
            throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
        } catch (TargetError e) {
            // The script threw an application level exception
            ScriptException se = new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
            se.initCause(e.getTarget());
            throw se;
        } catch (EvalError e) {
            // The script couldn't be evaluated properly
            throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber());
        } catch (IOException e) {
            throw new ScriptException(e.toString());
        }
    }
360763
function renderModule(context, options) {
	var  cacheKey
		,modSourceTemplate
		,mergedData
		,html
	;

	// this check is used when rendering isolated modules or views for development and testing (in the default layout!).
	// skip any modules that are not THE module or THE view.
	// view: skip all modules that have the attribute _isLayout="true"
	// module: skip all other modules
	if (
		context.skipModules === true ||                         // case: module
		context.skipModules == 'layout' && options._isLayout    // case: view
		)
	{ return ''; }

	options.template = options.template || options.name;
	options.tag = options.tag || defaults.tag;
	options.data = options.data || {};
	options.data.moduleNestingLevel = typeof context.moduleNestingLevel === 'undefined' ? 0 : context.moduleNestingLevel + 1;
	autoIncrementIndent = options.data.moduleNestingLevel > 0 ? 1 : false;
	options.data.indent = options.indent || autoIncrementIndent || context.indent || 0;

	// merge the request context and data in the module include, with the latter trumping the former.
	mergedData = _.merge({}, context, options.data);

	// create a unique identifier for the module/template combination
	cacheKey = options.name + ' ' + options.template;

	// If addTest exists it means we should pass module options into it for later client-side module testing.
	context._locals && context._locals.addTest && context._locals.addTest(options);

	// force reading from disk in development mode
	NODE_ENV == 'development' && (cache[cacheKey] = null);

	// if the module/template combination is cached use it, else read from disk and cache it.
	modSourceTemplate = cache[cacheKey] || (cache[cacheKey] = getModTemplate(options));

	// render the module source in the locally merged context
	// moduleSrc is a {{variable}} in the moduleWrapper template
	try {
		options.moduleSrc = modSourceTemplate.fn(mergedData);
	}
	catch (e) {
		if (process.env.NODE_ENV != 'test') {
			if (e instanceof RenderError)   // if this is our error from a nested template rethrow it.
				throw e;
			else                            // if this is the original Handlebars error, make it useful
				throw new RenderError('Module: ' + options.name + ', Template: ' + options.template + cfg.templateExtension +'\n'+ e.toString().replace(/^Error/, 'Reason'));
		}
	}


	if (options.noWrapper) {
		html = options.moduleSrc;
	}
	else {
		// if we have a persisted read error, add the error class to the module.
		modSourceTemplate.err && (options.classes = options.classes ? options.classes + ' xtc-error' : 'xtc-error');

		if (annotateModules) {
			options._module = modSourceTemplate.name;
			options._file = modSourceTemplate.file;
			options._path = modSourceTemplate.path;
			options._repository = modSourceTemplate.repository;
		}

		// render the wrapper template
		html = wrapperFn(options);
	}

	// manage indentation
	if (mergedData.indent) {
		html = utils.indent(html, mergedData.indent, cfg.indentString);
	}

	return html;
}
769648
function scopeEval(source, scope) {
  var keys = [];
  var values = [];
  for (var key in scope) {
    if (scope.hasOwnProperty(key)) {
      keys.push(key);
      values.push(scope[key]);
    }
  }
  keys.push(source);
  return Function.apply(null, keys).apply(null, values);
}
564031
def safe_eval(source, *args, **kwargs):
    
    source = source.replace('import', '')  # import is not allowed
    return eval(source, *args, **kwargs)
84665
function evaluate(config) {
  const _config = _parseConfig(config);
  const options = _createOptions(_config);
  return _runScript(_config, options);
}
1304852
@Override
	public Value evaluate(String line, Context ctxt) throws Exception
	{
		PExp expr = parseExpression(line, getDefaultName());
		Environment env = new ModuleEnvironment(assistantFactory, defaultModule);

		try
		{
			typeCheck(expr, env);
		} catch (VDMErrorsException e)
		{
			// We don't care... we just needed to type check it.
		}

		ctxt.threadState.init();

		try
		{
			return expr.apply(VdmRuntime.getExpressionEvaluator(), ctxt);
		} catch (Exception e)
		{
			throw e;
		}
	}
958393
def render(self, context):
    ''''''
    modules = {
    }
    context['false'] = False
    context['true'] = True
    new_ctx = eval('dict(%s)'%self.code,modules,context)
    context.update(new_ctx)
    return ''
339172
function processValuesFromContext(node, params, msg, varList) {
                let pMsg = {};
                Object.assign(pMsg, params);
                varList.forEach((varItem) => {
                    if (varItem.type === undefined || params[varItem.type] === undefined) {
                        pMsg[varItem.name] = params[varItem.name];
                    } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') {
                        pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg);
                        pMsg[varItem.type] = params[varItem.type];
                        console.log('Inside flow or global');
                        console.log(varItem.name + ' - - ' + pMsg[varItem.name]);
                    } else {
                        pMsg[varItem.name] = params[varItem.name];
                        pMsg[varItem.type] = params[varItem.type];
                    }
                });
                return pMsg;
            }
186858
function(code, url, done) {
  try {
    require('vm').runInThisContext(code, url)
    done()
  } catch (e) {
    done(e)
  }
}
121653
function globalEval(code) {
        var script;

        code = code.replace(/^\s+/, '').replace(/\s+$/, '');

        if (code) {
            if (code.indexOf('use strict') === 1) {
                script = document.createElement('script');
                script.text = code;
                head.appendChild(script).parentNode.removeChild(script);
            }
            else {
                eval(code);
            }
        }
    }
829658
function optimize (source, path, module)
  {
    var result = sourceTrans.optimize (source, module.name, options.moduleVar);
    var stat = sourceTrans.TRANS_STAT;
    switch (result.status) {

      case stat.OK:

        //----------------------------------------------------------
        // Module already enclosed in a closure with no arguments.
        //----------------------------------------------------------
        return /** @type {OperationResult} */ {
          status: STAT.INDENTED,
          data:   sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar)
        };


      case stat.NO_CLOSURE_FOUND:

        //----------------------------------------------------------
        // Unwrapped source code.
        // It must be validated to make sure it's safe.
        //----------------------------------------------------------
        if (path)
          verboseOut.write ('Validating ' + path.cyan + '...');
        var valid = sourceTrans.validateUnwrappedCode (source);
        if (valid)
        // The code passed validation.
          verboseOut.ok ();
        else {
          verboseOut.writeln ('FAILED'.yellow);
          warnAboutGlobalCode (valid, path);
          // If --force, continue.
        }
        // Either the code is valid or --force was used, so process it.
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleRefExps (module, source, options.moduleVar)
        };


      case stat.RENAME_REQUIRED:

        //----------------------------------------------------------
        // Module already enclosed in a closure, with its reference
        // passed in as the function's argument.
        //----------------------------------------------------------
        /** @type {ModuleClosureInfo} */
        var modInfo = result.data;
        if (!options.renameModuleRefs) {
          warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
            '<cyan>moduleVar=\'%\'</cyan>.%%%',
            modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
            getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
          );
          // If --force, continue.
        }
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar)
        };


      case stat.INVALID_DECLARATION:

        warn ('Wrong module declaration: <cyan>%</cyan>', result.data);
        // If --force, continue.
        break;


      default:
        throw new Error ('Optimize failed. It returned ' + JSON.stringify (result));
    }
    // Optimization failed. Return the unaltered source code.
    return /** @type {OperationResult} */ {status: STAT.OK, data: source};
  }