var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.getModuleConfigs=exports.buildCoreWebpackProject=exports.waitForWebpack=exports.runWebpackServer=exports.configureCoreWebProject=exports.waitForUrl=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _path=_interopRequireDefault(require("path"));
var _betterOpn=_interopRequireDefault(require("better-opn"));
var _axios=_interopRequireDefault(require("axios"));
var _ip=_interopRequireDefault(require("ip"));
var _commandExists=_interopRequireDefault(require("command-exists"));
var _fileutils=require("../systemManager/fileutils");
var _exec=require("../systemManager/exec");
var _common=require("../common");














var _resolve=require("../systemManager/resolve");
var _logger=require("../systemManager/logger");










var _engineManager=require("../engineManager");
var _pluginManager=require("../pluginManager");

var _constants=require("../constants");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;}

var WEBPACK=_path.default.join(_constants.RNV_NODE_MODULES_DIR,'webpack/bin/webpack.js');
var WEBPACK_DEV_SERVER=_path.default.join(_constants.RNV_NODE_MODULES_DIR,'webpack-dev-server/bin/webpack-dev-server.js');

var _generateWebpackConfigs=function _generateWebpackConfigs(c){
(0,_logger.logTask)('_generateWebpackConfigs');var
platform=c.platform;
var appFolder=(0,_common.getPlatformBuildDir)(c);
var appFolderServer=(0,_common.getPlatformServerDir)(c);var _getModuleConfigs=


getModuleConfigs(c),modulePaths=_getModuleConfigs.modulePaths,moduleAliases=_getModuleConfigs.moduleAliases;

var modulePath=_path.default.join(appFolder,'modules.json');
var externalModulePaths=[];
var localModulePaths=[];
if((0,_fileutils.fsExistsSync)(modulePath)){
var modules=(0,_fileutils.readObjectSync)(modulePath);
externalModulePaths=modules.externalPaths;
localModulePaths=modules.localPaths;
if(modules.aliases){
moduleAliases=_objectSpread(_objectSpread({},modules.aliases),moduleAliases);
}
}

modulePaths=modulePaths.
concat(externalModulePaths.map(function(v){return(0,_resolve.doResolvePath)(v,true,{},c.paths.project.nodeModulesDir);})).
concat(localModulePaths.map(function(v){return _path.default.join(c.paths.project.dir,v);})).
filter(Boolean);


var extendConfig=(0,_common.getConfigProp)(c,platform,'webpackConfig',{});
var entryFile=(0,_common.getConfigProp)(c,platform,'entryFile','index.web');
var title=(0,_common.getAppTitle)(c,platform);
var analyzer=(0,_common.getConfigProp)(c,platform,'analyzer')||c.program.analyzer;

if(!(0,_fileutils.fsExistsSync)(appFolderServer)){
(0,_fileutils.mkdirSync)(appFolderServer);
}











var assetVersion='';
var versionedAssets=(0,_common.getConfigProp)(c,platform,'versionedAssets',false);
if(versionedAssets){
assetVersion="-"+(0,_common.getAppVersion)(c,platform);
}
var timestampAssets=(0,_common.getConfigProp)(c,platform,'timestampAssets',false);
if(timestampAssets){
assetVersion="-"+c.runtime.timestamp;
}

var bundleAssets=c.runtime.forceBundleAssets||(0,_common.getConfigProp)(c,c.platform,'bundleAssets',false);

var obj=_objectSpread({
modulePaths:modulePaths,
moduleAliases:moduleAliases,
analyzer:analyzer,
entryFile:entryFile,
title:title,
assetVersion:assetVersion,
buildFolder:bundleAssets?(0,_common.getPlatformProjectDir)(c):(0,_common.getPlatformServerDir)(c),
extensions:(0,_engineManager.getPlatformExtensions)(c,true)},
extendConfig);


var extendJs="\n    module.exports = "+
JSON.stringify(obj,null,2);

(0,_fileutils.fsWriteFileSync)(_path.default.join(appFolder,'webpack.extend.js'),extendJs);
};


