From 537be200d04e36aeee993cc6ff2cda2faab5e27e Mon Sep 17 00:00:00 2001 From: zhenyuWang <13641039885@163.com> Date: Wed, 22 May 2024 16:35:40 +0800 Subject: [PATCH] chore(automator): program.swipe --- packages/uni-app-plus/lib/uni.automator.js | 2 +- packages/uni-automator/dist/index.js | 2 +- packages/uni-h5/lib/uni.automator.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/uni-app-plus/lib/uni.automator.js b/packages/uni-app-plus/lib/uni.automator.js index 738bb193563..dba972914a4 100644 --- a/packages/uni-app-plus/lib/uni.automator.js +++ b/packages/uni-app-plus/lib/uni.automator.js @@ -1 +1 @@ -"use strict";var e=require("fs"),t=require("path"),s=require("debug"),a=require("jsonc-parser"),r=require("fs-extra"),i=require("postcss-selector-parser"),o=require("licia/dateFormat"),n=require("util"),l=require("jimp"),c=require("dns"),d=require("child_process");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=u(e),h=u(t),m=u(s),f=u(r),y=u(i),v=u(o),_=u(l),I=u(c);function P(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"body":"uni-"+t}}))}m.default("automator:devtool");const N=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const E=/^win/.test(process.platform);function S(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}const g=m.default("automator:launcher"),w=n.promisify(p.default.readdir),D=n.promisify(p.default.stat);async function U(e){const s=await w(e);return(await Promise.all(s.map((async s=>{const a=t.resolve(e,s);return(await D(a)).isDirectory()?U(a):a})))).reduce(((e,t)=>e.concat(t)),[])}class ${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((()=>(g(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(g(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(e){return U(e).then((s=>{const a=s.map((s=>{const a=(e=>E?e.replace(/\\/g,"/"):e)(t.join(this.DIR_WWW,t.relative(e,s)));return g(`${v.default("yyyy-mm-dd HH:MM:ss:l")} push ${s} ${a}`),this.pushFile(s,a)}));return Promise.all(a)})).then((e=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const A=m.default("automator:simctl");function M(e){const t=parseInt(e);return t>9?String(t):"0"+t}class R extends ${constructor(){super(...arguments),this.bundleVersion=""}async init(){const e=S("node-simctl").Simctl;this.tool=new e({udid:this.id});try{await this.tool.bootDevice()}catch(e){}await this.initSDCard(),A(`${v.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const e=await this.tool.appInfo(this.package);A(`${v.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],A(`${v.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]+M(t[1])+M(t[2])}async install(){return A(`${v.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(){A("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,a)=>{var r,i;void 0!==(null===(r=null==e?void 0:e.area)||void 0===r?void 0:r.x)&&void 0!==(null===(i=null==e?void 0:e.area)||void 0===i?void 0:i.y)?_.default.read(Buffer.from(t,"base64")).then((t=>{const r=e.area.x,i=e.area.y;let o=t.bitmap.width-r;e.area.width&&(o=Math.min(o,e.area.width));let n=t.bitmap.height-i;e.area.height&&(n=Math.min(n,e.area.height)),t.crop(r,i,o,n).getBase64Async(_.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(t)}))}exists(e){return f.default.existsSync(e)?Promise.resolve(!0):Promise.reject(Error(`${e} not exists`))}pushFile(e,t){return Promise.resolve(f.default.copySync(e,t))}adbCommand(e){return new Promise((e=>{e("adbCommand only for App Android!")}))}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 H=S("adbkit"),b=m.default("automator:adb");class x extends ${constructor(){super(...arguments),this.needStart=!0}async init(){if(void 0!==I.default.setDefaultResultOrder&&I.default.setDefaultResultOrder("ipv4first"),this.tool=H.createClient(),b(`${v.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),b(`${v.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{b(`${v.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((e=>{b(`${v.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(b(`${v.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${e}`),e){const e=S("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 "),b(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${e} `)),t.call(this,e)}}return this.tool.install(this.id,this.app).then((()=>{b(`${v.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,a)=>{const r=[];t.on("data",(function(e){r.push(e)})),t.on("end",(function(){var t,i;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)?_.default.read(Buffer.concat(r)).then((t=>{var r,i,o,n;const l=e.area.x,c=e.area.y;let d=t.bitmap.width-l;(null===(r=e.area)||void 0===r?void 0:r.width)&&(d=Math.min(d,null===(i=e.area)||void 0===i?void 0:i.width));let u=t.bitmap.height-c;(null===(o=e.area)||void 0===o?void 0:o.height)&&(u=Math.min(u,null===(n=e.area)||void 0===n?void 0:n.height)),t.crop(l,c,d,u).getBase64Async(_.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(Buffer.concat(r).toString("base64"))}))}))))}adbCommand(e){return new Promise((t=>{this.tool.shell(this.id,e).then((e=>{let s,a="";e.on("data",(e=>{a+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(a)}),50)})),setTimeout((()=>{t(a)}),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=h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher","out","export","pushResources.js"),s=process.env.HX_CONFIG_ADB_PATH||h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher-tools","tools","adbs","adb"),a=[t,s].map((e=>p.default.promises.access(e,p.default.constants.F_OK).then((()=>`${e} exists`)).catch((()=>`${e} not exists`))));return Promise.all(a).then((()=>{const{PushResources:a}=require(t);return new a({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 b(`${v.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${e}`),this.tool.shell(this.id,e).then(H.util.readAll).then((e=>{const t=e.toString();return b(`${v.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 T=m.default("automator:devtool");let C,O=!1;const X={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const k={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>C.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshotWithDevice":{reflect:async(e,t)=>{const s=await C.captureScreenshot(t);return T(`App.captureScreenshot ${s.length}`),{data:s}}},"App.adbCommand":{reflect:async(e,t)=>{const s=await C.adbCommand(t);return T(`App.adbCommand ${s.length}`),{data:s}}}};!function(e){N.forEach((t=>{e[t]=function(e){return{reflect:async(t,s)=>t(e,s,!1),params:e=>(e.selector&&(e.selector=y.default(P).processSync(e.selector)),e)}}(t)}))}(k);const j={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]),C=function(e,t){return"ios"===e?new R(t):new x(t)}(e.platform,e),await C.init();const s=await C.version();if(s){if(e.version){const t=C.formatVersion(function(e,t){if(e.endsWith(".txt"))try{const s=p.default.readFileSync(e).toString().match(X[t]);if(s)return s[1]}catch(e){console.error(e)}return e}(e.version,e.platform));T(`version: ${s}`),T(`newVersion: ${t}`),t!==s&&(O=!0)}}else O=!0;if(O){if(!e.executablePath)throw Error(`app-plus->${e.platform}->executablePath is not provided`);if(!p.default.existsSync(e.executablePath))throw Error(`${e.executablePath} not exists`)}return e},create:async function(e,t,s){O&&await C.install(),(O||s.compiled||await C.shouldPush())&&await C.push(e),await C.start()}},adapter:k,beforeCompile(e){if(process.env.UNI_INPUT_DIR&&"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW){const t=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8")),s=h.default.resolve(process.env.UNI_INPUT_DIR,"unpackage",".automator","app-webview");process.env.UNI_INPUT_DIR=h.default.resolve(s,"src"),process.env.UNI_OUTPUT_DIR=h.default.resolve(s,"unpackage","dist","dev"),r.existsSync(process.env.UNI_INPUT_DIR)&&r.emptyDirSync(process.env.UNI_INPUT_DIR),r.copySync(h.default.resolve(e,"lib","app-webview","project"),process.env.UNI_INPUT_DIR);const i=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8"));r.writeFileSync(h.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&&C.app&&C.app.endsWith(".app")){const e=h.default.resolve(process.env.UNI_INPUT_DIR,"uni_modules");if(!p.default.existsSync(e))return;if(!r.readdirSync(e).some((t=>r.existsSync(h.default.resolve(e,t,"utssdk")))))return;process.env.UNI_APP_X="true"===process.env.UNI_APP_X?"1":"0",process.env.HX_DEPENDENCIES_DIR=h.default.join(process.env.UNI_OUTPUT_DIR,"../../../cache/.automator/uts_standard_simulator"),process.env.HX_RUN_DEVICE_TYPE="ios_simulator",C.app&&(process.env.UTS_BASE_INFO=p.default.readFileSync(h.default.resolve(C.app,"Frameworks/DCloudUTSFoundation.framework/uts-info.json"),"utf8")),!process.env.HX_Version&&process.env.UNI_HBUILDERX_PLUGINS&&(process.env.HX_Version=require(h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"about","package.json")).version),T("HX_DEPENDENCIES_DIR",process.env.HX_DEPENDENCIES_DIR),T("UTS_BASE_INFO",process.env.UTS_BASE_INFO)}},afterCompile(){if("ios_simulator"===process.env.HX_RUN_DEVICE_TYPE&&C.app){process.env.UNI_APP_X="1"===process.env.UNI_APP_X?"true":"false";const t=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"Resources"),s=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"modules"),a=p.default.existsSync(t),i=p.default.existsSync(s),o=(e=h.default.basename(C.app),h.default.resolve(process.env.HX_DEPENDENCIES_DIR,".automator/"+e));if(!a&&!i)return;if(r.existsSync(o)&&r.emptyDirSync(o),r.copySync(C.app,o),C.app=o,a&&r.copySync(t,h.default.resolve(C.app,"Resources")),i){const e=[];r.readdirSync(s).forEach((t=>{t.endsWith(".framework")&&(e.push(t),r.copySync(h.default.join(s,t),h.default.resolve(C.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' '${C.app}'`,s=d.execSync(t);T(t,s.toString())}))}if(a||i){const e=d.execSync(`codesign -fs "-" "${C.app}"`);T("codesign success",e.toString())}}var e}};module.exports=j; +"use strict";var e=require("fs"),t=require("path"),s=require("debug"),a=require("jsonc-parser"),r=require("fs-extra"),i=require("postcss-selector-parser"),o=require("licia/dateFormat"),n=require("util"),l=require("jimp"),c=require("child_process"),d=require("dns");function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=u(e),h=u(t),m=u(s),f=u(r),y=u(i),v=u(o),_=u(l),I=u(d);function P(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"body":"uni-"+t}}))}m.default("automator:devtool");const N=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const E=/^win/.test(process.platform);function w(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}const S=m.default("automator:launcher"),$=n.promisify(p.default.readdir),g=n.promisify(p.default.stat);async function D(e){const s=await $(e);return(await Promise.all(s.map((async s=>{const a=t.resolve(e,s);return(await g(a)).isDirectory()?D(a):a})))).reduce(((e,t)=>e.concat(t)),[])}class U{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((()=>(S(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(S(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(e){return D(e).then((s=>{const a=s.map((s=>{const a=(e=>E?e.replace(/\\/g,"/"):e)(t.join(this.DIR_WWW,t.relative(e,s)));return S(`${v.default("yyyy-mm-dd HH:MM:ss:l")} push ${s} ${a}`),this.pushFile(s,a)}));return Promise.all(a)})).then((e=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const A=m.default("automator:simctl");function M(e){const t=parseInt(e);return t>9?String(t):"0"+t}class R extends U{constructor(){super(...arguments),this.bundleVersion=""}async init(){const e=w("node-simctl").Simctl;this.tool=new e({udid:this.id});try{await this.tool.bootDevice()}catch(e){}await this.initSDCard(),A(`${v.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const e=await this.tool.appInfo(this.package);A(`${v.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],A(`${v.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]+M(t[1])+M(t[2])}async install(){return A(`${v.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(){A("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,a)=>{var r,i;void 0!==(null===(r=null==e?void 0:e.area)||void 0===r?void 0:r.x)&&void 0!==(null===(i=null==e?void 0:e.area)||void 0===i?void 0:i.y)?_.default.read(Buffer.from(t,"base64")).then((t=>{const r=e.area.x,i=e.area.y;let o=t.bitmap.width-r;e.area.width&&(o=Math.min(o,e.area.width));let n=t.bitmap.height-i;e.area.height&&(n=Math.min(n,e.area.height)),t.crop(r,i,o,n).getBase64Async(_.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(t)}))}exists(e){return f.default.existsSync(e)?Promise.resolve(!0):Promise.reject(Error(`${e} not exists`))}pushFile(e,t){return Promise.resolve(f.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:a,duration:r}=e;c.exec(`idb ui swipe ${s.x} ${s.y} ${a.x} ${a.y} --duration ${r?r/1e3:.1}`,(e=>{e&&console.error(`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 H=w("adbkit"),x=m.default("automator:adb");class b extends U{constructor(){super(...arguments),this.needStart=!0}async init(){if(void 0!==I.default.setDefaultResultOrder&&I.default.setDefaultResultOrder("ipv4first"),this.tool=H.createClient(),x(`${v.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),x(`${v.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{x(`${v.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((e=>{x(`${v.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(x(`${v.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${e}`),e){const e=w("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 "),x(`${v.default("yyyy-mm-dd HH:MM:ss:l")} ${e} `)),t.call(this,e)}}return this.tool.install(this.id,this.app).then((()=>{x(`${v.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,a)=>{const r=[];t.on("data",(function(e){r.push(e)})),t.on("end",(function(){var t,i;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)?_.default.read(Buffer.concat(r)).then((t=>{var r,i,o,n;const l=e.area.x,c=e.area.y;let d=t.bitmap.width-l;(null===(r=e.area)||void 0===r?void 0:r.width)&&(d=Math.min(d,null===(i=e.area)||void 0===i?void 0:i.width));let u=t.bitmap.height-c;(null===(o=e.area)||void 0===o?void 0:o.height)&&(u=Math.min(u,null===(n=e.area)||void 0===n?void 0:n.height)),t.crop(l,c,d,u).getBase64Async(_.default.MIME_PNG).then((e=>{s(e.replace("data:image/png;base64,",""))})).catch((e=>{a(e)}))})).catch((e=>{a(e)})):s(Buffer.concat(r).toString("base64"))}))}))))}adbCommand(e){return new Promise((t=>{this.tool.shell(this.id,e).then((e=>{let s,a="";e.on("data",(e=>{a+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(a)}),50)})),setTimeout((()=>{t(a)}),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,a="";e.on("data",(e=>{a+=e.toString(),s&&clearTimeout(s),s=setTimeout((()=>{t(a)}),50)})),setTimeout((()=>{t(a)}),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=h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher","out","export","pushResources.js"),s=process.env.HX_CONFIG_ADB_PATH||h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"launcher-tools","tools","adbs","adb"),a=[t,s].map((e=>p.default.promises.access(e,p.default.constants.F_OK).then((()=>`${e} exists`)).catch((()=>`${e} not exists`))));return Promise.all(a).then((()=>{const{PushResources:a}=require(t);return new a({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 x(`${v.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${e}`),this.tool.shell(this.id,e).then(H.util.readAll).then((e=>{const t=e.toString();return x(`${v.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 T=m.default("automator:devtool");let C,O=!1;const X={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const k={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>C.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshotWithDevice":{reflect:async(e,t)=>{const s=await C.captureScreenshot(t);return T(`App.captureScreenshot ${s.length}`),{data:s}}},"App.adbCommand":{reflect:async(e,t)=>{const s=await C.adbCommand(t);return T(`App.adbCommand ${s.length}`),{data:s}}},"App.swipe":{reflect:async(e,t)=>{const s=await C.swipe(t);return T(`App.swipe ${s.length}`),{data:s}}}};!function(e){N.forEach((t=>{e[t]=function(e){return{reflect:async(t,s)=>t(e,s,!1),params:e=>(e.selector&&(e.selector=y.default(P).processSync(e.selector)),e)}}(t)}))}(k);const j={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]),C=function(e,t){return"ios"===e?new R(t):new b(t)}(e.platform,e),await C.init();const s=await C.version();if(s){if(e.version){const t=C.formatVersion(function(e,t){if(e.endsWith(".txt"))try{const s=p.default.readFileSync(e).toString().match(X[t]);if(s)return s[1]}catch(e){console.error(e)}return e}(e.version,e.platform));T(`version: ${s}`),T(`newVersion: ${t}`),t!==s&&(O=!0)}}else O=!0;if(O){if(!e.executablePath)throw Error(`app-plus->${e.platform}->executablePath is not provided`);if(!p.default.existsSync(e.executablePath))throw Error(`${e.executablePath} not exists`)}return e},create:async function(e,t,s){O&&await C.install(),(O||s.compiled||await C.shouldPush())&&await C.push(e),await C.start()}},adapter:k,beforeCompile(e){if(process.env.UNI_INPUT_DIR&&"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW){const t=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8")),s=h.default.resolve(process.env.UNI_INPUT_DIR,"unpackage",".automator","app-webview");process.env.UNI_INPUT_DIR=h.default.resolve(s,"src"),process.env.UNI_OUTPUT_DIR=h.default.resolve(s,"unpackage","dist","dev"),r.existsSync(process.env.UNI_INPUT_DIR)&&r.emptyDirSync(process.env.UNI_INPUT_DIR),r.copySync(h.default.resolve(e,"lib","app-webview","project"),process.env.UNI_INPUT_DIR);const i=a.parse(r.readFileSync(h.default.resolve(process.env.UNI_INPUT_DIR,"manifest.json"),"utf8"));r.writeFileSync(h.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&&C.app&&C.app.endsWith(".app")){const e=h.default.resolve(process.env.UNI_INPUT_DIR,"uni_modules");if(!p.default.existsSync(e))return;if(!r.readdirSync(e).some((t=>r.existsSync(h.default.resolve(e,t,"utssdk")))))return;process.env.UNI_APP_X="true"===process.env.UNI_APP_X?"1":"0",process.env.HX_DEPENDENCIES_DIR=h.default.join(process.env.UNI_OUTPUT_DIR,"../../../cache/.automator/uts_standard_simulator"),process.env.HX_RUN_DEVICE_TYPE="ios_simulator",C.app&&(process.env.UTS_BASE_INFO=p.default.readFileSync(h.default.resolve(C.app,"Frameworks/DCloudUTSFoundation.framework/uts-info.json"),"utf8")),!process.env.HX_Version&&process.env.UNI_HBUILDERX_PLUGINS&&(process.env.HX_Version=require(h.default.join(process.env.UNI_HBUILDERX_PLUGINS,"about","package.json")).version),T("HX_DEPENDENCIES_DIR",process.env.HX_DEPENDENCIES_DIR),T("UTS_BASE_INFO",process.env.UTS_BASE_INFO)}},afterCompile(){if("ios_simulator"===process.env.HX_RUN_DEVICE_TYPE&&C.app){process.env.UNI_APP_X="1"===process.env.UNI_APP_X?"true":"false";const t=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"Resources"),s=h.default.resolve(process.env.HX_DEPENDENCIES_DIR,"modules"),a=p.default.existsSync(t),i=p.default.existsSync(s),o=(e=h.default.basename(C.app),h.default.resolve(process.env.HX_DEPENDENCIES_DIR,".automator/"+e));if(!a&&!i)return;if(r.existsSync(o)&&r.emptyDirSync(o),r.copySync(C.app,o),C.app=o,a&&r.copySync(t,h.default.resolve(C.app,"Resources")),i){const e=[];r.readdirSync(s).forEach((t=>{t.endsWith(".framework")&&(e.push(t),r.copySync(h.default.join(s,t),h.default.resolve(C.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' '${C.app}'`,s=c.execSync(t);T(t,s.toString())}))}if(a||i){const e=c.execSync(`codesign -fs "-" "${C.app}"`);T("codesign success",e.toString())}}var e}};module.exports=j; diff --git a/packages/uni-automator/dist/index.js b/packages/uni-automator/dist/index.js index 4ef9a8445c5..b9b0436d011 100644 --- a/packages/uni-automator/dist/index.js +++ b/packages/uni-automator/dist/index.js @@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */function ct(t,e,n,s){var i,o=arguments.length,r=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}var pt;function lt(t,e){const n=e.value;return e.value=async function(e){return(await(null==n?void 0:n.call(this,e)))(t)},e}function ut(t,e,n){return lt(pt.RUNTIME,n)}function ht(t,e,n){return lt(pt.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(pt||(pt={}));class dt{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===pt.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(t,e):this.puppet.runtimeConnection.send(t,e)}on(t,e){this.puppet.on(t,e)}}class mt extends dt{constructor(t,e){super(t),this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId,this.videoId=e.videoId}async getData(t){return this.invokeMethod("Element.getData",t)}async setData(t){return this.invokeMethod("Element.setData",t)}async callMethod(t){return this.invokeMethod("Element.callMethod",t)}async getElement(t){return this.invokeMethod("Element.getElement",t)}async getElements(t){return this.invokeMethod("Element.getElements",t)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(t){return this.invokeMethod("Element.getHTML",t)}async getAttributes(t){return this.invokeMethod("Element.getAttributes",t)}async getStyles(t){return this.invokeMethod("Element.getStyles",t)}async getDOMProperties(t){return this.invokeMethod("Element.getDOMProperties",t)}async getProperties(t){return this.invokeMethod("Element.getProperties",t)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(t){return this.invokeMethod("Element.touchstart",t)}async touchmove(t){return this.invokeMethod("Element.touchmove",t)}async touchend(t){return this.invokeMethod("Element.touchend",t)}async triggerEvent(t){return this.invokeMethod("Element.triggerEvent",t)}async callFunction(t){return this.invokeMethod("Element.callFunction",t)}async callContextMethod(t){return this.invokeMethod("Element.callContextMethod",t)}invokeMethod(t,e={}){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.invoke(t,e)}}ct([ut],mt.prototype,"getData",null),ct([ut],mt.prototype,"setData",null),ct([ut],mt.prototype,"callMethod",null),ct([ht],mt.prototype,"getElement",null),ct([ht],mt.prototype,"getElements",null),ct([ht],mt.prototype,"getOffset",null),ct([ht],mt.prototype,"getHTML",null),ct([ht],mt.prototype,"getAttributes",null),ct([ht],mt.prototype,"getStyles",null),ct([ht],mt.prototype,"getDOMProperties",null),ct([ht],mt.prototype,"getProperties",null),ct([ht],mt.prototype,"tap",null),ct([ht],mt.prototype,"longpress",null),ct([ht],mt.prototype,"touchstart",null),ct([ht],mt.prototype,"touchmove",null),ct([ht],mt.prototype,"touchend",null),ct([ht],mt.prototype,"triggerEvent",null),ct([ht],mt.prototype,"callFunction",null),ct([ht],mt.prototype,"callContextMethod",null);const gt=Object.prototype.hasOwnProperty,vt=Array.isArray,yt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function ft(t,e){if(vt(t))return t;if(e&&(n=e,s=t,gt.call(n,s)))return[t];var n,s;const i=[];return t.replace(yt,(function(t,e,n,s){return i.push(n?s.replace(/\\(\\)?/g,"$1"):e||t),s})),i}function wt(t,e){const n=ft(e,t);let s;for(s=n.shift();null!=s;){if(null==(t=t[s]))return;s=n.shift()}return t}const Pt=require("util"),Mt=["scrollLeft","scrollTop","scrollWidth","scrollHeight"];class It{constructor(t,e,n){this.puppet=t,this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId||null,this.videoId=e.videoId||null,this.tagName=e.tagName,this.nvue=e.nvue,this.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new mt(t,e)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[Pt.inspect.custom](){return this.toJSON()}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((t=>It.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap)))}async size(){const[t,e]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:t,height:e}}async offset(){const{left:t,top:e}=await this.api.getOffset();return{left:t,top:e}}async text(){return this.domProperty("innerText")}async attribute(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.puppet.isX?this.domProperty("value"):this.property("value")}async property(t){if(!F.default(t))throw Error("name must be a string");if(this.puppet.checkProperty){let e=this.publicProps;if(e||(this.publicProps=e=await this._property("__propPublic")),!e[t])throw Error(`${this.tagName}.${t} not exists`)}return this.puppet.isX&&"h5"===process.env.UNI_PLATFORM&&Mt.includes(t)?await this.domProperty(t):this._property(t)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getStyles({names:[t]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue||"true"===process.env.UNI_APP_X?this.api.longpress():(await this.touchstart(),await z.default(350),this.touchend())}async trigger(t,e){const n={type:t};return Y.default(e)||(n.detail=e),this.api.triggerEvent(n)}async touchstart(t){return this.api.touchstart(t)}async touchmove(t){return this.api.touchmove(t)}async touchend(t){return this.api.touchend(t)}async domProperty(t){return it((async t=>(await this.api.getDOMProperties({names:t})).properties),t)}_property(t){return it((async t=>(await this.api.getProperties({names:t})).properties),t)}send(t,e){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.puppet.send(t,e)}async callFunction(t,...e){return(await this.api.callFunction({functionName:t,args:e})).result}static create(t,e,n){let s,i=n.get(e.elementId);if(i)return i;if(e.nodeId)s=kt;else switch(e.tagName.toLowerCase()){case"input":s=At;break;case"textarea":s=Et;break;case"scroll-view":s=_t;break;case"swiper":s=Tt;break;case"movable-view":s=Ut;break;case"switch":s=bt;break;case"slider":s=Ct;break;case"video":s=Nt;break;default:s=It}return i=new s(t,e,n),n.set(e.elementId,i),i}}class kt extends It{async setData(t){return this.api.setData({data:t})}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class At extends It{async input(t){return this.callFunction("input.input",t)}}class Et extends It{async input(t){return this.callFunction("textarea.input",t)}}class _t extends It{async scrollTo(t,e){return this.callFunction("scroll-view.scrollTo",t,e)}async property(t){return"scrollTop"===t?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===t?this.callFunction("scroll-view.scrollLeft"):super.property(t)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class Tt extends It{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class Ut extends It{async moveTo(t,e){return this.callFunction("movable-view.moveTo",t,e)}async property(t){return"x"===t?this._property("_translateX"):"y"===t?this._property("_translateY"):super.property(t)}}class bt extends It{async tap(){return this.callFunction("switch.tap")}}class Ct extends It{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class Nt extends It{async callContextMethod(t,...e){return await this.api.callContextMethod({method:t,args:e})}}class Ot extends dt{constructor(t,e){super(t),this.id=e.id}async getData(t){return this.invokeMethod("Page.getData",t)}async setData(t){return this.invokeMethod("Page.setData",t)}async callMethod(t){return this.invokeMethod("Page.callMethod",t)}async callMethodWithCallback(t){return this.invokeMethod("Page.callMethodWithCallback",t)}async getElement(t){return this.invokeMethod("Page.getElement",t)}async getElements(t){return this.invokeMethod("Page.getElements",t)}async getWindowProperties(t){return this.invokeMethod("Page.getWindowProperties",t)}invokeMethod(t,e={}){return e.pageId=this.id,this.invoke(t,e)}}ct([ut],Ot.prototype,"getData",null),ct([ut],Ot.prototype,"setData",null),ct([ut],Ot.prototype,"callMethod",null),ct([ut],Ot.prototype,"callMethodWithCallback",null),ct([ht],Ot.prototype,"getElement",null),ct([ht],Ot.prototype,"getElements",null),ct([ht],Ot.prototype,"getWindowProperties",null);const Rt=require("util");class St{constructor(t,e){this.puppet=t,this.id=e.id,this.path=e.path,this.query=e.query,this.elementMap=new Map,this.api=new Ot(t,e)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[Rt.inspect.custom](){return this.toJSON()}async waitFor(t){return G.default(t)?await z.default(t):B.default(t)?j.default(t,0,50):F.default(t)?j.default((async()=>{if("true"===process.env.UNI_APP_X){return!!await this.$(t)}return(await this.$$(t)).length>0}),0,50):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((e=>It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)))}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async setData(t){return this.api.setData({data:t})}async size(){const[t,e]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:t,height:e}}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}async callMethodWithCallback(t,...e){return await this.api.callMethodWithCallback({method:t,args:e})}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=F.default(t);e&&(t=[t]);const{properties:n}=await this.api.getWindowProperties({names:t});return e?n[0]:n}static create(t,e,n){let s=n.get(e.id);return s?(s.path=e.path,s.query=e.query,s):(s=new St(t,e),n.set(e.id,s),s)}}class Dt extends dt{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(t){return this.invoke("App.callUniMethod",t)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(t){return this.invoke("App.mockUniMethod",t)}async captureScreenshotByRuntime(t){return this.invoke("App.captureScreenshot",t)}async captureScreenshotWithDeviceByRuntime(t){return this.invoke("App.captureScreenshotWithDevice",t)}async socketEmitter(t){return this.invoke("App.socketEmitter",t)}async callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",t)}async adbCommand(t){return this.invoke("App.adbCommand",t)}async exit(){return this.invoke("App.exit")}async addBinding(t){return this.invoke("App.addBinding",t)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(t){return this.on("App.logAdded",t)}onBindingCalled(t){return this.on("App.bindingCalled",t)}onExceptionThrown(t){return this.on("App.exceptionThrown",t)}}ct([ut],Dt.prototype,"getPageStack",null),ct([ut],Dt.prototype,"callUniMethod",null),ct([ut],Dt.prototype,"getCurrentPage",null),ct([ut],Dt.prototype,"mockUniMethod",null),ct([ut],Dt.prototype,"captureScreenshotByRuntime",null),ct([ut],Dt.prototype,"captureScreenshotWithDeviceByRuntime",null),ct([ut],Dt.prototype,"socketEmitter",null),ct([ht],Dt.prototype,"callFunction",null),ct([ht],Dt.prototype,"captureScreenshot",null),ct([ht],Dt.prototype,"adbCommand",null),ct([ht],Dt.prototype,"exit",null),ct([ht],Dt.prototype,"addBinding",null),ct([ht],Dt.prototype,"enableLog",null);class xt extends dt{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(t){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(t){this.puppet.once("Tool.onRemoteDebugConnected",t),this.puppet.once("Tool.onPreviewConnected",t)}}function jt(t){return new Promise((e=>setTimeout(e,t)))}ct([ht],xt.prototype,"getInfo",null),ct([ht],xt.prototype,"enableRemoteDebug",null),ct([ht],xt.prototype,"close",null),ct([ht],xt.prototype,"getTestAccounts",null);class $t extends a.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new Dt(t),this.toolApi=new xt(t),this.appApi.onLogAdded((t=>{this.emit("console",t)})),this.appApi.onBindingCalled((({name:t,args:e})=>{try{const n=this.appBindings.get(t);n&&n(...e)}catch(t){}})),this.appApi.onExceptionThrown((t=>{this.emit("exception",t)}))}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map((t=>St.create(this.puppet,t,this.pageMap)))}async navigateTo(t){return this.changeRoute("navigateTo",t)}async redirectTo(t){return this.changeRoute("redirectTo",t)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(t){return this.changeRoute("reLaunch",t)}async switchTab(t){return this.changeRoute("switchTab",t)}async currentPage(){const{id:t,path:e,query:n}=await this.appApi.getCurrentPage();return St.create(this.puppet,{id:t,path:e,query:n},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(t,...e){return(await this.appApi.callUniMethod({method:t,args:e})).result}async mockUniMethod(t,e,...n){return B.default(e)||(s=e,F.default(s)&&(s=V.default(s),J.default(s,"function")||J.default(s,"() =>")))?this.appApi.mockUniMethod({method:t,functionDeclaration:e.toString(),args:n}):this.appApi.mockUniMethod({method:t,result:e});var s}async restoreUniMethod(t){return this.appApi.mockUniMethod({method:t})}async evaluate(t,...e){return(await this.appApi.callFunction({functionDeclaration:t.toString(),args:e})).result}async pageScrollTo(t){await this.callUniMethod("pageScrollTo",{scrollTop:t,duration:0})}async close(){try{await this.appApi.exit()}catch(t){}await jt(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){return this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(t){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:e}=await this.toolApi.enableRemoteDebug({auto:t});var n;e&&await(n=e,new Promise((t=>{W.default.generate(n,{small:!0},(e=>{process.stdout.write(e),t(void 0)}))})));const s=new Promise((t=>{this.toolApi.onRemoteDebugConnected((async()=>{await jt(1e3),t(void 0)}))})),i=new Promise((t=>{this.puppet.setRemoteRuntimeConnectionCallback((()=>{t(void 0)}))}));return Promise.all([s,i])}disconnect(){this.puppet.dispose()}on(t,e){return"console"===t&&this.appApi.enableLog(),super.on(t,e),this}async exposeFunction(t,e){if(this.appBindings.has(t))throw Error(`Failed to expose function with name ${t}: already exists!`);this.appBindings.set(t,e),await this.appApi.addBinding({name:t})}async checkVersion(){}async screenshot(t){const e=this.puppet.isX&&"app-plus"===this.puppet.platform?(null==t?void 0:t.deviceShot)?"captureScreenshotWithDeviceByRuntime":"captureScreenshotByRuntime":"captureScreenshot",{data:n}=await this.appApi[e]({id:null==t?void 0:t.id,fullPage:null==t?void 0:t.fullPage,area:null==t?void 0:t.area,offsetX:null==t?void 0:t.offsetX,offsetY:null==t?void 0:t.offsetY});if(!(null==t?void 0:t.path))return n;await X.default.writeFile(t.path,n,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){if(this.puppet.isVue3&&"h5"===process.env.UNI_PLATFORM&&"navigateBack"!==t){const{__id__:n}=await this.callUniMethod(t,{url:e,isAutomatedTesting:!0}),s=Date.now();return await j.default((async()=>{if(Date.now()-s>1e4)throw Error(`${t} to ${e} failed, unable to get the correct current page`);let i;try{i=await this.currentPage()}catch(t){return!1}return i.id===n&&i}),0,1e3)}return await this.callUniMethod(t,{url:e}),await jt(1e3),await this.currentPage()}async socketEmitter(t){return this.appApi.socketEmitter(t)}async adbCommand(t){return"android"===process.env.UNI_APP_PLATFORM?await this.appApi.adbCommand(t):Error("Program.adbCommand is only supported on the app android platform")}}class qt{constructor(t){this.options=t}has(t){return!!this.options[t]}send(t,e,n){const s=this.options[e];if(!s)return Promise.reject(Error(`adapter for ${e} not found`));const i=s.reflect;return i?(s.params&&(n=s.params(n)),"function"==typeof i?i(t.send.bind(t),n):(e=i,t.send(e,n))):Promise.reject(Error(`${e}'s reflect is required`))}}const Lt=N.default("automator:puppet"),Ft=".automator.json";function Ht(t){try{return require(t)}catch(t){}}function Wt(t,e,n,s){const i=function(t,e,n){let s,i;return process.env.UNI_OUTPUT_DIR?(i=C.default.join(process.env.UNI_OUTPUT_DIR,`../.automator/${e}`,Ft),s=Ht(i)):(i=C.default.join(t,`dist/${n}/.automator/${e}`,Ft),s=Ht(i),s||(i=C.default.join(t,`unpackage/dist/${n}/.automator/${e}`,Ft),s=Ht(i))),Lt(`${i}=>${JSON.stringify(s)}`),s}(t,n,s);if(!i||!i.wsEndpoint)return!1;const o=require("../package.json").version;if(i.version!==o)return Lt(`unmet=>${i.version}!==${o}`),!1;const r=function(t){let e;try{const t=L.default.v4.sync();e=q.default.ip(t&&t.interface),e&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(e)||(e=void 0))}catch(t){}return"ws://"+(e||"localhost")+":"+t}(e);return Lt(`wsEndpoint=>${r}`),i.wsEndpoint===r}class Xt extends a.EventEmitter{constructor(t,e){if(super(),this.isX=!1,this.isVue3=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),e)this.target=e;else{if(this.target=null,"h5"===t)try{this.target=ot("@dcloudio/uni-h5/lib/h5/uni.automator.js")}catch(t){}this.target||(this.target=ot(`@dcloudio/uni-${"app"===t?"app-plus":t}/lib/uni.automator.js`))}if(!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new qt(this.target.adapter||{})}setCompiler(t){this.compiler=t}setRuntimeServer(t){this.wss=t}setRemoteRuntimeConnectionCallback(t){this.remoteRuntimeConnectionCallback=t}setRuntimeConnection(t){this.runtimeConnection=t,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(t){this.devtoolConnection=t}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const e=this.target.devtools.required;return!e||!e.find((e=>!b.default.existsSync(C.default.join(t,e))))}validateDevtools(t){const e=this.target.devtools.validate;return e?e(t,this):Promise.resolve(t)}createDevtools(t,e,n){const s=this.target.devtools.create;return s?(e.timeout=n,s(t,e,this)):Promise.resolve()}shouldCompile(t,e,n,s){this.compiled=!0;const i=this.target.shouldCompile;if(i)this.compiled=i(n,s);else if(!0===n.compile)this.compiled=!0;else{if("false"===process.env.UNI_AUTOMATOR_COMPILE)return!1;this.compiled=!Wt(t,e,this.platform,this.mode)}return this.compiled}beforeCompile(){this.target.beforeCompile&&this.target.beforeCompile(C.default.resolve(__dirname,".."))}afterCompile(){this.target.afterCompile&&this.target.afterCompile()}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const t=this.target.mode;return t||("production"===process.env.NODE_ENV?"build":"dev")}}const Bt=N.default("automator:compiler"),Vt=/The\s+(.*)\s+directory is ready/;class Jt{constructor(t){this.puppet=t,this.puppet.setCompiler(this)}compile(t){const e=this.puppet.mode,n=this.puppet.platform;let s=t.silent;const i=t.port,o=t.host,r=`${e}:${n}`,a=t.projectPath,[c,p]=this.getSpawnArgs(t,r);p.push("--auto-port"),p.push(K.default(i)),o&&(p.push("--auto-host"),p.push(o));const l={cwd:t.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===e?"production":"development"})};return new Promise(((t,i)=>{const o=o=>{const r=o.toString().trim();if(!s&&console.log(r),r.includes("- Network")||r.includes("> Network")||r.includes("➜ Network")){const e=r.match(/Network:(.*)/)[1].trim();Bt(`url: ${e}`),t({path:e})}else if(r.includes("DONE Build failed"))i(r);else if(r.includes("DONE Build complete")){const i=r.match(Vt);let o="";if(i&&i.length>1)o=C.default.join(a,i[1]);else{const t=this.puppet.isX&&"app-plus"===n?"app":n;o=C.default.join(a,`dist/${e}/${t}`),T.existsSync(o)||(o=process.env.UNI_OUTPUT_DIR)}this.puppet.afterCompile(),s=!0,this.stop(),t({path:"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW?process.env.UNI_OUTPUT_DIR:o})}};Bt(`${c} ${p.join(" ")} %o`,l),this.cliProcess=E.spawn(c,p,l),this.cliProcess.on("error",(t=>{i(t)})),this.cliProcess.stdout.on("data",o),this.cliProcess.stderr.on("data",o)}))}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(t,e){let n;const s=t.cliPath;try{n=require(C.default.join(s,"package.json"))}catch(t){}let i=this.puppet.isX;if(n&&(n.devDependencies&&n.devDependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),!i&&n.dependencies&&n.dependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),n.scripts&&n.scripts[e]))return[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",e,"--"]];this.puppet.isVue3=i,["android","ios"].includes(process.env.UNI_OS_NAME)&&(process.env.UNI_APP_PLATFORM=process.env.UNI_OS_NAME);let o=this.puppet.platform;if("app-plus"===this.puppet.platform&&this.puppet.isX&&(o="android"===process.env.UNI_APP_PLATFORM?"app-android":"ios"===process.env.UNI_APP_PLATFORM?"app-ios":"app"),process.env.UNI_INPUT_DIR=t.projectPath,process.env.UNI_OUTPUT_DIR=C.default.join(t.projectPath,`unpackage/dist/${this.puppet.mode}/${o}`),process.env.UNI_HBUILDERX_PLUGINS||T.existsSync(C.default.resolve(s,"../about"))&&(process.env.UNI_HBUILDERX_PLUGINS=C.default.dirname(s)),this.puppet.beforeCompile(),i){const t="app-plus"===this.puppet.platform?"app":this.puppet.platform;return process.env.UNI_PLATFORM=t,[process.env.UNI_NODE_PATH||"node",[require.resolve("@dcloudio/vite-plugin-uni/bin/uni.js",{paths:[s]}),"-p",t]]}return[process.env.UNI_NODE_PATH||"node",[C.default.join(s,"bin/uniapp-cli.js")]]}}const Gt=N.default("automator:launcher"),zt="true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM?12e4:24e4;class Yt{async launch(t){const{port:e,cliPath:n,timeout:i,projectPath:o}=await this.validate(t);let r={};"app"===t.platform||"app-plus"===t.platform?(r=t.app||t["app-plus"],"true"===process.env.UNI_APP_X&&r["uni-app-x"]&&(r=s.recursive(!0,r,r["uni-app-x"])),delete r["uni-app-x"]):r=t[t.platform],r||(r={}),r.projectPath=o,Gt(r),this.puppet=new Xt(t.platform,r.puppet),r=await this.puppet.validateDevtools(r);let a=this.puppet.shouldCompile(o,e,t,r),c=process.env.UNI_OUTPUT_DIR||o;if(a||this.puppet.validateProject(c)||(c=C.default.join(o,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(c=C.default.join(o,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(a=!0))),a){this.puppet.compiled=t.compile=!0,this.compiler=new Jt(this.puppet);const s=await this.compiler.compile({host:t.host,port:e,cliPath:n,projectPath:o,silent:!!t.silent});s.path&&(c=s.path)}const p=[];return p.push(this.createRuntimeConnection(e,i)),p.push(this.puppet.createDevtools(c,r,i)),new Promise(((t,n)=>{Promise.all(p).then((([n,s])=>{n&&this.puppet.setRuntimeConnection(n),s&&this.puppet.setDevtoolConnection(s),N.default("automator:program")("ready");const i=r.teardown||"disconnect";t(new $t(this.puppet,{teardown:i,port:e}))})).catch((t=>n(t)))}))}resolveCliPath(t){if(!t)return t;try{const{dependencies:e,devDependencies:n}=require(C.default.join(t,"package.json"));if(Kt(n)||Kt(e))return t}catch(t){}}resolveProjectPath(t,e){return t||(t=process.env.UNI_INPUT_DIR||process.cwd()),O.default(t)&&(t=C.default.resolve(t)),b.default.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=process.env.UNI_CLI_PATH||t.cliPath;if(n=this.resolveCliPath(n||""),!n&&(n=this.resolveCliPath(process.cwd())),!n&&(n=this.resolveCliPath(e)),!n)throw Error("cliPath is not provided");if("false"!==process.env.UNI_APP_X){const t=this.getManifestJson(e);("true"===process.env.UNI_APP_X||"uni-app-x"in t)&&(process.env.UNI_APP_X="true",t.appid&&(process.env.UNI_APP_ID=t.appid))}process.env.UNI_AUTOMATOR_HOST&&(t.host=process.env.UNI_AUTOMATOR_HOST),process.env.UNI_AUTOMATOR_PORT&&(t.port=parseInt(process.env.UNI_AUTOMATOR_PORT));return{port:await async function(t,e){const n=await H.default(t||e);if(t&&n!==t)throw Error(`Port ${t} is in use, please specify another port`);return n}(t.port||9520),cliPath:n,timeout:t.timeout||zt,projectPath:e}}getManifestJson(t){if(t){const e=C.default.join(t,"manifest.json");if(b.default.existsSync(e))return i.parse(b.default.readFileSync(e,"utf8"))}return{}}async createRuntimeConnection(t,e){return at.createRuntimeConnection(t,this.puppet,e)}}function Kt(t){return!!t&&!(!t["@dcloudio/vue-cli-plugin-uni"]&&!t["@dcloudio/vite-plugin-uni"])}exports.Automator=class{constructor(){this.launcher=new Yt}async launch(t){return this.launcher.launch(t)}},exports.initUni=t=>new Proxy({},{get(e,n){return"connectSocket"===n?async(...e)=>{const s=`${Date.now()}-${Math.random()}`;return e[0].id=s,await t.callUniMethod(n,...e).then((n=>{nt(e[0],n),et.set(s,new Map);const i={id:s,onMessage:e=>{t.socketEmitter({id:s,method:"onMessage"}),et.get(s).set("onMessage",e)},send:e=>{t.socketEmitter({id:s,method:"send",data:e.data}).then((t=>{nt(e,t)})).catch((t=>{st(e,t)}))},close:e=>{t.socketEmitter({id:s,method:"close",code:e.code,reason:e.reason}).then((t=>{nt(e,t),et.delete(s)})).catch((t=>{st(e,t)}))},onOpen:e=>{t.socketEmitter({id:s,method:"onOpen"}),et.get(s).set("onOpen",e)},onClose:e=>{t.socketEmitter({id:s,method:"onClose"}),et.get(s).set("onClose",e)},onError:e=>{t.socketEmitter({id:s,method:"onError"}),et.get(s).set("onError",e)}};return et.get(s).set("socketTask",i),i})).catch((t=>(st(e[0],t),null)))}:(s=n,tt.includes(s)?e=>{Z.has(n)||Z.set(n,new Map);const s=Z.get(n),i=`${Date.now()}-${Math.random()}`;s.set(i,e),t.callUniMethod(n,i)}:function(t){return t.startsWith("off")&&tt.includes(t.replace("off","on"))}(n)?async e=>{const s=n.replace("off","on");if(Z.has(s))if(e){const i=Z.get(s);i.forEach(((s,o)=>{s===e&&(i.delete(o),t.callUniMethod(n,o))}))}else Z.delete(s),t.callUniMethod(n)}:async(...e)=>await t.callUniMethod(n,...e).then((t=>(nt(e[0],t),t))).catch((t=>(st(e[0],t),t))));var s}}); +***************************************************************************** */function ct(t,e,n,s){var i,o=arguments.length,r=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}var pt;function lt(t,e){const n=e.value;return e.value=async function(e){return(await(null==n?void 0:n.call(this,e)))(t)},e}function ut(t,e,n){return lt(pt.RUNTIME,n)}function ht(t,e,n){return lt(pt.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(pt||(pt={}));class dt{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===pt.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(t,e):this.puppet.runtimeConnection.send(t,e)}on(t,e){this.puppet.on(t,e)}}class mt extends dt{constructor(t,e){super(t),this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId,this.videoId=e.videoId}async getData(t){return this.invokeMethod("Element.getData",t)}async setData(t){return this.invokeMethod("Element.setData",t)}async callMethod(t){return this.invokeMethod("Element.callMethod",t)}async getElement(t){return this.invokeMethod("Element.getElement",t)}async getElements(t){return this.invokeMethod("Element.getElements",t)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(t){return this.invokeMethod("Element.getHTML",t)}async getAttributes(t){return this.invokeMethod("Element.getAttributes",t)}async getStyles(t){return this.invokeMethod("Element.getStyles",t)}async getDOMProperties(t){return this.invokeMethod("Element.getDOMProperties",t)}async getProperties(t){return this.invokeMethod("Element.getProperties",t)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(t){return this.invokeMethod("Element.touchstart",t)}async touchmove(t){return this.invokeMethod("Element.touchmove",t)}async touchend(t){return this.invokeMethod("Element.touchend",t)}async triggerEvent(t){return this.invokeMethod("Element.triggerEvent",t)}async callFunction(t){return this.invokeMethod("Element.callFunction",t)}async callContextMethod(t){return this.invokeMethod("Element.callContextMethod",t)}invokeMethod(t,e={}){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.invoke(t,e)}}ct([ut],mt.prototype,"getData",null),ct([ut],mt.prototype,"setData",null),ct([ut],mt.prototype,"callMethod",null),ct([ht],mt.prototype,"getElement",null),ct([ht],mt.prototype,"getElements",null),ct([ht],mt.prototype,"getOffset",null),ct([ht],mt.prototype,"getHTML",null),ct([ht],mt.prototype,"getAttributes",null),ct([ht],mt.prototype,"getStyles",null),ct([ht],mt.prototype,"getDOMProperties",null),ct([ht],mt.prototype,"getProperties",null),ct([ht],mt.prototype,"tap",null),ct([ht],mt.prototype,"longpress",null),ct([ht],mt.prototype,"touchstart",null),ct([ht],mt.prototype,"touchmove",null),ct([ht],mt.prototype,"touchend",null),ct([ht],mt.prototype,"triggerEvent",null),ct([ht],mt.prototype,"callFunction",null),ct([ht],mt.prototype,"callContextMethod",null);const gt=Object.prototype.hasOwnProperty,vt=Array.isArray,yt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function ft(t,e){if(vt(t))return t;if(e&&(n=e,s=t,gt.call(n,s)))return[t];var n,s;const i=[];return t.replace(yt,(function(t,e,n,s){return i.push(n?s.replace(/\\(\\)?/g,"$1"):e||t),s})),i}function wt(t,e){const n=ft(e,t);let s;for(s=n.shift();null!=s;){if(null==(t=t[s]))return;s=n.shift()}return t}const Pt=require("util"),Mt=["scrollLeft","scrollTop","scrollWidth","scrollHeight"];class It{constructor(t,e,n){this.puppet=t,this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId||null,this.videoId=e.videoId||null,this.tagName=e.tagName,this.nvue=e.nvue,this.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new mt(t,e)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[Pt.inspect.custom](){return this.toJSON()}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((t=>It.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap)))}async size(){const[t,e]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:t,height:e}}async offset(){const{left:t,top:e}=await this.api.getOffset();return{left:t,top:e}}async text(){return this.domProperty("innerText")}async attribute(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.puppet.isX?this.domProperty("value"):this.property("value")}async property(t){if(!F.default(t))throw Error("name must be a string");if(this.puppet.checkProperty){let e=this.publicProps;if(e||(this.publicProps=e=await this._property("__propPublic")),!e[t])throw Error(`${this.tagName}.${t} not exists`)}return this.puppet.isX&&"h5"===process.env.UNI_PLATFORM&&Mt.includes(t)?await this.domProperty(t):this._property(t)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(t){if(!F.default(t))throw Error("name must be a string");return(await this.api.getStyles({names:[t]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue||"true"===process.env.UNI_APP_X?this.api.longpress():(await this.touchstart(),await z.default(350),this.touchend())}async trigger(t,e){const n={type:t};return Y.default(e)||(n.detail=e),this.api.triggerEvent(n)}async touchstart(t){return this.api.touchstart(t)}async touchmove(t){return this.api.touchmove(t)}async touchend(t){return this.api.touchend(t)}async domProperty(t){return it((async t=>(await this.api.getDOMProperties({names:t})).properties),t)}_property(t){return it((async t=>(await this.api.getProperties({names:t})).properties),t)}send(t,e){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.puppet.send(t,e)}async callFunction(t,...e){return(await this.api.callFunction({functionName:t,args:e})).result}static create(t,e,n){let s,i=n.get(e.elementId);if(i)return i;if(e.nodeId)s=kt;else switch(e.tagName.toLowerCase()){case"input":s=At;break;case"textarea":s=Et;break;case"scroll-view":s=_t;break;case"swiper":s=Tt;break;case"movable-view":s=Ut;break;case"switch":s=bt;break;case"slider":s=Ct;break;case"video":s=Nt;break;default:s=It}return i=new s(t,e,n),n.set(e.elementId,i),i}}class kt extends It{async setData(t){return this.api.setData({data:t})}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class At extends It{async input(t){return this.callFunction("input.input",t)}}class Et extends It{async input(t){return this.callFunction("textarea.input",t)}}class _t extends It{async scrollTo(t,e){return this.callFunction("scroll-view.scrollTo",t,e)}async property(t){return"scrollTop"===t?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===t?this.callFunction("scroll-view.scrollLeft"):super.property(t)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class Tt extends It{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class Ut extends It{async moveTo(t,e){return this.callFunction("movable-view.moveTo",t,e)}async property(t){return"x"===t?this._property("_translateX"):"y"===t?this._property("_translateY"):super.property(t)}}class bt extends It{async tap(){return this.callFunction("switch.tap")}}class Ct extends It{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class Nt extends It{async callContextMethod(t,...e){return await this.api.callContextMethod({method:t,args:e})}}class Ot extends dt{constructor(t,e){super(t),this.id=e.id}async getData(t){return this.invokeMethod("Page.getData",t)}async setData(t){return this.invokeMethod("Page.setData",t)}async callMethod(t){return this.invokeMethod("Page.callMethod",t)}async callMethodWithCallback(t){return this.invokeMethod("Page.callMethodWithCallback",t)}async getElement(t){return this.invokeMethod("Page.getElement",t)}async getElements(t){return this.invokeMethod("Page.getElements",t)}async getWindowProperties(t){return this.invokeMethod("Page.getWindowProperties",t)}invokeMethod(t,e={}){return e.pageId=this.id,this.invoke(t,e)}}ct([ut],Ot.prototype,"getData",null),ct([ut],Ot.prototype,"setData",null),ct([ut],Ot.prototype,"callMethod",null),ct([ut],Ot.prototype,"callMethodWithCallback",null),ct([ht],Ot.prototype,"getElement",null),ct([ht],Ot.prototype,"getElements",null),ct([ht],Ot.prototype,"getWindowProperties",null);const Rt=require("util");class St{constructor(t,e){this.puppet=t,this.id=e.id,this.path=e.path,this.query=e.query,this.elementMap=new Map,this.api=new Ot(t,e)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[Rt.inspect.custom](){return this.toJSON()}async waitFor(t){return G.default(t)?await z.default(t):B.default(t)?j.default(t,0,50):F.default(t)?j.default((async()=>{if("true"===process.env.UNI_APP_X){return!!await this.$(t)}return(await this.$$(t)).length>0}),0,50):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map((e=>It.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)))}async data(t){const e={};if(t&&(e.path=t),"true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM&&"true"!==process.env.UNI_AUTOMATOR_APP_WEBVIEW){const n=(await this.api.getData(e)).data;return t?wt(n,t):n}return(await this.api.getData(e)).data}async setData(t){return this.api.setData({data:t})}async size(){const[t,e]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:t,height:e}}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}async callMethodWithCallback(t,...e){return await this.api.callMethodWithCallback({method:t,args:e})}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=F.default(t);e&&(t=[t]);const{properties:n}=await this.api.getWindowProperties({names:t});return e?n[0]:n}static create(t,e,n){let s=n.get(e.id);return s?(s.path=e.path,s.query=e.query,s):(s=new St(t,e),n.set(e.id,s),s)}}class Dt extends dt{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(t){return this.invoke("App.callUniMethod",t)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(t){return this.invoke("App.mockUniMethod",t)}async captureScreenshotByRuntime(t){return this.invoke("App.captureScreenshot",t)}async captureScreenshotWithDeviceByRuntime(t){return this.invoke("App.captureScreenshotWithDevice",t)}async socketEmitter(t){return this.invoke("App.socketEmitter",t)}async callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",t)}async adbCommand(t){return this.invoke("App.adbCommand",t)}async swipe(t){return this.invoke("App.swipe",t)}async exit(){return this.invoke("App.exit")}async addBinding(t){return this.invoke("App.addBinding",t)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(t){return this.on("App.logAdded",t)}onBindingCalled(t){return this.on("App.bindingCalled",t)}onExceptionThrown(t){return this.on("App.exceptionThrown",t)}}ct([ut],Dt.prototype,"getPageStack",null),ct([ut],Dt.prototype,"callUniMethod",null),ct([ut],Dt.prototype,"getCurrentPage",null),ct([ut],Dt.prototype,"mockUniMethod",null),ct([ut],Dt.prototype,"captureScreenshotByRuntime",null),ct([ut],Dt.prototype,"captureScreenshotWithDeviceByRuntime",null),ct([ut],Dt.prototype,"socketEmitter",null),ct([ht],Dt.prototype,"callFunction",null),ct([ht],Dt.prototype,"captureScreenshot",null),ct([ht],Dt.prototype,"adbCommand",null),ct([ht],Dt.prototype,"swipe",null),ct([ht],Dt.prototype,"exit",null),ct([ht],Dt.prototype,"addBinding",null),ct([ht],Dt.prototype,"enableLog",null);class xt extends dt{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(t){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(t){this.puppet.once("Tool.onRemoteDebugConnected",t),this.puppet.once("Tool.onPreviewConnected",t)}}function jt(t){return new Promise((e=>setTimeout(e,t)))}ct([ht],xt.prototype,"getInfo",null),ct([ht],xt.prototype,"enableRemoteDebug",null),ct([ht],xt.prototype,"close",null),ct([ht],xt.prototype,"getTestAccounts",null);class $t extends a.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new Dt(t),this.toolApi=new xt(t),this.appApi.onLogAdded((t=>{this.emit("console",t)})),this.appApi.onBindingCalled((({name:t,args:e})=>{try{const n=this.appBindings.get(t);n&&n(...e)}catch(t){}})),this.appApi.onExceptionThrown((t=>{this.emit("exception",t)}))}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map((t=>St.create(this.puppet,t,this.pageMap)))}async navigateTo(t){return this.changeRoute("navigateTo",t)}async redirectTo(t){return this.changeRoute("redirectTo",t)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(t){return this.changeRoute("reLaunch",t)}async switchTab(t){return this.changeRoute("switchTab",t)}async currentPage(){const{id:t,path:e,query:n}=await this.appApi.getCurrentPage();return St.create(this.puppet,{id:t,path:e,query:n},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(t,...e){return(await this.appApi.callUniMethod({method:t,args:e})).result}async mockUniMethod(t,e,...n){return B.default(e)||(s=e,F.default(s)&&(s=V.default(s),J.default(s,"function")||J.default(s,"() =>")))?this.appApi.mockUniMethod({method:t,functionDeclaration:e.toString(),args:n}):this.appApi.mockUniMethod({method:t,result:e});var s}async restoreUniMethod(t){return this.appApi.mockUniMethod({method:t})}async evaluate(t,...e){return(await this.appApi.callFunction({functionDeclaration:t.toString(),args:e})).result}async pageScrollTo(t){await this.callUniMethod("pageScrollTo",{scrollTop:t,duration:0})}async close(){try{await this.appApi.exit()}catch(t){}await jt(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){return this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(t){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:e}=await this.toolApi.enableRemoteDebug({auto:t});var n;e&&await(n=e,new Promise((t=>{W.default.generate(n,{small:!0},(e=>{process.stdout.write(e),t(void 0)}))})));const s=new Promise((t=>{this.toolApi.onRemoteDebugConnected((async()=>{await jt(1e3),t(void 0)}))})),i=new Promise((t=>{this.puppet.setRemoteRuntimeConnectionCallback((()=>{t(void 0)}))}));return Promise.all([s,i])}disconnect(){this.puppet.dispose()}on(t,e){return"console"===t&&this.appApi.enableLog(),super.on(t,e),this}async exposeFunction(t,e){if(this.appBindings.has(t))throw Error(`Failed to expose function with name ${t}: already exists!`);this.appBindings.set(t,e),await this.appApi.addBinding({name:t})}async checkVersion(){}async screenshot(t){const e=this.puppet.isX&&"app-plus"===this.puppet.platform?(null==t?void 0:t.deviceShot)?"captureScreenshotWithDeviceByRuntime":"captureScreenshotByRuntime":"captureScreenshot",{data:n}=await this.appApi[e]({id:null==t?void 0:t.id,fullPage:null==t?void 0:t.fullPage,area:null==t?void 0:t.area,offsetX:null==t?void 0:t.offsetX,offsetY:null==t?void 0:t.offsetY});if(!(null==t?void 0:t.path))return n;await X.default.writeFile(t.path,n,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){if(this.puppet.isVue3&&"h5"===process.env.UNI_PLATFORM&&"navigateBack"!==t){const{__id__:n}=await this.callUniMethod(t,{url:e,isAutomatedTesting:!0}),s=Date.now();return await j.default((async()=>{if(Date.now()-s>1e4)throw Error(`${t} to ${e} failed, unable to get the correct current page`);let i;try{i=await this.currentPage()}catch(t){return!1}return i.id===n&&i}),0,1e3)}return await this.callUniMethod(t,{url:e}),await jt(1e3),await this.currentPage()}async socketEmitter(t){return this.appApi.socketEmitter(t)}async adbCommand(t){return"android"===process.env.UNI_APP_PLATFORM?await this.appApi.adbCommand(t):Error("Program.adbCommand is only supported on the app android platform")}async swipe(t){return await this.appApi.swipe(t)}}class qt{constructor(t){this.options=t}has(t){return!!this.options[t]}send(t,e,n){const s=this.options[e];if(!s)return Promise.reject(Error(`adapter for ${e} not found`));const i=s.reflect;return i?(s.params&&(n=s.params(n)),"function"==typeof i?i(t.send.bind(t),n):(e=i,t.send(e,n))):Promise.reject(Error(`${e}'s reflect is required`))}}const Lt=N.default("automator:puppet"),Ft=".automator.json";function Ht(t){try{return require(t)}catch(t){}}function Wt(t,e,n,s){const i=function(t,e,n){let s,i;return process.env.UNI_OUTPUT_DIR?(i=C.default.join(process.env.UNI_OUTPUT_DIR,`../.automator/${e}`,Ft),s=Ht(i)):(i=C.default.join(t,`dist/${n}/.automator/${e}`,Ft),s=Ht(i),s||(i=C.default.join(t,`unpackage/dist/${n}/.automator/${e}`,Ft),s=Ht(i))),Lt(`${i}=>${JSON.stringify(s)}`),s}(t,n,s);if(!i||!i.wsEndpoint)return!1;const o=require("../package.json").version;if(i.version!==o)return Lt(`unmet=>${i.version}!==${o}`),!1;const r=function(t){let e;try{const t=L.default.v4.sync();e=q.default.ip(t&&t.interface),e&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(e)||(e=void 0))}catch(t){}return"ws://"+(e||"localhost")+":"+t}(e);return Lt(`wsEndpoint=>${r}`),i.wsEndpoint===r}class Xt extends a.EventEmitter{constructor(t,e){if(super(),this.isX=!1,this.isVue3=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),e)this.target=e;else{if(this.target=null,"h5"===t)try{this.target=ot("@dcloudio/uni-h5/lib/h5/uni.automator.js")}catch(t){}this.target||(this.target=ot(`@dcloudio/uni-${"app"===t?"app-plus":t}/lib/uni.automator.js`))}if(!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new qt(this.target.adapter||{})}setCompiler(t){this.compiler=t}setRuntimeServer(t){this.wss=t}setRemoteRuntimeConnectionCallback(t){this.remoteRuntimeConnectionCallback=t}setRuntimeConnection(t){this.runtimeConnection=t,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(t){this.devtoolConnection=t}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const e=this.target.devtools.required;return!e||!e.find((e=>!b.default.existsSync(C.default.join(t,e))))}validateDevtools(t){const e=this.target.devtools.validate;return e?e(t,this):Promise.resolve(t)}createDevtools(t,e,n){const s=this.target.devtools.create;return s?(e.timeout=n,s(t,e,this)):Promise.resolve()}shouldCompile(t,e,n,s){this.compiled=!0;const i=this.target.shouldCompile;if(i)this.compiled=i(n,s);else if(!0===n.compile)this.compiled=!0;else{if("false"===process.env.UNI_AUTOMATOR_COMPILE)return!1;this.compiled=!Wt(t,e,this.platform,this.mode)}return this.compiled}beforeCompile(){this.target.beforeCompile&&this.target.beforeCompile(C.default.resolve(__dirname,".."))}afterCompile(){this.target.afterCompile&&this.target.afterCompile()}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const t=this.target.mode;return t||("production"===process.env.NODE_ENV?"build":"dev")}}const Bt=N.default("automator:compiler"),Vt=/The\s+(.*)\s+directory is ready/;class Jt{constructor(t){this.puppet=t,this.puppet.setCompiler(this)}compile(t){const e=this.puppet.mode,n=this.puppet.platform;let s=t.silent;const i=t.port,o=t.host,r=`${e}:${n}`,a=t.projectPath,[c,p]=this.getSpawnArgs(t,r);p.push("--auto-port"),p.push(K.default(i)),o&&(p.push("--auto-host"),p.push(o));const l={cwd:t.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===e?"production":"development"})};return new Promise(((t,i)=>{const o=o=>{const r=o.toString().trim();if(!s&&console.log(r),r.includes("- Network")||r.includes("> Network")||r.includes("➜ Network")){const e=r.match(/Network:(.*)/)[1].trim();Bt(`url: ${e}`),t({path:e})}else if(r.includes("DONE Build failed"))i(r);else if(r.includes("DONE Build complete")){const i=r.match(Vt);let o="";if(i&&i.length>1)o=C.default.join(a,i[1]);else{const t=this.puppet.isX&&"app-plus"===n?"app":n;o=C.default.join(a,`dist/${e}/${t}`),T.existsSync(o)||(o=process.env.UNI_OUTPUT_DIR)}this.puppet.afterCompile(),s=!0,this.stop(),t({path:"true"===process.env.UNI_AUTOMATOR_APP_WEBVIEW?process.env.UNI_OUTPUT_DIR:o})}};Bt(`${c} ${p.join(" ")} %o`,l),this.cliProcess=E.spawn(c,p,l),this.cliProcess.on("error",(t=>{i(t)})),this.cliProcess.stdout.on("data",o),this.cliProcess.stderr.on("data",o)}))}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(t,e){let n;const s=t.cliPath;try{n=require(C.default.join(s,"package.json"))}catch(t){}let i=this.puppet.isX;if(n&&(n.devDependencies&&n.devDependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),!i&&n.dependencies&&n.dependencies["@dcloudio/vite-plugin-uni"]&&(i=!0),n.scripts&&n.scripts[e]))return[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",e,"--"]];this.puppet.isVue3=i,["android","ios"].includes(process.env.UNI_OS_NAME)&&(process.env.UNI_APP_PLATFORM=process.env.UNI_OS_NAME);let o=this.puppet.platform;if("app-plus"===this.puppet.platform&&this.puppet.isX&&(o="android"===process.env.UNI_APP_PLATFORM?"app-android":"ios"===process.env.UNI_APP_PLATFORM?"app-ios":"app"),process.env.UNI_INPUT_DIR=t.projectPath,process.env.UNI_OUTPUT_DIR=C.default.join(t.projectPath,`unpackage/dist/${this.puppet.mode}/${o}`),process.env.UNI_HBUILDERX_PLUGINS||T.existsSync(C.default.resolve(s,"../about"))&&(process.env.UNI_HBUILDERX_PLUGINS=C.default.dirname(s)),this.puppet.beforeCompile(),i){const t="app-plus"===this.puppet.platform?"app":this.puppet.platform;return process.env.UNI_PLATFORM=t,[process.env.UNI_NODE_PATH||"node",[require.resolve("@dcloudio/vite-plugin-uni/bin/uni.js",{paths:[s]}),"-p",t]]}return[process.env.UNI_NODE_PATH||"node",[C.default.join(s,"bin/uniapp-cli.js")]]}}const Gt=N.default("automator:launcher"),zt="true"===process.env.UNI_APP_X&&"android"===process.env.UNI_APP_PLATFORM?12e4:24e4;class Yt{async launch(t){const{port:e,cliPath:n,timeout:i,projectPath:o}=await this.validate(t);let r={};"app"===t.platform||"app-plus"===t.platform?(r=t.app||t["app-plus"],"true"===process.env.UNI_APP_X&&r["uni-app-x"]&&(r=s.recursive(!0,r,r["uni-app-x"])),delete r["uni-app-x"]):r=t[t.platform],r||(r={}),r.projectPath=o,Gt(r),this.puppet=new Xt(t.platform,r.puppet),r=await this.puppet.validateDevtools(r);let a=this.puppet.shouldCompile(o,e,t,r),c=process.env.UNI_OUTPUT_DIR||o;if(a||this.puppet.validateProject(c)||(c=C.default.join(o,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(c=C.default.join(o,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(c)||(a=!0))),a){this.puppet.compiled=t.compile=!0,this.compiler=new Jt(this.puppet);const s=await this.compiler.compile({host:t.host,port:e,cliPath:n,projectPath:o,silent:!!t.silent});s.path&&(c=s.path)}const p=[];return p.push(this.createRuntimeConnection(e,i)),p.push(this.puppet.createDevtools(c,r,i)),new Promise(((t,n)=>{Promise.all(p).then((([n,s])=>{n&&this.puppet.setRuntimeConnection(n),s&&this.puppet.setDevtoolConnection(s),N.default("automator:program")("ready");const i=r.teardown||"disconnect";t(new $t(this.puppet,{teardown:i,port:e}))})).catch((t=>n(t)))}))}resolveCliPath(t){if(!t)return t;try{const{dependencies:e,devDependencies:n}=require(C.default.join(t,"package.json"));if(Kt(n)||Kt(e))return t}catch(t){}}resolveProjectPath(t,e){return t||(t=process.env.UNI_INPUT_DIR||process.cwd()),O.default(t)&&(t=C.default.resolve(t)),b.default.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=process.env.UNI_CLI_PATH||t.cliPath;if(n=this.resolveCliPath(n||""),!n&&(n=this.resolveCliPath(process.cwd())),!n&&(n=this.resolveCliPath(e)),!n)throw Error("cliPath is not provided");if("false"!==process.env.UNI_APP_X){const t=this.getManifestJson(e);("true"===process.env.UNI_APP_X||"uni-app-x"in t)&&(process.env.UNI_APP_X="true",t.appid&&(process.env.UNI_APP_ID=t.appid))}process.env.UNI_AUTOMATOR_HOST&&(t.host=process.env.UNI_AUTOMATOR_HOST),process.env.UNI_AUTOMATOR_PORT&&(t.port=parseInt(process.env.UNI_AUTOMATOR_PORT));return{port:await async function(t,e){const n=await H.default(t||e);if(t&&n!==t)throw Error(`Port ${t} is in use, please specify another port`);return n}(t.port||9520),cliPath:n,timeout:t.timeout||zt,projectPath:e}}getManifestJson(t){if(t){const e=C.default.join(t,"manifest.json");if(b.default.existsSync(e))return i.parse(b.default.readFileSync(e,"utf8"))}return{}}async createRuntimeConnection(t,e){return at.createRuntimeConnection(t,this.puppet,e)}}function Kt(t){return!!t&&!(!t["@dcloudio/vue-cli-plugin-uni"]&&!t["@dcloudio/vite-plugin-uni"])}exports.Automator=class{constructor(){this.launcher=new Yt}async launch(t){return this.launcher.launch(t)}},exports.initUni=t=>new Proxy({},{get(e,n){return"connectSocket"===n?async(...e)=>{const s=`${Date.now()}-${Math.random()}`;return e[0].id=s,await t.callUniMethod(n,...e).then((n=>{nt(e[0],n),et.set(s,new Map);const i={id:s,onMessage:e=>{t.socketEmitter({id:s,method:"onMessage"}),et.get(s).set("onMessage",e)},send:e=>{t.socketEmitter({id:s,method:"send",data:e.data}).then((t=>{nt(e,t)})).catch((t=>{st(e,t)}))},close:e=>{t.socketEmitter({id:s,method:"close",code:e.code,reason:e.reason}).then((t=>{nt(e,t),et.delete(s)})).catch((t=>{st(e,t)}))},onOpen:e=>{t.socketEmitter({id:s,method:"onOpen"}),et.get(s).set("onOpen",e)},onClose:e=>{t.socketEmitter({id:s,method:"onClose"}),et.get(s).set("onClose",e)},onError:e=>{t.socketEmitter({id:s,method:"onError"}),et.get(s).set("onError",e)}};return et.get(s).set("socketTask",i),i})).catch((t=>(st(e[0],t),null)))}:(s=n,tt.includes(s)?e=>{Z.has(n)||Z.set(n,new Map);const s=Z.get(n),i=`${Date.now()}-${Math.random()}`;s.set(i,e),t.callUniMethod(n,i)}:function(t){return t.startsWith("off")&&tt.includes(t.replace("off","on"))}(n)?async e=>{const s=n.replace("off","on");if(Z.has(s))if(e){const i=Z.get(s);i.forEach(((s,o)=>{s===e&&(i.delete(o),t.callUniMethod(n,o))}))}else Z.delete(s),t.callUniMethod(n)}:async(...e)=>await t.callUniMethod(n,...e).then((t=>(nt(e[0],t),t))).catch((t=>(st(e[0],t),t))));var s}}); diff --git a/packages/uni-h5/lib/uni.automator.js b/packages/uni-h5/lib/uni.automator.js index 62002e5e7f9..6f552e4d389 100644 --- a/packages/uni-h5/lib/uni.automator.js +++ b/packages/uni-h5/lib/uni.automator.js @@ -1 +1 @@ -"use strict";var e=require("debug"),t=require("postcss-selector-parser"),o=require("fs");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(e),a=r(t),s=r(o);const i=n.default("automator:devtool");function c(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"uni-page-body":"uni-"+t}}))}const l=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];function u(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}/^win/.test(process.platform);const p=["chromium","firefox","webkit"];let f=!1;try{f=!!u("playwright")}catch(e){}const h=new Map;function d(e="chromium"){const t=e&&p.includes(e)?e:p[0];let o=h.get(t);return o||(o=function(e){if("webkit"===e)return w("webkit");if("firefox"===e)return w("firefox");if(f)return w("chromium");throw new Error("Playwright dependency not found, please install playwright!")}(t),h.set(t,o)),o}function w(e){const t=u("playwright");let o,r;return{type:e,provider:"playwright",async open(n,a,s){o=await t[e].launch(a.options),"firefox"===e&&(a.contextOptions.isMobile=!1),i(`browser.newContext ${JSON.stringify(a.contextOptions)}`);const c=await o.newContext(a.contextOptions);r=await c.newPage(),r.on("console",(e=>{s.emit("App.logAdded",{type:e.type(),args:[e.text()]})})),r.on("pageerror",(e=>{s.emit("App.exceptionThrown",e)})),await r.goto(a.url||n),await r.waitForTimeout(1e3)},close:()=>o.close(),screenshot:(e=!1)=>r.screenshot({fullPage:e}).then((e=>e.toString("base64")))}}let g;const m={"Tool.close":{reflect:async()=>{await g.close()}},"App.exit":{reflect:async()=>{}},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(e,t)=>{const o=await g.screenshot(!!t.fullPage);return i(`App.captureScreenshot ${o.length}`),{data:o}}}};!function(e){l.forEach((t=>{e[t]=function(e){return{reflect:async(t,o)=>t(e,o,!1),params:e=>(e.selector&&(e.selector=a.default(c).processSync(e.selector)),e)}}(t)}))}(m);const y={devtools:{name:"browser",paths:[],validate:async function(e){return e.options=e.options||{},e.executablePath&&!e.options.executablePath&&(e.options.executablePath=e.executablePath),e.contextOptions={viewport:Object.assign({width:375,height:667},e.options.defaultViewport||{}),hasTouch:!0,isMobile:!0,deviceScaleFactor:2},e.options.defaultViewport=Object.assign({width:375,height:667,deviceScaleFactor:2,hasTouch:!0,isMobile:!0},e.options.defaultViewport||{}),e.teardown||(e.teardown=!1===e.options.headless?"disconnect":"close"),e},create:async function(e,t,o){t.executablePath?await new Promise(((o,r)=>{const{exec:n}=require("node:child_process");if(/^win/.test(process.platform)){const r="C:\\Users\\Public\\AppData\\Local\\chrome";s.default.existsSync(r)||s.default.mkdirSync(r,{recursive:!0}),n(`start ${t.executablePath} --user-data-dir=${r} ${e}`,(e=>{if(e)throw console.error(`open ${t.executablePath} fail, ${e}`),Error(e)})),setTimeout((()=>{o(null)}),1e3)}else n(`open -a "${t.executablePath}" ${e}`,(e=>{e&&(console.error(`open ${t.executablePath} fail, ${e}`),r(e)),o(null)}))})):(g=d(process.env.BROWSER),i("createDevtools "+(g.provider+" "+g.type+" "+JSON.stringify(t))),await g.open(e,t,o))}},shouldCompile:(e,t)=>!t.url,adapter:m};module.exports=y; +"use strict";var e=require("debug"),t=require("postcss-selector-parser"),o=require("fs");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(e),a=r(t),s=r(o);const i=n.default("automator:devtool");function c(e){e.walk((e=>{if("tag"===e.type){const t=e.value;e.value="page"===t?"uni-page-body":"uni-"+t}}))}const l=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];function p(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}/^win/.test(process.platform);const u=["chromium","firefox","webkit"];let f=!1;try{f=!!p("playwright")}catch(e){}const w=new Map;function h(e="chromium"){const t=e&&u.includes(e)?e:u[0];let o=w.get(t);return o||(o=function(e){if("webkit"===e)return d("webkit");if("firefox"===e)return d("firefox");if(f)return d("chromium");throw new Error("Playwright dependency not found, please install playwright!")}(t),w.set(t,o)),o}function d(e){const t=p("playwright");let o,r;return{type:e,provider:"playwright",async open(n,a,s){o=await t[e].launch(a.options),"firefox"===e&&(a.contextOptions.isMobile=!1),i(`browser.newContext ${JSON.stringify(a.contextOptions)}`);const c=await o.newContext(a.contextOptions);r=await c.newPage(),r.on("console",(e=>{s.emit("App.logAdded",{type:e.type(),args:[e.text()]})})),r.on("pageerror",(e=>{s.emit("App.exceptionThrown",e)})),await r.goto(a.url||n),await r.waitForTimeout(1e3)},close:()=>o.close(),screenshot:(e=!1)=>r.screenshot({fullPage:e}).then((e=>e.toString("base64"))),swipe:e=>new Promise((async t=>{const{startPoint:o,endPoint:n}=e;await r.evaluate((([e,t])=>{window.scrollBy({left:e.x-t.x,top:e.y-t.y,behavior:"smooth"})}),[o,n]),t("swipe success")}))}}let g;const y={"Tool.close":{reflect:async()=>{await g.close()}},"App.exit":{reflect:async()=>{}},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(e,t)=>{const o=await g.screenshot(!!t.fullPage);return i(`App.captureScreenshot ${o.length}`),{data:o}}},"App.swipe":{reflect:async(e,t)=>{const o=await g.swipe(t);return i(`App.swipe ${o.length}`),{data:o}}}};!function(e){l.forEach((t=>{e[t]=function(e){return{reflect:async(t,o)=>t(e,o,!1),params:e=>(e.selector&&(e.selector=a.default(c).processSync(e.selector)),e)}}(t)}))}(y);const m={devtools:{name:"browser",paths:[],validate:async function(e){return e.options=e.options||{},e.executablePath&&!e.options.executablePath&&(e.options.executablePath=e.executablePath),e.contextOptions={viewport:Object.assign({width:375,height:667},e.options.defaultViewport||{}),hasTouch:!0,isMobile:!0,deviceScaleFactor:2},e.options.defaultViewport=Object.assign({width:375,height:667,deviceScaleFactor:2,hasTouch:!0,isMobile:!0},e.options.defaultViewport||{}),e.teardown||(e.teardown=!1===e.options.headless?"disconnect":"close"),e},create:async function(e,t,o){t.executablePath?await new Promise(((o,r)=>{const{exec:n}=require("node:child_process");if(/^win/.test(process.platform)){const r="C:\\Users\\Public\\AppData\\Local\\chrome";s.default.existsSync(r)||s.default.mkdirSync(r,{recursive:!0}),n(`start ${t.executablePath} --user-data-dir=${r} ${e}`,(e=>{if(e)throw console.error(`open ${t.executablePath} fail, ${e}`),Error(e)})),setTimeout((()=>{o(null)}),1e3)}else n(`open -a "${t.executablePath}" ${e}`,(e=>{e&&(console.error(`open ${t.executablePath} fail, ${e}`),r(e)),o(null)}))})):(g=h(process.env.BROWSER),i("createDevtools "+(g.provider+" "+g.type+" "+JSON.stringify(t))),await g.open(e,t,o))}},shouldCompile:(e,t)=>!t.url,adapter:y};module.exports=m;