From b8db835af951bed9e56e515108c0f48f2061935d Mon Sep 17 00:00:00 2001 From: Futago-za Ryuu Date: Thu, 5 Apr 2018 08:16:50 +0100 Subject: [PATCH] Refactor vm.runInContext --- lib/util/vm.js | 60 ++++++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/lib/util/vm.js b/lib/util/vm.js index 3e797ac..28fe03f 100644 --- a/lib/util/vm.js +++ b/lib/util/vm.js @@ -1,48 +1,56 @@ "use strict"; -const VM_VARS = { +const code = ( () => { - "module": true, - "process": true, - "VM_VARS": true, - "PREFACE_VARS": true, - "generateDeclaration": true, - "runInContext": true, - "code": true, - "preface": true, + let preface = ""; + const MODULE_VARS = { -}; + "module": true, + "process": true, + "code": true, + "runInContext": true, + "source": true, + "preface": true, + + }; + + Object.keys( MODULE_VARS ).forEach( name => { + + preface += `var ${ name } = void 0;`; -const PREFACE_VARS = Object.keys( VM_VARS ) - .map( name => `var ${ name } = void 0;` ) - .join( " " ); + } ); -function generateDeclaration( name ) { + function generate( name ) { - return ( ! VM_VARS[ name ] ? "var " : "" ) - + `${ name } = vm$context.${ name };`; + return `${ ( MODULE_VARS[ name ] ? "" : "var " ) + name } = __context.${ name };`; -} + } + + return { generate, preface }; + +} )(); module.exports = { - // `eval` the given code, using properties found in `context` as top-level - // variables, while hiding some variables in this module from the code. + // `eval` the given source, using properties found in `context` as top-level + // variables, while hiding some variables in this module from the source. // // Based on `vm.runInContext` found in Node.js, this is a cross-env solution. - runInContext( code, vm$context ) { + runInContext( source, __context ) { + + let preface = code.preface; + + if ( typeof __context === "object" ) { - let preface = PREFACE_VARS; + Object.keys( __context ).forEach( name => { - if ( typeof vm$context === "object" ) { + preface += code.generate( name ); - preface += Object.keys( vm$context ) - .map( generateDeclaration ) - .join( " " ); + } ); } - return eval( preface + code ); + return eval( preface + source ); },