var _parseCssSync=function _parseCssSync(c){
var templateProjectDir=(0,_common.getTemplateProjectDir)(c);
var timestampPathsConfig=(0,_common.getTimestampPathsConfig)(c,c.platform);
var backgroundColor=(0,_common.getConfigProp)(c,c.platform,'backgroundColor');

var bundleAssets=c.runtime.forceBundleAssets||(0,_common.getConfigProp)(c,c.platform,'bundleAssets',false);
var targetDir=bundleAssets?(0,_common.getPlatformProjectDir)(c):(0,_common.getPlatformServerDir)(c);

var injects=[
{
pattern:'{{PLUGIN_COLORS_BG}}',
override:(0,_common.sanitizeColor)(
backgroundColor,
'backgroundColor').
hex}];



(0,_common.addSystemInjects)(c,injects);
var cssPath=_path.default.join(templateProjectDir,'app.css');
if((0,_fileutils.fsExistsSync)(cssPath)){
(0,_fileutils.writeCleanFile)(
cssPath,
_path.default.join(targetDir,'app.css'),
injects,
timestampPathsConfig,c);

}
};

var waitForUrl=function waitForUrl(url){return new Promise(function(resolve,reject){
var attempts=0;
var maxAttempts=10;
var CHECK_INTEVAL=2000;
var interval=setInterval(function(){
_axios.default.get(url).
then(function(){
resolve(true);
}).
catch(function(){
attempts++;
if(attempts>maxAttempts){
clearInterval(interval);

return reject(
"Can't connect to webpack. Try restarting it.");

}
});
},CHECK_INTEVAL);
});};exports.waitForUrl=waitForUrl;

var _runWebBrowser=function _runWebBrowser(c,platform,devServerHost,port,alreadyStarted){return new Promise(function(resolve){
(0,_logger.logTask)(
'_runWebBrowser',"ip:"+devServerHost+" port:"+port+" openBrowser:"+!!c.runtime.shouldOpenBrowser);

if(!c.runtime.shouldOpenBrowser)return resolve();
var wait=waitForWebpack(c).
then(function(){
(0,_betterOpn.default)("http://"+devServerHost+":"+port+"/");
}).
catch(function(e){
(0,_logger.logWarning)(e);
});
if(alreadyStarted)return wait;
return resolve();
});};

