"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.overrideResolveFilename=overrideResolveFilename;exports.overrideNodeModulesPath=overrideNodeModulesPath;exports.CustomNodeModuleController=void 0;var _path=_interopRequireDefault(require("path"));
var _lodash=_interopRequireDefault(require("lodash"));

var _utils=require("@corenode/utils");

class CustomNodeModuleController{
constructor(aliases,paths){
let Module=_lodash.default.clone(require("module"));

Module.overrides={
filenames:{},
paths:[]};


if(typeof aliases==="object"){
(0,_utils.objectToArrayMap)(aliases).forEach(alias=>{
Module.overrides.filenames[alias.key]=_path.default.resolve(process.cwd(),alias.value);
});
}

if(typeof paths==="object"){

}

Module=overrideNodeModulesPath(Module,Module.overrides.paths);
Module=overrideResolveFilename(Module,Module.overrides.filenames);

return Module;
}}exports.CustomNodeModuleController=CustomNodeModuleController;


function overrideResolveFilename(instance,to={}){
if(typeof instance!=="object"){
throw new Error(`Instance must be an object`);
}

const oldResolveFilename=instance._origin_resolveFilename=instance._resolveFilename;
instance._resolveFilename=function(request,parentModule,isMain,options){
if(typeof to[request]!=="undefined"){
request=to[request];
}
return oldResolveFilename.call(this,request,parentModule,isMain,options);
};

instance._autoCreatedRequire=instance.createRequire(process.cwd());
instance._require=function(request){
if(typeof to[request]!=="undefined"){
request=to[request];
}
return instance._autoCreatedRequire.call(this,request);
};

return instance;
}

function overrideNodeModulesPath(instance,to=[]){
if(typeof instance!=="object"){
throw new Error(`Instance must be an object`);
}

const oldNodeModulePaths=instance._origin_nodeModulePaths=instance._nodeModulePaths;
instance._nodeModulePaths=function(from){
let paths=oldNodeModulePaths.call(this,from);

if(from.indexOf("node_modules")===-1){
paths=to.concat(paths);
}
return paths;
};

return instance;
}