var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"launchAppleSimulator",{enumerable:true,get:function get(){return _deviceManager.launchAppleSimulator;}});Object.defineProperty(exports,"listAppleDevices",{enumerable:true,get:function get(){return _deviceManager.listAppleDevices;}});exports.runAppleLog=exports.packageBundleForXcode=exports.archiveXcodeProject=exports.exportXcodeProject=exports.runXcodeProject=exports.configureXcodeProject=exports.copyAppleAssets=exports.runPod=exports.getAppFolderName=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));

var _path=_interopRequireDefault(require("path"));
var _fs=_interopRequireDefault(require("fs"));
var _chalk=_interopRequireDefault(require("chalk"));
var _child_process=_interopRequireDefault(require("child_process"));
var _inquirer=_interopRequireDefault(require("inquirer"));

var _exec=require("../../systemTools/exec");
var _deviceManager=require("./deviceManager");
var _common=require("../../common");










var _projectParser=require("../../projectTools/projectParser");
var _fileutils=require("../../systemTools/fileutils");
var _constants=require("../../constants");
var _plistParser=require("./plistParser");



var _xcschemeParser=require("./xcschemeParser");
var _podfileParser=require("./podfileParser");
var _xcodeParser=require("./xcodeParser");
var _swiftParser=require("./swiftParser");

var checkIfCommandExists=function checkIfCommandExists(command){return new Promise(function(resolve,reject){return _child_process.default.exec("command -v "+command+" 2>/dev/null",function(error){
if(error)return reject(new Error(command+" not installed"));
return resolve();
});});};

var runPod=function runPod(c,command,cwd){var rejectOnFail=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;return new Promise(function(resolve,reject){
(0,_common.logTask)("runPod:"+command+":"+rejectOnFail);

if(!_fs.default.existsSync(cwd)){
if(rejectOnFail)return reject("Location "+cwd+" does not exists!");
(0,_common.logError)("Location "+cwd+" does not exists!");
return resolve();
}
return checkIfCommandExists('pod').
then(function(){return(0,_exec.executeAsync)(c,"pod "+command,{
cwd:cwd,
evn:process.env}).

then(function(){
resolve();
}).
catch(function(e){
if(rejectOnFail){
(0,_common.logWarning)(e);
return reject(e);
}
(0,_common.logError)(e);
return resolve();
});}).
catch(function(err){return(0,_common.logError)(err);});
});};exports.runPod=runPod;

var copyAppleAssets=function copyAppleAssets(c,platform,appFolderName){return new Promise(function(resolve){
(0,_common.logTask)('copyAppleAssets');
if(!(0,_common.isPlatformActive)(c,platform,resolve))return;

var appFolder=(0,_common.getAppFolder)(c,platform);


_fs.default.writeFileSync(_path.default.join(appFolder,'main.jsbundle'),'{}');
(0,_fileutils.mkdirSync)(_path.default.join(appFolder,'assets'));
(0,_fileutils.mkdirSync)(_path.default.join(appFolder,appFolderName+"/images"));

resolve();
});};exports.copyAppleAssets=copyAppleAssets;

var runXcodeProject=function runXcodeProject(c,platform,target){var newTarget;return _regenerator.default.async(function runXcodeProject$(_context){while(1){switch(_context.prev=_context.next){case 0:
(0,_common.logTask)("runXcodeProject:"+platform+":"+target);if(!(

target==='?')){_context.next=9;break;}_context.next=4;return _regenerator.default.awrap(
(0,_deviceManager.launchAppleSimulator)(c,platform,target));case 4:newTarget=_context.sent;_context.next=7;return _regenerator.default.awrap(
_runXcodeProject(c,platform,newTarget));case 7:_context.next=11;break;case 9:_context.next=11;return _regenerator.default.awrap(

_runXcodeProject(c,platform,target));case 11:case"end":return _context.stop();}}});};exports.runXcodeProject=runXcodeProject;