var _runRemoteDebuggerChii=function _runRemoteDebuggerChii(c,obj){var debugIp,resolvedDebugIp,debugUrl,command;return _regenerator.default.async(function _runRemoteDebuggerChii$(_context){while(1){switch(_context.prev=_context.next){case 0:
debugIp=c.program.debugIp;_context.prev=1;_context.next=4;return _regenerator.default.awrap(

(0,_commandExists.default)('chii'));case 4:

resolvedDebugIp=debugIp||_ip.default.address();
(0,_logger.logInfo)("Starting a remote debugger build with ip "+

resolvedDebugIp+". If this IP is not correct, you can always override it with --debugIp");


debugUrl=(0,_logger.chalk)().cyan("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT);

command="chii start --port "+_constants.REMOTE_DEBUG_PORT;
(0,_exec.executeAsync)(c,command,{stdio:'inherit',silent:true});_context.prev=9;_context.next=12;return _regenerator.default.awrap(


waitForUrl("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT));case 12:
(0,_logger.logRaw)("\n\nDebugger running at: "+

debugUrl);
(0,_betterOpn.default)("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT+"/");_context.next=19;break;case 16:_context.prev=16;_context.t0=_context["catch"](9);

(0,_logger.logError)(_context.t0);case 19:

obj.remoteDebuggerActive=true;
obj.debugVariables+="DEBUG=true DEBUG_IP="+
resolvedDebugIp+" DEBUG_CLIENT=chii DEBUG_SCRIPT=\"http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT+"/target.js\"";
obj.lineBreaks='\n';_context.next=27;break;case 24:_context.prev=24;_context.t1=_context["catch"](1);

(0,_logger.logWarning)("You are missing chii. You can install via "+(0,_logger.chalk)().white('npm i -g chii')+") Trying to use weinre next");case 27:return _context.abrupt("return",


true);case 28:case"end":return _context.stop();}}},null,null,[[1,24],[9,16]],Promise);};


var _runRemoteDebuggerWeinre=function _runRemoteDebuggerWeinre(c,obj){var debugIp,resolvedDebugIp,debugUrl,command;return _regenerator.default.async(function _runRemoteDebuggerWeinre$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:
debugIp=c.program.debugIp;_context2.prev=1;_context2.next=4;return _regenerator.default.awrap(

(0,_commandExists.default)('weinre'));case 4:

resolvedDebugIp=debugIp||_ip.default.address();
(0,_logger.logInfo)("Starting a remote debugger build with ip "+

resolvedDebugIp+". If this IP is not correct, you can always override it with --debugIp");


debugUrl=(0,_logger.chalk)().cyan("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT+"/client/#"+c.platform);

command="weinre --boundHost -all- --httpPort "+_constants.REMOTE_DEBUG_PORT;
(0,_exec.executeAsync)(c,command,{stdio:'inherit',silent:true});_context2.prev=9;_context2.next=12;return _regenerator.default.awrap(


waitForUrl("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT));case 12:
(0,_logger.logRaw)("\n\nDebugger running at: "+

debugUrl);
(0,_betterOpn.default)("http://"+resolvedDebugIp+":"+_constants.REMOTE_DEBUG_PORT+"/client/#"+c.platform);_context2.next=19;break;case 16:_context2.prev=16;_context2.t0=_context2["catch"](9);

(0,_logger.logError)(_context2.t0);case 19:

obj.remoteDebuggerActive=true;
obj.debugVariables+="DEBUG=true DEBUG_IP="+
resolvedDebugIp+" DEBUG_CLIENT=weinre DEBUG_SCRIPT=\"http://"+resolvedDebugIp+":"+
_constants.REMOTE_DEBUG_PORT+"/target/target-script-min.js#"+c.platform+"}";
obj.lineBreaks='\n';_context2.next=27;break;case 24:_context2.prev=24;_context2.t1=_context2["catch"](1);

(0,_logger.logWarning)("You are missing weinre. Skipping debug. install via "+(0,_logger.chalk)().white('npm i -g weinre'));case 27:return _context2.abrupt("return",

true);case 28:case"end":return _context2.stop();}}},null,null,[[1,24],[9,16]],Promise);};


var _runWebDevServer=function _runWebDevServer(c,enableRemoteDebugger){var debug,environment,configName,appFolder,wpPublic,wpConfig,debugObj,debugOrder,devServerHost,url,WPS_ALTERNATIVE,wps,command;return _regenerator.default.async(function _runWebDevServer$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:
(0,_logger.logTask)('_runWebDevServer');
debug=c.program.debug;

environment=(0,_common.getConfigProp)(c,c.platform,'environment','production');
configName=environment==='production'?'prod':'dev';

appFolder=(0,_common.getPlatformBuildDir)(c);
wpPublic=(0,_common.getPlatformServerDir)(c);
wpConfig=_path.default.join(appFolder,"webpack.config."+configName+".js");
debugObj={lineBreaks:'\n\n\n',debugVariables:'',remoteDebuggerActive:false};
debugOrder=[_runRemoteDebuggerChii,_runRemoteDebuggerWeinre];
if(debug==='weinre')debugOrder=[_runRemoteDebuggerWeinre,_runRemoteDebuggerChii];if(!(
(debug||enableRemoteDebugger)&&debug!=='false')){_context3.next=16;break;}_context3.next=13;return _regenerator.default.awrap(
debugOrder[0](c,debugObj));case 13:if(
debugObj.remoteDebuggerActive){_context3.next=16;break;}_context3.next=16;return _regenerator.default.awrap(
debugOrder[1](c,debugObj));case 16:



devServerHost=(0,_common.getDevServerHost)(c);

url=(0,_logger.chalk)().cyan("http://"+devServerHost+":"+c.runtime.port);
(0,_logger.logRaw)(debugObj.lineBreaks+"Dev server running at: "+url+"\n\n");


WPS_ALTERNATIVE=(0,_resolve.doResolve)('webpack-dev-server')+"/bin/webpack-dev-server.js";

wps='webpack-dev-server';
if((0,_fileutils.fsExistsSync)(WEBPACK_DEV_SERVER)){
wps=WEBPACK_DEV_SERVER;
}else if((0,_fileutils.fsExistsSync)(WPS_ALTERNATIVE)){
wps=WPS_ALTERNATIVE;
}else{
(0,_logger.logWarning)("cannot find installed webpack-dev-server. looked in following locations:\n"+
(0,_logger.chalk)().white(WEBPACK_DEV_SERVER)+",\n"+
(0,_logger.chalk)().white(WPS_ALTERNATIVE)+"\nwill try to use globally installed one");

}

command="npx cross-env PLATFORM="+c.platform+" "+
debugObj.debugVariables+" "+
wps+" -d --devtool source-map --config "+
wpConfig+"  --inline --hot --colors --content-base "+

wpPublic+" --history-api-fallback --port "+
c.runtime.port+" --mode="+
environment+" --host "+
devServerHost;_context3.prev=23;_context3.next=26;return _regenerator.default.awrap(

(0,_exec.executeAsync)(c,command,{
stdio:'inherit',
silent:true}));case 26:





(0,_logger.logDebug)('_runWebDevServer: running');_context3.next=33;break;case 29:_context3.prev=29;_context3.t0=_context3["catch"](23);

(0,_logger.logDebug)(_context3.t0);return _context3.abrupt("return",
true);case 33:case"end":return _context3.stop();}}},null,null,[[23,29]],Promise);};




var configureCoreWebProject=function configureCoreWebProject(c){return _regenerator.default.async(function configureCoreWebProject$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:
(0,_logger.logTask)('configureCoreWebProject');
_generateWebpackConfigs(c);
_parseCssSync(c);case 3:case"end":return _context4.stop();}}},null,null,null,Promise);};exports.configureCoreWebProject=configureCoreWebProject;


