"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));



var _path=_interopRequireDefault(require("path"));
var _fs=_interopRequireDefault(require("fs"));
var _events=require("events");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 _require=

require("./vm/index.js"),EvalMachine=_require.EvalMachine;const _require2=
require("./logger"),Logger=_require2.Logger;let _require3=

require("@corenode/utils"),verbosity=_require3.verbosity,schemizedParse=_require3.schemizedParse;
verbosity=verbosity.options({method:"[RUNTIME]"});

const _environmentFiles=[".corenode",".corenode.js",".corenode.ts",".corenode.json"];
class CoreEvents extends _events.EventEmitter{
constructor(){
super({captureRejections:true});
}

[_events.captureRejectionSymbol](err,event,...args){
console.log("rejection happened for",event,"with",err,...args);
this.destroy(err);
}

destroy(err){

}}


class Runtime{
constructor(load,options){(0,_defineProperty2.default)(this,"get",



































{
environmentFiles:()=>_environmentFiles,
paths:{
_env:()=>_path.default.resolve(process.cwd(),".corenode"),
_src:()=>_path.default.resolve(__dirname,".."),
_root:()=>_path.default.resolve(__dirname,"../../..")}});this.isMain=require.main===module;this.runParams={load,options};this.opts=this.runParams.options;if(this.opts.cwd){process.chdir(this.opts.cwd)}if(this.opts.args){process.args=this.opts.args}if(this.opts.argv){process.argv=this.opts.argv}if(typeof global._inited==="undefined"){global._inited=false}if(typeof process.runtime!=="object"){process.runtime={}}this.controller={};this.helpers=require("./helpers");this.thread=0;this.modules=null;this.events=new CoreEvents;this.logger=new Logger;this.setEvents();this.init()}



appendToController(key,value,options){var _options$configurable,_options$enumerable;
let properties={
configurable:(_options$configurable=options===null||options===void 0?void 0:options.configurable)!==null&&_options$configurable!==void 0?_options$configurable:false,
enumerable:(_options$enumerable=options===null||options===void 0?void 0:options.enumerable)!==null&&_options$enumerable!==void 0?_options$enumerable:true,
value:value};


if(options!==null&&options!==void 0&&options._proto_)
properties.__proto__=options.__proto__;

if(options!==null&&options!==void 0&&options.writable)
properties.writable=options.writable;

Object.defineProperty(this.controller,key,properties);
return this.controller[key];
}

setGlobals(){const _require4=
require("@corenode/builtin-lib"),globals=_require4.globals;

new globals(["corenode_cli","corenode"]);
const keywords=["_packages","_env"];

keywords.forEach(key=>{
if(typeof global[key]==="undefined"){
global[key]={};
}
});

global._versionScheme={mayor:0,minor:1,patch:2};
global.isLocalMode=false;

global._envpath=this.get.paths._env();
global._runtimeSource=this.get.paths._src();
global._runtimeRoot=this.get.paths._root();

Object.defineProperty(global,"_setPackage",{
configurable:false,
enumerable:true,
writable:false,
value:Object.freeze((key,path)=>{
global._packages[key]=path;
})});

Object.defineProperty(global,"_delPackage",{
configurable:false,
enumerable:true,
writable:false,
value:Object.freeze(key=>{
delete global._packages[key];
})});


global._setPackage("_engine",_path.default.resolve(__dirname,"../package.json"));
global._setPackage("_project",_path.default.resolve(process.cwd(),"package.json"));

global.corenode=process.runtime;
}

setEnvironment(){
_environmentFiles.forEach(file=>{
const fromPath=_path.default.resolve(process.cwd(),`./${file}`);
if(_fs.default.existsSync(fromPath)){
global._envpath=fromPath;
try{
global._env=JSON.parse(_fs.default.readFileSync(fromPath,"utf-8"));
}catch(error){
console.error(`\n🆘  Error parsing runtime env > ${error.message} \n\n`);
console.error(error);
}
}
});
}

startREPL(){
try{
const repl=require("repl");
const machine=new EvalMachine;

machine.onDestroy(address=>{
console.error(`🛑 VM[${address}] Has been destroyed`);
process.exit();
});

function fnEv(cmd,context,filename,callback){
try{
const out=machine.run(cmd);
callback(null,out);
}catch(error){
return callback(error.message);
}
}

console.log(`|  REPL Console | v${this.version}_${process.versions.node} |\n`);
repl.start({
prompt:`#> `,
useColors:true,
eval:fnEv});

}catch(error){
console.error(error);
verbosity.error(`Error starting eval machine > ${error}`);
}
}

setEvents(){
this.events.addListener("cli_noCommand",()=>{
this.startREPL();
});
}

init(){
return new Promise((resolve,reject)=>{
try{
process.runtime=this;
process.argvf=process.argv.slice(1);

if(!global._inited){
this.setGlobals();
this.setEnvironment();
}


this.version=this.helpers.getVersion({engine:true});
this._version=schemizedParse(this.version,Object.keys(global._versionScheme),".");


const moduleController=require("./modules").default;
this.modules=new moduleController;


try{
const rootPkg=this.helpers.getRootPackage();

if(rootPkg.name.includes("corenode")||rootPkg.name.includes("nodecore")){
global.isLocalMode=true;
}
}catch(error){

}


global._inited=true;


if(process.env.LOCAL_BIN=="true"&&!global.isLocalMode){
console.warn("\n\x1B[7m",`⚠️  'LOCAL_BIN' environment flag is enabled, but this project is not allowed to run in local mode, ignoring running in local mode!`,"\x1B[0m\n");
}else if(global.isLocalMode){
console.warn("\n\n\x1B[7m",`🚧  USING LOCAL DEVELOPMENT MODE  🚧`,"\x1B[0m\n\n");
}let _this$runParams$load=

this.runParams.load,targetBin=_this$runParams$load.targetBin,isLocalMode=_this$runParams$load.isLocalMode;
if(isLocalMode){
global.isLocalMode=true;
}

if(this.runParams.load.runCli){
const yparser=require("yargs-parser");
const argv=process.argv;
const args=yparser(argv);

if(typeof args["_"][2]!=="undefined"){
const fileFromArgs=_path.default.resolve(args["_"][2]);
if(!targetBin&&_fs.default.existsSync(fileFromArgs)){
targetBin=fileFromArgs;
}
if(targetBin){
try{
if(!_fs.default.existsSync(targetBin)){
throw new Error(`Cannot read loader script [${targetBin}]`);
}

const machine=new EvalMachine;
machine.run(targetBin);
}catch(error){
this.logger.dump("error",error);
console.log("This error has been exported, check the log file for more details");
verbosity.options({method:"[RUNTIME]"}).error(`Main loader > ${error.message}`);
}
}else{
return require("../internals/packages/cli/dist");
}
}else{
this.startREPL();
}
}

return resolve();
}catch(error){
return reject(error);
}
});
}}


module.exports=_objectSpread({
Runtime},
require("./helpers"));