var _runXcodeProject=function _runXcodeProject(c,platform,target){var appPath,device,scheme,runScheme,bundleIsDev,bundleAssets,p,devicesArr,run,selectedDevice,devices,_ref,sim,allowProvisioningUpdates;return _regenerator.default.async(function _runXcodeProject$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:
(0,_common.logTask)("_runXcodeProject:"+platform+":"+target);

appPath=(0,_common.getAppFolder)(c,platform);
device=c.program.device;
scheme=(0,_common.getConfigProp)(c,platform,'scheme');
runScheme=(0,_common.getConfigProp)(c,platform,'runScheme');
bundleIsDev=(0,_common.getConfigProp)(c,platform,'bundleIsDev')===true;
bundleAssets=(0,_common.getConfigProp)(c,platform,'bundleAssets')===true;if(


scheme){_context2.next=9;break;}return _context2.abrupt("return",
Promise.reject("You missing scheme in platforms."+
_chalk.default.yellow(platform)+" in your "+_chalk.default.white(
c.paths.appConfig.config)+"! Check example config for more info:  "+
_chalk.default.grey(
'https://github.com/pavjacko/renative/blob/master/appConfigs/helloWorld/renative.json')+" "));case 9:if(!(




device===true)){_context2.next=37;break;}_context2.next=12;return _regenerator.default.awrap(
(0,_deviceManager.getAppleDevices)(c,platform,false,true));case 12:devicesArr=_context2.sent;if(!(
devicesArr.length===1)){_context2.next=18;break;}
(0,_common.logSuccess)("Found one device connected! device name: "+_chalk.default.white(devicesArr[0].name)+" udid: "+_chalk.default.white(devicesArr[0].udid));
if(devicesArr[0].udid){
p=[
'run-ios',
'--project-path',
appPath,
'--device',
'--udid',
devicesArr[0].udid,
'--scheme',
scheme,
'--configuration',
runScheme];

}else{
p=[
'run-ios',
'--project-path',
appPath,
'--device',
devicesArr[0].name,
'--scheme',
scheme,
'--configuration',
runScheme];

}_context2.next=35;break;case 18:if(!(
devicesArr.length>1)){_context2.next=34;break;}
run=function run(selectedDevice){
(0,_common.logDebug)("Selected device: "+JSON.stringify(selectedDevice,null,3));
if(selectedDevice.udid){
p="run-ios --project-path "+appPath+" --device --udid "+selectedDevice.udid+" --scheme "+scheme+" --configuration "+runScheme;
}else{
p="run-ios --project-path "+appPath+" --device "+selectedDevice.name+" --scheme "+scheme+" --configuration "+runScheme;
}

(0,_common.logDebug)("RN params: "+p);

if(bundleAssets){
(0,_common.logDebug)('Assets will be bundled');
return packageBundleForXcode(c,platform,bundleIsDev).then(function(){return _checkLockAndExec(c,p);});
}
return _checkLockAndExec(c,p);
};if(!

c.program.target){_context2.next=25;break;}
selectedDevice=devicesArr.find(function(d){return d.name===c.program.target;});if(!
selectedDevice){_context2.next=24;break;}return _context2.abrupt("return",
run(selectedDevice));case 24:return _context2.abrupt("return",

Promise.reject("Could not find device "+c.program.target));case 25:


devices=devicesArr.map(function(v){return{name:v.name+" | "+v.deviceIcon+" | v: "+_chalk.default.green(v.version)+" | udid: "+_chalk.default.grey(v.udid)+(v.isDevice?_chalk.default.red(' (device)'):''),value:v};});_context2.next=28;return _regenerator.default.awrap(

_inquirer.default.prompt({
name:'sim',
message:'Select the device you want to launch on',
type:'list',
choices:devices}));case 28:_ref=_context2.sent;sim=_ref.sim;if(!


sim){_context2.next=32;break;}return _context2.abrupt("return",
run(sim));case 32:_context2.next=35;break;case 34:return _context2.abrupt("return",


Promise.reject("No "+platform+" devices connected!"));case 35:_context2.next=38;break;case 37:

if(device){
p=['run-ios','--project-path',appPath,'--device',device,'--scheme',scheme,'--configuration',runScheme];
}else{
p=['run-ios','--project-path',appPath,'--simulator',target.replace(/(\s+)/g,'\\$1'),'--scheme',scheme,'--configuration',runScheme];
}case 38:if(!

p){_context2.next=43;break;}
allowProvisioningUpdates=(0,_common.getConfigProp)(c,platform,'allowProvisioningUpdates',true);if(!


bundleAssets){_context2.next=42;break;}return _context2.abrupt("return",
packageBundleForXcode(c,platform,bundleIsDev).then(function(){return(0,_exec.executeAsync)(c,"react-native "+p.join(' '));}));case 42:return _context2.abrupt("return",

_checkLockAndExec(c,p.join(' ')));case 43:return _context2.abrupt("return",

Promise.reject('Missing options for react-native command!'));case 44:case"end":return _context2.stop();}}});};