var runWebpackServer=function runWebpackServer(c,enableRemoteDebugger){var port,platform,devServerHost,isPortActive,bundleAssets,resetCompleted;return _regenerator.default.async(function runWebpackServer$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:
port=c.runtime.port;
platform=c.platform;
(0,_logger.logTask)('runWeb',"port:"+port+" debugger:"+!!enableRemoteDebugger);

devServerHost=c.runtime.localhost;

devServerHost=(0,_common.getDevServerHost)(c);_context5.next=7;return _regenerator.default.awrap(

(0,_common.checkPortInUse)(c,platform,port));case 7:isPortActive=_context5.sent;
bundleAssets=(0,_common.getConfigProp)(c,c.platform,'bundleAssets',false);if(!

bundleAssets){_context5.next=14;break;}_context5.next=12;return _regenerator.default.awrap(
buildCoreWebpackProject(c));case 12:
(0,_logger.logSuccess)('bundleAssets set to true. webpack dev server will not run');return _context5.abrupt("return",
true);case 14:if(


isPortActive){_context5.next=23;break;}
(0,_logger.logInfo)("Your "+
(0,_logger.chalk)().white(
platform)+" devServerHost "+
(0,_logger.chalk)().white(
devServerHost)+" at port "+
(0,_logger.chalk)().white(
port)+" is not running. Starting it up for you...");_context5.next=18;return _regenerator.default.awrap(


_runWebBrowser(c,platform,devServerHost,port,false));case 18:
if(!bundleAssets){
(0,_logger.logSummary)('BUNDLER STARTED');
}_context5.next=21;return _regenerator.default.awrap(
_runWebDevServer(c,enableRemoteDebugger));case 21:_context5.next=36;break;case 23:_context5.next=25;return _regenerator.default.awrap(

(0,_common.confirmActiveBundler)(c));case 25:resetCompleted=_context5.sent;if(!

resetCompleted){_context5.next=34;break;}_context5.next=29;return _regenerator.default.awrap(
_runWebBrowser(c,platform,devServerHost,port,false));case 29:
if(!bundleAssets){
(0,_logger.logSummary)('BUNDLER STARTED');
}_context5.next=32;return _regenerator.default.awrap(
_runWebDevServer(c,enableRemoteDebugger));case 32:_context5.next=36;break;case 34:_context5.next=36;return _regenerator.default.awrap(

_runWebBrowser(c,platform,devServerHost,port,true));case 36:case"end":return _context5.stop();}}},null,null,null,Promise);};exports.runWebpackServer=runWebpackServer;




var waitForWebpack=function waitForWebpack(c){var suffix,attempts,maxAttempts,CHECK_INTEVAL,devServerHost,url,_args6=arguments;return _regenerator.default.async(function waitForWebpack$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:suffix=_args6.length>1&&_args6[1]!==undefined?_args6[1]:'assets/bundle.js';
(0,_logger.logTask)('waitForWebpack',"port:"+c.runtime.port);
attempts=0;
maxAttempts=10;
CHECK_INTEVAL=2000;


devServerHost=(0,_common.getDevServerHost)(c);
url="http://"+devServerHost+":"+c.runtime.port+"/"+suffix;return _context6.abrupt("return",

new Promise(function(resolve,reject){
var interval=setInterval(function(){
_axios.default.
get(url).
then(function(res){
if(res.status===200){
clearInterval(interval);

return resolve(true);
}
attempts++;
if(attempts===maxAttempts){
clearInterval(interval);

return reject(
"Can't connect to webpack. Try restarting it.");

}
}).
catch(function(){
attempts++;
if(attempts>maxAttempts){
clearInterval(interval);

return reject(
"Can't connect to webpack. Try restarting it.");

}
});
},CHECK_INTEVAL);
}));case 8:case"end":return _context6.stop();}}},null,null,null,Promise);};exports.waitForWebpack=waitForWebpack;


