"use strict";var e=require("fs"),t=require("path"),s=require("debug"),r=require("jsonc-parser"),a=require("fs-extra"),i=require("postcss-selector-parser"),o=require("licia/dateFormat"),n=require("util"),l=require("child_process"),c=require("dns");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=d(e),p=d(t),h=d(s),m=d(a),f=d(i),y=d(o),v=d(c);function _(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"body":"uni-"+t}}))}h.default("automator:devtool");const I=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const P=/^win/.test(process.platform);function N(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}const E=h.default("automator:launcher"),w=n.promisify(u.default.readdir),S=n.promisify(u.default.stat);async function $(e){const s=await w(e);return(await Promise.all(s.map((async s=>{const r=t.resolve(e,s);return(await S(r)).isDirectory()?$(r):r})))).reduce(((e,t)=>e.concat(t)),[])}class g{constructor(e){this.isX=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),this.id=e.id,this.app=e.executablePath,this.appid=e.appid||process.env.UNI_APP_ID||(this.isX?"__UNI__uniappx":"HBuilder"),this.package=e.package||(this.isX?"io.dcloud.uniappx":"io.dcloud.HBuilder"),this.activity=e.activity||(this.isX?"io.dcloud.uniapp.UniAppActivity":"io.dcloud.PandoraEntry")}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then((()=>(E(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(E(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(e){return $(e).then((s=>{const r=s.map((s=>{const r=(e=>P?e.replace(/\\/g,"/"):e)(t.join(this.DIR_WWW,t.relative(e,s)));return E(`${y.default("yyyy-mm-dd HH:MM:ss:l")} push ${s} ${r}`),this.pushFile(s,r)}));return Promise.all(r)})).then((e=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const D=h.default("automator:simctl");function U(e){const t=parseInt(e);return t>9?String(t):"0"+t}class A extends g{constructor(){super(...arguments),this.bundleVersion=""}async init(){const e=N("node-simctl").Simctl;this.tool=new e({udid:this.id});try{await this.tool.bootDevice()}catch(e){}await this.initSDCard(),D(`${y.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const e=await this.tool.appInfo(this.package);D(`${y.default("yyyy-mm-dd HH:MM:ss:l")} appInfo ${e}`);const t=e.match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");const s=e.match(/CFBundleVersion\s+=\s+(.*);/);if(!s)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),this.bundleVersion=s[1],D(`${y.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.bundleVersion)}formatVersion(e){const t=e.split(".");return 3!==t.length?e:t[0]+U(t[1])+U(t[2])}async install(){return D(`${y.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.tool.grantPermission(this.package,"all"),await this.initSDCard(),Promise.resolve(!0)}async start(){D("ios simulator start");try{await this.tool.terminateApp(this.package)}catch(e){console.error("ios simulator start terminateApp fail",e)}try{await this.tool.launchApp(this.package)}catch(e){console.error("ios simulator start launchApp fail",e),console.error(e)}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(e){const t=await Promise.resolve(await this.tool.getScreenshot());return new Promise(((s,r)=>{var a,i;if(void 0!==(null===(a=null==e?void 0:e.area)||void 0===a?void 0:a.x)&&void 0!==(null===(i=null==e?void 0:e.area)||void 0===i?void 0:i.y)){const a=require("jimp");a.read(Buffer.from(t,"base64")).then((t=>{const i=e.area.x,o=e.area.y;let n=t.bitmap.width-i;e.area.width&&(n=Math.min(n,e.area.width));let l=t.bitmap.height-o;e.area.height&&(l=Math.min(l,e.area.height)),t.crop(i,o,n,l).getBase64Async(a.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{r(e)}))})).catch((e=>{r(e)}))}else s(t)}))}exists(e){return m.default.existsSync(e)?Promise.resolve(!0):Promise.reject(Error(`${e} not exists`))}pushFile(e,t){return Promise.resolve(m.default.copySync(e,t))}adbCommand(e){return new Promise((e=>{e("adbCommand only for App Android!")}))}swipe(e){return new Promise((t=>{const{startPoint:s,endPoint:r,duration:a}=e;l.exec(`idb connect ${this.id} && idb ui swipe ${s.x} ${s.y} ${r.x} ${r.y} --duration ${a?a/1e3:.1} --udid ${this.id}`,(e=>{if(e)return console.error(`exec error: ${e}`),void t(`swipe fail: ${e}`);t("swipe success")}))}))}get DIR_WWW(){return"true"===process.env.UNI_APP_X?`${this.sdcard}/Documents/uni-app-x/apps/__UNI__uniappx/www/`:`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const M=N("adbkit"),R=h.default("automator:adb");class x extends g{constructor(){super(...arguments),this.needStart=!0}async init(){if(void 0!==v.default.setDefaultResultOrder&&v.default.setDefaultResultOrder("ipv4first"),this.tool=M.createClient(),R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} init ${await this.tool.version()}`),!this.id){const e=await this.tool.listDevices();if(!e.length)throw Error("Device not found");this.id=e[0].id}console.log("before echo ${$EXTERNAL_STORAGE}"),this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),console.log("after echo ${$EXTERNAL_STORAGE}",this.sdcard),R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((e=>{R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${e}`)}))}version(){return this.shell(this.COMMAND_VERSION).then((e=>{const t=e.match(/versionName=(.*)/);return t&&t.length>1?t[1]:""}))}formatVersion(e){return e}async install(){let e=!0;try{const t=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(t)<6&&(e=!1)}catch(e){}if(R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${e}`),e){const e=N("adbkit/lib/adb/command.js"),t=e.prototype._send;e.prototype._send=function(e){return 0===e.indexOf("shell:pm install -r ")&&(e=e.replace("shell:pm install -r ","shell:pm install -r -g "),R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${e} `)),t.call(this,e)}}return this.tool.install(this.id,this.app).then((()=>{R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} installed`),this.init()}))}start(){return this.needStart?this.exit().then((()=>this.shell(this.COMMAND_START))):Promise.resolve()}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(e){return this.tool.screencap(this.id).then((t=>new Promise(((s,r)=>{const a=[];t.on("data",(function(e){a.push(e)})),t.on("end",(function(){var t,i;if(void 0!==(null===(t=e.area)||void 0===t?void 0:t.x)&&void 0!==(null===(i=e.area)||void 0===i?void 0:i.y)){const t=require("jimp");t.read(Buffer.concat(a)).then((a=>{var i,o,n,l;const c=e.area.x,d=e.area.y;let u=a.bitmap.width-c;(null===(i=e.area)||void 0===i?void 0:i.width)&&(u=Math.min(u,null===(o=e.area)||void 0===o?void 0:o.width));let p=a.bitmap.height-d;(null===(n=e.area)||void 0===n?void 0:n.height)&&(p=Math.min(p,null===(l=e.area)||void 0===l?void 0:l.height)),a.crop(c,d,u,p).getBase64Async(t.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{r(e)}))})).catch((e=>{r(e)}))}else s(Buffer.concat(a).toString("base64"))}))}))))}adbCommand(e){return new Promise((t=>{this.tool.shell(this.id,e).then((e=>{let s,r="";e.on("data",(e=>{r+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(r)}),50)})),setTimeout((()=>{t(r)}),1500)}))}))}swipe(e){return new Promise((t=>{this.tool.shell(this.id,`input swipe ${e.startPoint.x} ${e.startPoint.y} ${e.endPoint.x} ${e.endPoint.y} ${e.duration||100}`).then((e=>{let s,r="";e.on("data",(e=>{r+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(r)}),50)})),setTimeout((()=>{t(r)}),1500)}))}))}exists(e){return this.tool.stat(this.id,e)}pushFile(e,t){return this.tool.push(this.id,e,t)}async push(e){if(!process.env.UNI_HBUILDERX_PLUGINS)return super.push(e);const t=p.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher","out","export","pushResources.js"),s=process.env.HX_CONFIG_ADB_PATH||p.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher-tools","tools","adbs","adb"),r=[t,s].map((e=>u.default.promises.access(e,u.default.constants.F_OK).then((()=>`${e} exists`)).catch((()=>`${e} not exists`))));return Promise.all(r).then((()=>{const{PushResources:r}=require(t);return new r({adbPath:s,appid:this.appid,uuid:this.id,packageName:this.package,sourcePath:e}).start(),this.needStart=!1,!0})).catch((async t=>(console.log("pushResources or adb not exists: ",t),await super.push(e))))}shell(e){return R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${e}`),this.tool.shell(this.id,e).then(M.util.readAll).then((e=>{const t=e.toString();return R(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${t}`),t}))}get DIR_WWW(){return`/storage/emulated/0/Android/data/${this.package}/apps/${this.appid}/www`}get COMMAND_EXTERNAL(){return"echo $EXTERNAL_STORAGE"}get COMMAND_VERSION(){return`dumpsys package ${this.package}`}get COMMAND_STOP(){return`am force-stop ${this.package}`}get COMMAND_START(){return`am start -n ${this.package}/${this.activity} --es appid ${this.appid} --ez needUpdateApp false --ez reload true --ez externalStorage true`}}const H=h.default("automator:devtool");let b,T=!1;const C={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const O={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>b.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshotWithDevice":{reflect:async(e,t)=>{const s=await b.captureScreenshot(t);return H(`App.captureScreenshot ${s.length}`),{data:s}}},"App.adbCommand":{reflect:async(e,t)=>{const s=await b.adbCommand(t);return H(`App.adbCommand ${s.length}`),{data:s}}},"App.swipe":{reflect:async(e,t)=>{const s=await b.swipe(t);return H(`App.swipe ${s.length}`),{data:s}}}};!function(e){I.forEach((t=>{e[t]=function(e){return{reflect:async(t,s)=>t(e,s,!1),params:e=>(e.selector&&(e.selector=f.default(_).processSync(e.selector)),e)}}(t)}))}(O);const X={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(e,t){e.platform=(e.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(e,e[e.platform]),b=function(e,t){return"ios"===e?new A(t):new x(t)}(e.platform,e),await b.init();const s=await b.version();if(s){if(e.version){const t=b.formatVersion(function(e,t){if(e.endsWith(".txt"))try{const s=u.default.readFileSync(e).toString().match(C[t]);if(s)return s[1]}catch(e){console.error(e)}return e}(e.version,e.platform));H(`version: ${s}`),H(`newVersion: ${t}`),t!==s&&(T=!0)}}else T=!0;if(T){if(!e.executablePath)throw Error(`app-plus->${e.platform}->executablePath is not provided`);if(!u.default.existsSync(e.executablePath))throw Error(`${e.executablePath} not exists`)}return e},create:async function(e,t,s){T&&await b.install(),(T||s.compiled||await b.shouldPush())&&await b.push(e),await b.start()}},adapter:O,beforeCompile(e){if(process.env.UNI_INPUT_DIR&&"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW){const t=r.parse(a.readFileSync(p.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8")),s=p.default.resolve(process.env.UNI_INPUT_DIR,"unpackage",".automator","app-webview");process.env.UNI_INPUT_DIR=p.default.resolve(s,"src"),process.env.UNI_OUTPUT_DIR=p.default.resolve(s,"unpackage","dist","dev"),a.existsSync(process.env.UNI_INPUT_DIR)&&a.emptyDirSync(process.env.UNI_INPUT_DIR),a.copySync(p.default.resolve(e,"lib","app-webview","project"),process.env.UNI_INPUT_DIR);const i=r.parse(a.readFileSync(p.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8"));a.writeFileSync(p.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),JSON.stringify(Object.assign(Object.assign({},i),{name:t.name||"",appid:t.appid||""}),null,2))}else if(process.env.UNI_INPUT_DIR&&"ios"===process.env.UNI_OS_NAME&&b.app&&b.app.endsWith(".app")){const e=p.default.resolve(process.env.UNI_INPUT_DIR,"uni_modules");if(!u.default.existsSync(e))return;if(!a.readdirSync(e).some((t=>a.existsSync(p.default.resolve(e,t,"utssdk")))))return;process.env.UNI_APP_X="true"===process.env.UNI_APP_X?"1":"0",process.env.HX_DEPENDENCIES_DIR=p.default.join(process.env.UNI_OUTPUT_DIR,"../../../cache/.automator/uts_standard_simulator"),process.env.HX_RUN_DEVICE_TYPE="ios_simulator",b.app&&(process.env.UTS_BASE_INFO=u.default.readFileSync(p.default.resolve(b.app,"Frameworks/DCloudUTSFoundation.framework/uts-info.json"),"utf8")),!process.env.HX_Version&&process.env.UNI_HBUILDERX_PLUGINS&&(process.env.HX_Version=require(p.default.join(process.env.UNI_HBUILDERX_PLUGINS,"about","package.json")).version),H("HX_DEPENDENCIES_DIR",process.env.HX_DEPENDENCIES_DIR),H("UTS_BASE_INFO",process.env.UTS_BASE_INFO)}},afterCompile(){if("ios_simulator"===process.env.HX_RUN_DEVICE_TYPE&&b.app){process.env.UNI_APP_X="1"===process.env.UNI_APP_X?"true":"false";const t=p.default.resolve(process.env.HX_DEPENDENCIES_DIR,"Resources"),s=p.default.resolve(process.env.HX_DEPENDENCIES_DIR,"modules"),r=u.default.existsSync(t),i=u.default.existsSync(s),o=(e=p.default.basename(b.app),p.default.resolve(process.env.HX_DEPENDENCIES_DIR,".automator/"+e));if(!r&&!i)return;if(a.existsSync(o)&&a.emptyDirSync(o),a.copySync(b.app,o),b.app=o,r&&a.copySync(t,p.default.resolve(b.app,"Resources")),i){const e=[];a.readdirSync(s).forEach((t=>{t.endsWith(".framework")&&(e.push(t),a.copySync(p.default.join(s,t),p.default.resolve(b.app,"Frameworks",t)))})),e.forEach((e=>{const t=`'${process.env.UNI_HBUILDERX_PLUGINS}/launcher-tools/tools/uts/optool' 'install' '-c' 'weak' '-p' '@rpath/${e}/${e.replace(".framework","")}' '-t' '${b.app}'`,s=l.execSync(t);H(t,s.toString())}))}if(r||i){const e=l.execSync(`codesign -fs "-" "${b.app}"`);H("codesign success",e.toString())}}var e}};module.exports=X;