var _checkLockAndExec=function _checkLockAndExec(c,p){return(0,_exec.executeAsync)(c,"react-native "+p).
catch(function(e){
var isDeviceLocked=e.includes('ERROR:DEVICE_LOCKED');
if(isDeviceLocked){
return _inquirer.default.prompt({message:'Unlock your device and press ENTER',type:'confirm',name:'confirm'}).
then(function(){return(0,_exec.executeAsync)(c,"react-native "+p);});
}
return Promise.reject(e);
});};

var composeXcodeArgsFromCLI=function composeXcodeArgsFromCLI(string){
var spacesReplaced=string.replace(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g,'&&&');
var keysAndValues=spacesReplaced.split('&&&');
var unescapedValues=keysAndValues.map(function(s){return s.replace(/\'/g,'').replace(/"/g,'').replace(/\\/g,'');});

return unescapedValues;
};

var archiveXcodeProject=function archiveXcodeProject(c,platform){
(0,_common.logTask)("archiveXcodeProject:"+platform);


var appFolderName=getAppFolderName(c,platform);
var runScheme=(0,_common.getConfigProp)(c,platform,'runScheme','Debug');
var sdk=(0,_common.getConfigProp)(c,platform,'sdk');
if(!sdk){
if(platform===_constants.IOS)sdk='iphoneos';
if(platform===_constants.TVOS)sdk='appletvos';
if(platform===_constants.MACOS)sdk='macosx';
}
var sdkArr=[sdk];

var appPath=(0,_common.getAppFolder)(c,platform);
var exportPath=_path.default.join(appPath,'release');

var scheme=(0,_common.getConfigProp)(c,platform,'scheme');
var allowProvisioningUpdates=(0,_common.getConfigProp)(c,platform,'allowProvisioningUpdates',true);
var ignoreLogs=(0,_common.getConfigProp)(c,platform,'ignoreLogs');
var bundleIsDev=(0,_common.getConfigProp)(c,platform,'bundleIsDev')===true;
var exportPathArchive=exportPath+"/"+scheme+".xcarchive";
var ps='';
if(c.program.xcodebuildArchiveArgs){
ps=c.program.xcodebuildArchiveArgs;
}
var p=[];

if(!ps.includes('-workspace')){
p.push('-workspace');
p.push(appPath+"/"+appFolderName+".xcworkspace");
}
if(!ps.includes('-scheme')){
p.push('-scheme');
p.push(scheme);
}
if(!ps.includes('-sdk')){
p.push('-sdk');
p.push.apply(p,sdkArr);
}
if(!ps.includes('-configuration')){
p.push('-configuration');
p.push(runScheme);
}
p.push('archive');
if(!ps.includes('-archivePath')){
p.push('-archivePath');
p.push(exportPathArchive);
}

if(allowProvisioningUpdates&&!ps.includes('-allowProvisioningUpdates'))p.push('-allowProvisioningUpdates');
if(ignoreLogs&&!ps.includes('-quiet'))p.push('-quiet');



(0,_common.logTask)('archiveXcodeProject: STARTING xcodebuild ARCHIVE...');

if(c.buildConfig.platforms[platform].runScheme==='Release'){
return packageBundleForXcode(c,platform,bundleIsDev).
then(function(){return(0,_exec.executeAsync)(c,"xcodebuild "+ps+" "+p.join(' '));}).
then(function(){
(0,_common.logSuccess)("Your Archive is located in "+_chalk.default.white(exportPath)+" .");
});
}

var args=ps!==''?[].concat((0,_toConsumableArray2.default)(composeXcodeArgsFromCLI(ps)),p):p;

(0,_common.logDebug)('xcodebuild args',args);

return(0,_exec.executeAsync)('xcodebuild',{rawCommand:{args:args}}).
then(function(){
(0,_common.logSuccess)("Your Archive is located in "+_chalk.default.white(exportPath)+" .");
});
};exports.archiveXcodeProject=archiveXcodeProject;

var exportXcodeProject=function exportXcodeProject(c,platform){
(0,_common.logTask)("exportXcodeProject:"+platform);

var appPath=(0,_common.getAppFolder)(c,platform);
var exportPath=_path.default.join(appPath,'release');

var scheme=(0,_common.getConfigProp)(c,platform,'scheme');
var allowProvisioningUpdates=(0,_common.getConfigProp)(c,platform,'allowProvisioningUpdates',true);
var ignoreLogs=(0,_common.getConfigProp)(c,platform,'ignoreLogs');

var ps='';
if(c.program.xcodebuildExportArgs){
ps=c.program.xcodebuildExportArgs;
}
var p=['-exportArchive'];

if(!ps.includes('-archivePath')){
p.push("-archivePath "+exportPath+"/"+scheme+".xcarchive");
}
if(!ps.includes('-exportOptionsPlist')){
p.push("-exportOptionsPlist "+appPath+"/exportOptions.plist");
}
if(!ps.includes('-exportPath')){
p.push("-exportPath "+exportPath);
}

if(allowProvisioningUpdates&&!ps.includes('-allowProvisioningUpdates'))p.push('-allowProvisioningUpdates');
if(ignoreLogs&&!ps.includes('-quiet'))p.push('-quiet');

(0,_common.logDebug)('running',p);

(0,_common.logTask)('exportXcodeProject: STARTING xcodebuild EXPORT...');

return(0,_exec.executeAsync)(c,"xcodebuild "+p.join(' ')).
then(function(){
(0,_common.logSuccess)("Your IPA is located in "+_chalk.default.white(exportPath)+" .");
});
};exports.exportXcodeProject=exportXcodeProject;

var packageBundleForXcode=function packageBundleForXcode(c,platform){var isDev=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;
(0,_common.logTask)("packageBundleForXcode:"+platform);var
maxErrorLength=c.program.maxErrorLength;
var args=[
'bundle',
'--platform',
'ios',
'--dev',
isDev,
'--assets-dest',"platformBuilds/"+
c.runtime.appId+"_"+platform,
'--entry-file',
c.buildConfig.platforms[platform].entryFile+".js",
'--bundle-output',
(0,_common.getAppFolder)(c,platform)+"/main.jsbundle"];


if(c.program.info){
args.push('--verbose');
}

return(0,_exec.executeAsync)(c,"react-native "+args.join(' '));
};exports.packageBundleForXcode=packageBundleForXcode;

var getAppFolderName=function getAppFolderName(c,platform){
var projectFolder=(0,_common.getConfigProp)(c,platform,'projectFolder');
if(projectFolder){
return projectFolder;
}
return platform===_constants.IOS?'RNVApp':'RNVAppTVOS';
};exports.getAppFolderName=getAppFolderName;



var runAppleLog=function runAppleLog(c){return new Promise(function(){
(0,_common.logTask)('runAppleLog');
var filter=c.program.filter||'RNV';
var child=_child_process.default.execFile(
'xcrun',
['simctl','spawn','booted','log','stream','--predicate',"eventMessage contains \""+filter+"\""],
{stdio:'inherit',customFds:[0,1,2]});


child.stdout.on('data',function(data){
var d=data.toString();
if(d.toLowerCase().includes('error')){
console.log(_chalk.default.red(d));
}else if(d.toLowerCase().includes('success')){
console.log(_chalk.default.green(d));
}else{
console.log(d);
}
});
});};exports.runAppleLog=runAppleLog;

var configureXcodeProject=function configureXcodeProject(c,platform,ip,port){return new Promise(function(resolve,reject){
(0,_common.logTask)("configureXcodeProject:"+platform);var
device=c.program.device;
var bundlerIp=device?(0,_common.getIP)():'localhost';
var appFolder=(0,_common.getAppFolder)(c,platform);
var appFolderName=getAppFolderName(c,platform);
var bundleAssets=(0,_common.getConfigProp)(c,platform,'bundleAssets')===true;

c.pluginConfigiOS={
podfileInject:'',
exportOptions:'',
embeddedFonts:[],
embeddedFontSources:[],
pluginAppDelegateImports:'',
pluginAppDelegateMethods:'',
appDelegateMethods:{
application:{
didFinishLaunchingWithOptions:[],
applicationDidBecomeActive:[],
open:[],
supportedInterfaceOrientationsFor:[],
didReceiveRemoteNotification:[],
didFailToRegisterForRemoteNotificationsWithError:[],
didReceive:[],
didRegister:[],
didRegisterForRemoteNotificationsWithDeviceToken:[]},

userNotificationCenter:{
willPresent:[]}},


podfileSources:[]};



(0,_projectParser.parseFonts)(c,function(font,dir){
if(font.includes('.ttf')||font.includes('.otf')){
var key=font.split('.')[0];var
includedFonts=c.buildConfig.common.includedFonts;
if(includedFonts&&(includedFonts.includes('*')||includedFonts.includes(key))){
var fontSource=_path.default.join(dir,font);
if(_fs.default.existsSync(fontSource)){
var fontFolder=_path.default.join(appFolder,'fonts');
(0,_fileutils.mkdirSync)(fontFolder);
var fontDest=_path.default.join(fontFolder,font);
(0,_fileutils.copyFileSync)(fontSource,fontDest);
c.pluginConfigiOS.embeddedFontSources.push(fontSource);
c.pluginConfigiOS.embeddedFonts.push(font);
}else{
(0,_common.logWarning)("Font "+_chalk.default.white(fontSource)+" doesn't exist! Skipping.");
}
}
}
});



var tId=(0,_common.getConfigProp)(c,platform,'teamID');
if(device&&(!tId||tId==='')){
(0,_common.logError)("Looks like you're missing teamID in your "+
_chalk.default.white(
c.paths.appConfig.config)+" => .platforms."+
platform+".teamID . you will not be able to build "+platform+" app for device!");

}


var forceUpdate=!_fs.default.existsSync(_path.default.join(appFolder,'Podfile.lock'))||c.program.update;
(0,_projectParser.copyAssetsFolder)(c,platform).
then(function(){return copyAppleAssets(c,platform,appFolderName);}).
then(function(){return(0,_swiftParser.parseAppDelegate)(c,platform,appFolder,appFolderName,bundleAssets,bundlerIp,port);}).
then(function(){return(0,_plistParser.parseExportOptionsPlist)(c,platform);}).
then(function(){return(0,_xcschemeParser.parseXcscheme)(c,platform);}).
then(function(){return(0,_podfileParser.parsePodFile)(c,platform);}).
then(function(){return(0,_plistParser.parseEntitlementsPlist)(c,platform);}).
then(function(){return(0,_plistParser.parseInfoPlist)(c,platform);}).
then(function(){return(0,_projectParser.copyBuildsFolder)(c,platform);}).
then(function(){
runPod(c,forceUpdate?'update':'install',(0,_common.getAppFolder)(c,platform),true).
then(function(){return(0,_xcodeParser.parseXcodeProject)(c,platform);}).
then(function(){
resolve();
}).
catch(function(e){
if(!c.program.update){
if(e&&e.toString){
var s=e.toString();
if(
s.includes('No provisionProfileSpecifier configured')||
s.includes('TypeError:')||
s.includes('ReferenceError:')||
s.includes('find gem cocoapods'))
{
reject(e);
}
}else{
(0,_common.logWarning)("Looks like pod install is not enough! Let's try pod update! Error: "+e);
runPod(c,'update',(0,_common.getAppFolder)(c,platform),true).
then(function(){return(0,_xcodeParser.parseXcodeProject)(c,platform);}).
then(function(){return resolve();}).
catch(function(err){return reject(err);});
}
}else{
reject(e);
}
});
}).
catch(function(e){return reject(e);});
});};exports.configureXcodeProject=configureXcodeProject;