var buildCoreWebpackProject=function buildCoreWebpackProject(c){var _c$program,debug,debugIp,platform,debugVariables,environment,configName,WP_ALTERNATIVE,wp;return _regenerator.default.async(function buildCoreWebpackProject$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_c$program=
c.program,debug=_c$program.debug,debugIp=_c$program.debugIp;
platform=c.platform;
(0,_logger.logTask)('buildCoreWebpackProject');

debugVariables='';

if(debug){
(0,_logger.logInfo)("Starting a remote debugger build with ip "+(
debugIp||
_ip.default.address())+". If this IP is not correct, you can always override it with --debugIp");

debugVariables+="DEBUG=true DEBUG_IP="+(debugIp||_ip.default.address());
}

environment=(0,_common.getConfigProp)(c,c.platform,'environment','production');
configName=environment==='production'?'prod':'dev';

WP_ALTERNATIVE=(0,_resolve.doResolve)('webpack')+"/bin/webpack.js";

wp='webpack';
if((0,_fileutils.fsExistsSync)(WEBPACK)){
wp=WEBPACK;
}else if((0,_fileutils.fsExistsSync)(WP_ALTERNATIVE)){
wp=WP_ALTERNATIVE;
}else{
(0,_logger.logWarning)("cannot find installed webpack. looked in following locations:\n"+
(0,_logger.chalk)().white(WEBPACK)+",\n"+
(0,_logger.chalk)().white(WP_ALTERNATIVE)+"\nwill try to use globally installed one");

}_context7.next=12;return _regenerator.default.awrap(


(0,_exec.executeAsync)(c,"npx cross-env PLATFORM="+platform+" NODE_ENV="+environment+" "+
debugVariables+" node "+
wp+" -p --config ./platformBuilds/"+c.runtime.appId+"_"+platform+"/webpack.config."+configName+".js",{}));case 12:




(0,_logger.logSuccess)("Your Build is located in "+
(0,_logger.chalk)().cyan(
(0,_common.getPlatformProjectDir)(c))+" .");return _context7.abrupt("return",


true);case 14:case"end":return _context7.stop();}}},null,null,null,Promise);};exports.buildCoreWebpackProject=buildCoreWebpackProject;


var getModuleConfigs=function getModuleConfigs(c,primaryKey){
var modulePaths=[];
var moduleAliases={};

var doNotResolveModulePaths=[];


(0,_pluginManager.parsePlugins)(c,c.platform,function(plugin,pluginPlat,key){
var webpackConfig=plugin[primaryKey]||plugin.webpack||plugin.webpackConfig;

if(webpackConfig){
if(webpackConfig.modulePaths){
if(webpackConfig.modulePaths===false){

}else if(webpackConfig.modulePaths===true){
modulePaths.push("node_modules/"+key);
}else{
webpackConfig.modulePaths.forEach(function(v){
if(typeof v==='string'){
modulePaths.push(v);
}else if(v==null?void 0:v.projectPath){
doNotResolveModulePaths.push(_path.default.join(c.paths.project.dir,v.projectPath));
}
});
}
}
if(webpackConfig.moduleAliases){
if(webpackConfig.moduleAliases===true){
moduleAliases[key]=(0,_resolve.doResolvePath)(key,true,{},c.paths.project.nodeModulesDir);
}else{
Object.keys(webpackConfig.moduleAliases).forEach(function(aKey){
var mAlias=webpackConfig.moduleAliases[aKey];
if(typeof mAlias==='string'){
moduleAliases[key]=(0,_resolve.doResolvePath)(mAlias,true,{},c.paths.project.nodeModulesDir);
}else if(mAlias.path){
moduleAliases[key]=_path.default.join(c.paths.project.dir,mAlias.path);
}else if(mAlias.projectPath){
moduleAliases[key]=_path.default.join(c.paths.project.dir,mAlias.projectPath);
}
});
}
}
}
},true);

var moduleAliasesArray=[];
Object.keys(moduleAliases).forEach(function(key){
moduleAliasesArray.push(key+":"+moduleAliases[key]);
});

modulePaths=modulePaths.
map(function(v){return(0,_resolve.doResolvePath)(v,true,{},c.paths.project.dir);}).
concat(doNotResolveModulePaths).
concat([c.paths.project.assets.dir]).
filter(Boolean);


return{modulePaths:modulePaths,moduleAliases:moduleAliases,moduleAliasesArray:moduleAliasesArray};
};exports.getModuleConfigs=getModuleConfigs;
//# sourceMappingURL=webpackUtils.js.map