"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.EvalMachine=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _fs=_interopRequireDefault(require("fs"));
var _path=_interopRequireDefault(require("path"));
var _filesize=_interopRequireDefault(require("filesize"));
var _events=require("events");
var _resolvePackagePath=_interopRequireDefault(require("resolve-package-path"));function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach(function(key){(0,_defineProperty2.default)(target,key,source[key])})}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}}return target}

const RequireController=require("../require");
const objects=require("./objects");let _require=

require("@corenode/utils"),verbosity=_require.verbosity,objectToArrayMap=_require.objectToArrayMap;
const getVerbosity=()=>verbosity.options({method:`[VM]`,time:false});

const builtInModules={
"@babel/runtime":(0,_resolvePackagePath.default)("@babel/runtime")};


class EvalMachine{
constructor(params){var _this$params$id;(0,_defineProperty2.default)(this,"jail",




































































































































































































































{
get:key=>{
return this.context[key];
},
set:(key,value)=>{
this.context[key]=value;
},
del:key=>{
delete this.context[key];
}});this.vmController=require("vm");if(typeof params==="undefined"){params={}}if(typeof params.cwd==="undefined"){params.cwd=process.cwd()}this.params=params;try{if(typeof this.params.eval!=="undefined"){if(_fs.default.existsSync(this.params.eval)){this.params.eval=_fs.default.readFileSync(_path.default.resolve(this.params.eval))}}}catch(error){getVerbosity().dump(error);getVerbosity().error(`Cannot check eval file/script > ${error.message}`)}this.address=0;this.allocateNew();this.id=`EvalMachine_${(_this$params$id=this.params.id)!==null&&_this$params$id!==void 0?_this$params$id:this.address}`;this.context={};this.events=new _events.EventEmitter;if(typeof this.params.context!=="undefined"){this.context=_objectSpread(_objectSpread({},this.context),this.params.context)}this.events.on(`destroyVM`,()=>{if(typeof this._sendOnDestroy==="function"){this._sendOnDestroy(this.address)}});const globalNodeModules=this.getNodeModules(process.cwd());const localNodeModules=this.getNodeModules(this.params.cwd);this._modulesRegistry=_objectSpread(_objectSpread(_objectSpread(_objectSpread({},localNodeModules),globalNodeModules),builtInModules),this.params.aliaser);this.jail.set("self",this);this.jail.set("_modulesRegistry",this._modulesRegistry);this.jail.set("cwd",this.params.cwd);this.jail.set("_getProcess",()=>process);this.jail.set("_getRuntime",()=>process.runtime);this.jail.set("global",global);this.jail.set("_import",_module=>require("import-from")(_path.default.resolve(this.params.cwd,"node_modules"),_module));this.jail.set("expose",{});this.jail.set("_createModuleController",()=>{return new RequireController.CustomNodeModuleController(_objectSpread({},this._modulesRegistry))});this.jail.set("log",(...args)=>{const v=verbosity.options({method:`[${this.id}]`});v.log(...args)});if(typeof objects==="object"){objectToArrayMap(objects).forEach(obj=>{this.jail.set(obj.key,obj.value)})}try{const vmtFile=_path.default.resolve(__dirname,"vmt");const vmt=_fs.default.readFileSync(vmtFile,"utf8");this.script=String(vmt);if(typeof this.params.eval!=="undefined"){this.script=this.script+this.params.eval}}catch(error){verbosity.dump(error);throw new Error(`Cannot load VMT file >> ${error.message}`)}this.vmController.createContext(this.context);this.run(this.script)}dispatcher(){let obj={};const exposers=this.context.expose;const keys=Object.keys(exposers);keys.forEach(key=>{switch(typeof exposers[key]){case"function":{obj[key]=(...context)=>{let args=[...context];this.run(`expose.${key}(${args.join()})`)};break}default:{obj[key]=this.run(`expose.${key}`);break}}});return obj}getNodeModules(origin){let obj={};function readDir(from,resolvePath){if(typeof from!=="string"){return false}const directory=resolvePath?_path.default.resolve(from,resolvePath):_path.default.resolve(from);if(!_fs.default.existsSync(directory)){return false}return _fs.default.readdirSync(directory).map(dir=>{return{dir:dir,_path:_path.default.resolve(directory,dir)}})}const node_modules=readDir(origin,`node_modules`);if(Array.isArray(node_modules)){node_modules.forEach(entry=>{const pkg=_path.default.resolve(entry._path,"package.json");if(_fs.default.existsSync(pkg)){obj[entry.dir]=entry._path}})}return obj}allocateNew(){if(typeof process.runtime.vms!=="object"){process.runtime.vms={deep:0,pool:{}}}while(typeof process.runtime.vms.pool[this.address]!=="undefined"){this.address+=1}this.poolRef=process.runtime.vms.pool[this.address]=this;process.runtime.vms.deep=Object.keys(process.runtime.vms.pool).length}run(exec,callback){if(typeof this.vmController==="undefined"){throw new Error(`vmController is not available (maybe destroyed)`)}const vmscript=new this.vmController.Script(exec);const _run=vmscript.runInContext(this.context);if(typeof callback==="function"){callback(_run)}return _run}runSync(){}measureMemory(opts={}){return new Promise((resolve,reject)=>{var _opts$mode,_opts$execution;this.vmController.measureMemory({mode:(_opts$mode=opts===null||opts===void 0?void 0:opts.mode)!==null&&_opts$mode!==void 0?_opts$mode:"detailed",execution:(_opts$execution=opts===null||opts===void 0?void 0:opts.execution)!==null&&_opts$execution!==void 0?_opts$execution:"eager"}).then(result=>{if(opts!==null&&opts!==void 0&&opts.humanize){let total=result.total;total.jsMemoryEstimate=(0,_filesize.default)(total.jsMemoryEstimate);total.jsMemoryRange=[...total.jsMemoryRange.map(range=>(0,_filesize.default)(range))];result.total=total}return resolve(result)}).catch(error=>{getVerbosity().dump(error);getVerbosity().error(error);return reject(`Unavailable`)})})}onDestroy(fn){if(typeof fn!=="function"){throw new Error(`[${typeof fn}] is not an valid type for "onDestroy"`)}this._sendOnDestroy=fn}destroy(){this.events.emit(`destroyVM`);delete this.poolRef;delete process.runtime.vms.pool[this.address];delete this.vmController}}exports.EvalMachine=EvalMachine;