提交 6f8920f8 编写于 作者: fxy060608's avatar fxy060608

fix(app): automator with android 11+

上级 8d803205
"use strict";var t=require("fs"),e=require("debug"),s=require("licia/sleep"),i=require("postcss-selector-parser"),r=require("fs-extra"),a=require("licia/dateFormat"),n=require("path"),o=require("util");function l(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var c=l(t),u=l(e),d=l(s),h=l(i),p=l(r),m=l(a);function y(t){t.walk((t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}}))}u.default("automator:devtool");const f=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const v=/^win/.test(process.platform);function g(t){try{return require(t)}catch(e){return require(require.resolve(t,{paths:[process.cwd()]}))}}const w=u.default("automator:launcher"),$=o.promisify(c.default.readdir),M=o.promisify(c.default.stat);async function P(t){const e=await $(t);return(await Promise.all(e.map((async e=>{const s=n.resolve(t,e);return(await M(s)).isDirectory()?P(s):s})))).reduce(((t,e)=>t.concat(e)),[])}class E{constructor(t){this.isX=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),this.id=t.id,this.app=t.executablePath,this.appid=t.appid||process.env.UNI_APP_ID||"HBuilder",this.package=t.package||(this.isX?"io.dcloud.uniappx":"io.dcloud.HBuilder"),this.activity=t.activity||(this.isX?"io.dcloud.uniapp.UniAppActivity":"io.dcloud.PandoraEntry")}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then((()=>(w(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(w(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(t){return P(t).then((e=>{const s=e.map((e=>{const s=(t=>v?t.replace(/\\/g,"/"):t)(n.join(this.DIR_WWW,n.relative(t,e)));return w(`${m.default("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${s}`),this.pushFile(e,s)}));return Promise.all(s)})).then((t=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const A=u.default("automator:simctl");function _(t){const e=parseInt(t);return e>9?String(e):"0"+e}class S extends E{constructor(){super(...arguments),this.bundleVersion=""}async init(){const t=g("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),A(`${m.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=await this.tool.appInfo(this.package);A(`${m.default("yyyy-mm-dd HH:MM:ss:l")} appInfo ${t}`);const e=t.match(/DataContainer\s+=\s+"(.*)"/);if(!e)return Promise.resolve("");const s=t.match(/CFBundleVersion\s+=\s+(.*);/);if(!s)return Promise.resolve("");this.sdcard=e[1].replace("file:",""),this.bundleVersion=s[1],A(`${m.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.bundleVersion)}formatVersion(t){const e=t.split(".");return 3!==e.length?t:e[0]+_(e[1])+_(e[2])}async install(){return A(`${m.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(){try{await this.tool.terminateApp(this.package)}catch(t){}try{await this.tool.launchApp(this.package)}catch(t){console.error(t)}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(){return Promise.resolve(await this.tool.getScreenshot())}exists(t){return p.default.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(`${t} not exists`))}pushFile(t,e){return Promise.resolve(p.default.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const x=g("adbkit"),H=u.default("automator:adb");class D extends E{async init(){if(this.tool=x.createClient(),!this.id){const t=await this.tool.listDevices();if(!t.length)throw Error("Device not found");this.id=t[0].id}this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),H(`${m.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}version(){return this.shell(this.COMMAND_VERSION).then((t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""}))}formatVersion(t){return t}async install(){let t=!0;try{const e=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(e)<6&&(t=!1)}catch(t){}if(H(`${m.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${t}`),t){const t=g("adbkit/lib/adb/command.js"),e=t.prototype._send;t.prototype._send=function(t){return 0===t.indexOf("shell:pm install -r ")&&(t=t.replace("shell:pm install -r ","shell:pm install -r -g "),H(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ${t} `)),e.call(this,t)}}return this.tool.install(this.id,this.app).then((()=>this.init()))}start(){return this.exit().then((()=>this.shell(this.COMMAND_START)))}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(){return this.tool.screencap(this.id).then((t=>new Promise((e=>{const s=[];t.on("data",(function(t){s.push(t)})),t.on("end",(function(){e(Buffer.concat(s).toString("base64"))}))}))))}exists(t){return this.tool.stat(this.id,t)}pushFile(t,e){return this.tool.push(this.id,t,e)}shell(t){return H(`${m.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(x.util.readAll).then((t=>{const e=t.toString();return H(`${m.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e}))}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 ${this.appid} --ez needUpdateApp false --ez reload true`}}const I=u.default("automator:devtool");let b,C=!1;const N={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const R={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>b.exit()},"App.enableLog":{reflect:()=>Promise.resolve()}};!function(t){f.forEach((e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=h.default(y).processSync(t.selector)),t)}}(e)}))}(R);const O={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,e){t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),b=function(t,e){return"ios"===t?new S(e):new D(e)}(t.platform,t),await b.init();const s=await b.version();if(s){if(t.version){const e=b.formatVersion(function(t,e){if(t.endsWith(".txt"))try{const s=c.default.readFileSync(t).toString().match(N[e]);if(s)return s[1]}catch(t){console.error(t)}return t}(t.version,t.platform));I(`version: ${s}`),I(`newVersion: ${e}`),e!==s&&(C=!0)}}else C=!0;if(C){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!c.default.existsSync(t.executablePath))throw Error(`${t.executablePath} not exists`)}return t},create:async function(t,e,s){C&&await b.install(),(C||s.compiled||await b.shouldPush())&&(await b.push(t),await d.default(1e3)),await b.start()}},adapter:R};module.exports=O;
"use strict";var t=require("fs"),e=require("debug"),s=require("licia/sleep"),i=require("postcss-selector-parser"),r=require("fs-extra"),a=require("licia/dateFormat"),o=require("path"),n=require("util");function l(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var c=l(t),d=l(e),u=l(s),h=l(i),p=l(r),y=l(a);function m(t){t.walk((t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}}))}d.default("automator:devtool");const f=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];const $=/^win/.test(process.platform);function v(t){try{return require(t)}catch(e){return require(require.resolve(t,{paths:[process.cwd()]}))}}const M=d.default("automator:launcher"),w=n.promisify(c.default.readdir),g=n.promisify(c.default.stat);async function P(t){const e=await w(t);return(await Promise.all(e.map((async e=>{const s=o.resolve(t,e);return(await g(s)).isDirectory()?P(s):s})))).reduce(((t,e)=>t.concat(e)),[])}class E{constructor(t){this.isX=!1,"true"===process.env.UNI_APP_X&&(this.isX=!0),this.id=t.id,this.app=t.executablePath,this.appid=t.appid||process.env.UNI_APP_ID||"HBuilder",this.package=t.package||(this.isX?"io.dcloud.uniappx":"io.dcloud.HBuilder"),this.activity=t.activity||(this.isX?"io.dcloud.uniapp.UniAppActivity":"io.dcloud.PandoraEntry")}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then((()=>(M(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1))).catch((()=>(M(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0)))}push(t){return P(t).then((e=>{const s=e.map((e=>{const s=(t=>$?t.replace(/\\/g,"/"):t)(o.join(this.DIR_WWW,o.relative(t,e)));return M(`${y.default("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${s}`),this.pushFile(e,s)}));return Promise.all(s)})).then((t=>!0))}get FILE_APP_SERVICE(){return`${this.DIR_WWW}/app-service.js`}}const A=d.default("automator:simctl");function _(t){const e=parseInt(t);return e>9?String(e):"0"+e}class H extends E{constructor(){super(...arguments),this.bundleVersion=""}async init(){const t=v("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),A(`${y.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=await this.tool.appInfo(this.package);A(`${y.default("yyyy-mm-dd HH:MM:ss:l")} appInfo ${t}`);const e=t.match(/DataContainer\s+=\s+"(.*)"/);if(!e)return Promise.resolve("");const s=t.match(/CFBundleVersion\s+=\s+(.*);/);if(!s)return Promise.resolve("");this.sdcard=e[1].replace("file:",""),this.bundleVersion=s[1],A(`${y.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.bundleVersion)}formatVersion(t){const e=t.split(".");return 3!==e.length?t:e[0]+_(e[1])+_(e[2])}async install(){return A(`${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(){try{await this.tool.terminateApp(this.package)}catch(t){}try{await this.tool.launchApp(this.package)}catch(t){console.error(t)}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(){return Promise.resolve(await this.tool.getScreenshot())}exists(t){return p.default.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(`${t} not exists`))}pushFile(t,e){return Promise.resolve(p.default.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const S=v("adbkit"),x=d.default("automator:adb");class D extends E{async init(){if(this.tool=S.createClient(),!this.id){const t=await this.tool.listDevices();if(!t.length)throw Error("Device not found");this.id=t[0].id}await this.root(),this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}root(){return this.tool.root(this.id).then((()=>{x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${this.sdcard}`)})).catch((t=>{x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} root ${this.id} ${t}`)}))}version(){return this.shell(this.COMMAND_VERSION).then((t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""}))}formatVersion(t){return t}async install(){let t=!0;try{const e=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(e)<6&&(t=!1)}catch(t){}if(x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${t}`),t){const t=v("adbkit/lib/adb/command.js"),e=t.prototype._send;t.prototype._send=function(t){return 0===t.indexOf("shell:pm install -r ")&&(t=t.replace("shell:pm install -r ","shell:pm install -r -g "),x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ${t} `)),e.call(this,t)}}return this.tool.install(this.id,this.app).then((()=>this.init()))}start(){return this.exit().then((()=>this.shell(this.COMMAND_START)))}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(){return this.tool.screencap(this.id).then((t=>new Promise((e=>{const s=[];t.on("data",(function(t){s.push(t)})),t.on("end",(function(){e(Buffer.concat(s).toString("base64"))}))}))))}exists(t){return this.tool.stat(this.id,t)}pushFile(t,e){return this.tool.push(this.id,t,e)}shell(t){return x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(S.util.readAll).then((t=>{const e=t.toString();return x(`${y.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e}))}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 ${this.appid} --ez needUpdateApp false --ez reload true`}}const I=d.default("automator:devtool");let b,C=!1;const N={android:/android_version=(.*)/,ios:/iphone_version=(.*)/};const R={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>b.exit()},"App.enableLog":{reflect:()=>Promise.resolve()}};!function(t){f.forEach((e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=h.default(m).processSync(t.selector)),t)}}(e)}))}(R);const O={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,e){t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),b=function(t,e){return"ios"===t?new H(e):new D(e)}(t.platform,t),await b.init();const s=await b.version();if(s){if(t.version){const e=b.formatVersion(function(t,e){if(t.endsWith(".txt"))try{const s=c.default.readFileSync(t).toString().match(N[e]);if(s)return s[1]}catch(t){console.error(t)}return t}(t.version,t.platform));I(`version: ${s}`),I(`newVersion: ${e}`),e!==s&&(C=!0)}}else C=!0;if(C){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!c.default.existsSync(t.executablePath))throw Error(`${t.executablePath} not exists`)}return t},create:async function(t,e,s){C&&await b.install(),(C||s.compiled||await b.shouldPush())&&(await b.push(t),await u.default(1e3)),await b.start()}},adapter:R};module.exports=O;
此差异已折叠。
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/null;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}))}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn&&!fn)return data.error={message:method+" unimplemented"},send(data);try{fn(params).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}swan.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url:wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){swan.$$initRuntimeAutomator()}),500);
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}swan.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url:wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){swan.$$initRuntimeAutomator()}),500);
"use strict";var e=require("os"),t=require("path"),s=require("debug"),a=require("licia/isWindows"),r=require("fs"),n=require("child_process"),o=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/getPort"),p=require("licia/dateFormat"),m=require("ws"),d=require("events"),f=require("licia/uuid"),h=require("licia/stringify");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=g(e),y=g(t),E=g(s),b=g(a),v=g(r),P=g(n),j=g(o),O=g(i),$=g(c),M=g(l),q=g(u),C=g(p),A=g(m),S=g(f),T=g(h);const L=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;var N;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));const k={[N.SELECTOR]:[{test:H,processor:e=>e.replace(H,"nav")},{test:L,processor:e=>`swan-${e}`}],[N.TAGNAME]:[{test:R,processor:e=>e.replace(R,"swan-navigator")},{test:L,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},x=e=>t=>{const s=(k[e]||[]).filter((e=>e.test.test(t)));for(const e of s)t=e.processor(t);return t},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);class B extends d.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",(e=>{this.emit("message",e.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(e){this.ws.send(e)}close(){this.ws.close()}}const G="Connection closed";class W extends d.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=new Map,this.transport=e,this.debug=E.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:s,error:a,result:r,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(s,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),a?e.reject(Error(a.message)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(G))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},s=!0){if(s&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const a=S.default(),r=T.default({id:a,method:e,params:t});return this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((s,a)=>{const r=new A.default(e);r.addEventListener("open",(()=>{s(new W(new B(r),t,"devtool"))})),r.addEventListener("error",a)}))}static createRuntimeConnection(e,t,s){return new Promise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new A.default.Server({port:e});$.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new W(new B(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}const z=E.default("automator:devtool");async function J(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,p=!1;if(!1!==l){const t={stdio:"ignore"};o&&(t.cwd=o);let s=M.default(c,[]);s=M.default(s,["--auto"]),s=M.default(s,[e,"--auto-port",O.default(a)]),i&&(s=M.default(s,["--auto-account",i]));try{z("%s %o %o",r,s,t);const e=P.default.spawn(r,s,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{p=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{p=!0}),15e3);const m=await $.default((async()=>{try{if(u||p)return!0;const e=await async function(e,t){let s;try{s=await W.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return s}({wsEndpoint:`ws://127.0.0.1:${a}`},s);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throw Error(`Failed to launch ${s.devtools.name} , please make sure http port is open`);return await j.default(5e3),z(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}const U=[];["","-rc"].forEach((e=>{b.default?(U.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),U.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):U.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const V={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:U,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const s=function(e,t){const s=t.devtools.paths.slice(0);e&&s.unshift(e);for(const e of s)if(v.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let a=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=await async function(e,t){const s=await q.default(e||t);if(e&&s!==e)throw Error(`Port ${e} is in use, please specify another port`);return s}(a)}catch(t){e.launch=!1}else{a===await q.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:s})},async create(e,t,s){const a=await J(e,t,s);return s.compiled?E.default("automator:devtool")("Waiting for runtime automator"):(E.default("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split(" ").map((e=>D(e))).join(" "))}))).map((e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};var s}},"Page.getWindowProperties":{reflect:async(e,t)=>{const s=t.names.map((e=>e.replace("document.documentElement.",""))),a=(await e("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{const s=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return s.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=V;
"use strict";var e=require("os"),t=require("path"),s=require("debug"),a=require("licia/isWindows"),r=require("fs"),n=require("child_process"),o=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/getPort"),p=require("licia/dateFormat"),m=require("ws"),d=require("events"),f=require("licia/uuid"),h=require("licia/stringify");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=g(e),y=g(t),E=g(s),b=g(a),v=g(r),P=g(n),j=g(o),O=g(i),$=g(c),M=g(l),q=g(u),C=g(p),A=g(m),S=g(f),T=g(h);const L=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;var N;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));const k={[N.SELECTOR]:[{test:H,processor:e=>e.replace(H,"nav")},{test:L,processor:e=>`swan-${e}`}],[N.TAGNAME]:[{test:R,processor:e=>e.replace(R,"swan-navigator")},{test:L,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},x=e=>t=>{const s=(k[e]||[]).filter((e=>e.test.test(t)));for(const e of s)t=e.processor(t);return t},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);class B extends d.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",(e=>{this.emit("message",e.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(e){this.ws.send(e)}close(){this.ws.close()}}const G="Connection closed";class W extends d.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=new Map,this.transport=e,this.debug=E.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:s,error:a,result:r,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(s,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),a?e.reject(Error(a.message||a.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(G))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},s=!0){if(s&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const a=S.default(),r=T.default({id:a,method:e,params:t});return this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((s,a)=>{const r=new A.default(e);r.addEventListener("open",(()=>{s(new W(new B(r),t,"devtool"))})),r.addEventListener("error",a)}))}static createRuntimeConnection(e,t,s){return new Promise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new A.default.Server({port:e});$.default((async()=>{if(t.runtimeConnection)return!0}),s,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const s=new W(new B(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}const z=E.default("automator:devtool");async function J(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,p=!1;if(!1!==l){const t={stdio:"ignore"};o&&(t.cwd=o);let s=M.default(c,[]);s=M.default(s,["--auto"]),s=M.default(s,[e,"--auto-port",O.default(a)]),i&&(s=M.default(s,["--auto-account",i]));try{z("%s %o %o",r,s,t);const e=P.default.spawn(r,s,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{p=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{p=!0}),15e3);const m=await $.default((async()=>{try{if(u||p)return!0;const e=await async function(e,t){let s;try{s=await W.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return s}({wsEndpoint:`ws://127.0.0.1:${a}`},s);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throw Error(`Failed to launch ${s.devtools.name} , please make sure http port is open`);return await j.default(5e3),z(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}const U=[];["","-rc"].forEach((e=>{b.default?(U.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),U.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):U.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const V={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:U,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const s=function(e,t){const s=t.devtools.paths.slice(0);e&&s.unshift(e);for(const e of s)if(v.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let a=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=await async function(e,t){const s=await q.default(e||t);if(e&&s!==e)throw Error(`Port ${e} is in use, please specify another port`);return s}(a)}catch(t){e.launch=!1}else{a===await q.default(a)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:a,cliPath:s})},async create(e,t,s){const a=await J(e,t,s);return s.compiled?E.default("automator:devtool")("Waiting for runtime automator"):(E.default("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split(" ").map((e=>D(e))).join(" "))}))).map((e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};var s}},"Page.getWindowProperties":{reflect:async(e,t)=>{const s=t.names.map((e=>e.replace("document.documentElement.",""))),a=(await e("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{const s=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return s.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{const s=[];for(const a of t.names)s.push(await e("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=V;
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/null;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}))}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn&&!fn)return data.error={message:method+" unimplemented"},send(data);try{fn(params).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}wx.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url:wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500);
var CALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){return null==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getPageId(page){return page.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void 0}function getPagePath(page){return page.route||page.uri}function getPageQuery(page){return page.options||page.$page&&page.$page.options||{}}function parsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}function getPageVm(id){var page=function(id){return getCurrentPages().find((function(page){return getPageId(page)===id}))}(id);return page&&page.$vm}function findComponentVm(vm,nodeId){var res;return vm&&(!function(vm,nodeId){return vm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;var scope}(vm,nodeId)?vm.$children.find((function(child){return res=findComponentVm(child,nodeId)})):res=vm),res}function getComponentVm(pageId,nodeId){var pageVm=getPageVm(pageId);return pageVm&&findComponentVm(pageVm,nodeId)}function getData(vm,path){var data;return vm&&(data=path?function(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}function setData(vm,data){return vm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}function callMethod(vm,method,args){return new Promise((function(resolve,reject){if(!vm)return reject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])return reject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);var obj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeof obj&&"function"!=typeof obj||"function"!=typeof obj.then?resolve({result:ret}):ret.then((function(res){resolve({result:res})}))}))}!function(CALL_METHOD_ERROR){CALL_METHOD_ERROR.VM_NOT_EXISTS="VM_NOT_EXISTS",CALL_METHOD_ERROR.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(CALL_METHOD_ERROR||(CALL_METHOD_ERROR={}));var SYNC_APIS=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;function isSyncApi(method){return SYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}var App$1={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(page){return parsePage(page)}))})},getCurrentPage:function(){var pages=getCurrentPages(),len=pages.length;return new Promise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){var method=params.method,args=params.args;return new Promise((function(resolve,reject){if(!uni[method])return reject(Error("uni."+method+" not exists"));if(isSyncApi(method))return resolve({result:uni[method].apply(uni,args)});var params=[Object.assign({},args[0]||{},{success:function(result){setTimeout((function(){resolve({result:result})}),"pageScrollTo"===method?350:0)},fail:function(res){reject(Error(res.errMsg.replace(method+":fail ","")))}})];uni[method].apply(uni,params)}))},mockUniMethod:function(params){var method=params.method;if(!uni[method])throw Error("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throw Error("You can't mock uni."+method);var mockFn,result=params.result,functionDeclaration=params.functionDeclaration;return isUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],delete originUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){return result}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&&params.fail(result):params.success&&params.success(result),params.complete&&params.complete(result)}),4)}:function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];return new Function("return "+functionDeclaration)().apply(mockFn,args.concat(params.args))},mockFn.origin=originUni[method]||uni[method],originUni[method]||(originUni[method]=uni[method]),uni[method]=mockFn,Promise.resolve())},captureScreenshot:function(params){return new Promise((function(resolve,reject){var pages=getCurrentPages(),len=pages.length;if(len){var page=pages[len-1];if(page){var webview=page.$getAppWebview(),bitmap_1=new plus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){var data=bitmap_1.toBase64Data().replace("data:image/png;base64,","");bitmap_1.clear(),resolve({data:data})}),(function(err){reject(Error("captureScreenshot fail: "+err.message))}),{wholeContent:!!params.fullPage})}}else reject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){return getData(getPageVm(params.pageId),params.path)},setData:function(params){return setData(getPageVm(params.pageId),params.data)},callMethod:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="page."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))},callMethodWithCallback:function(params){var _a,err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="callMethodWithCallback:fail, Page["+params.pageId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="callMethodWithCallback:fail, page."+params.method+" not exists",_a),callback=params.args[params.args.length-1];callMethod(getPageVm(params.pageId),params.method,params.args).catch((function(type){callback({errMsg:err[type]})}))}};function getNodeId(params){return params.nodeId||params.elementId}var Element$1={getData:function(params){return getData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){return setData(getComponentVm(params.pageId,getNodeId(params)),params.data)},callMethod:function(params){var _a,nodeId=getNodeId(params),err=((_a={})[CALL_METHOD_ERROR.VM_NOT_EXISTS]="Component["+params.pageId+":"+nodeId+"] not exists",_a[CALL_METHOD_ERROR.METHOD_NOT_EXISTS]="component."+params.method+" not exists",_a);return new Promise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){return resolve(res)})).catch((function(type){reject(Error(err[type]))}))}))}},Api={};Object.keys(App$1).forEach((function(method){Api["App."+method]=App$1[method]})),Object.keys(Page$1).forEach((function(method){Api["Page."+method]=Page$1[method]})),Object.keys(Element$1).forEach((function(method){Api["Element."+method]=Element$1[method]}));var socketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function send(data){socketTask.send({data:JSON.stringify(data)})}function onMessage(res){var _a=JSON.parse(res.data),id=_a.id,method=_a.method,params=_a.params,data={id:id},fn=Api[method];if(!fn&&!fn)return data.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];return params.args.push((function(result){null!==result&&(data.result=result),send(data)})),void fn(params)}fn(params).then((function(res){res&&(data.result=res)})).catch((function(err){data.error={message:err.message}})).finally((function(){send(data)}))}catch(err){data.error={message:err.message},send(data)}}wx.$$initRuntimeAutomator=function(options){void 0===options&&(options={}),(socketTask=uni.connectSocket({url:wsEndpoint,complete:function(){}})).onMessage(onMessage),socketTask.onOpen((function(res){options.success&&options.success(),console.log("已开启自动化测试...")})),socketTask.onError((function(res){console.log("automator.onError",res)})),socketTask.onClose((function(){options.fail&&options.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500);
"use strict";var e=require("debug"),t=require("licia/isWindows"),o=require("licia/getPort"),r=require("qrcode-reader"),a=require("fs"),n=require("child_process"),s=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/dateFormat"),d=require("ws"),p=require("events"),f=require("licia/uuid"),m=require("licia/stringify");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=h(e),y=h(t),g=h(o),v=h(r),b=h(a),E=h(n),q=h(s),M=h(i),j=h(c),$=h(l),P=h(u),C=h(d),x=h(f),H=h(m);/^win/.test(process.platform);class k extends p.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",(e=>{this.emit("message",e.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(e){this.ws.send(e)}close(){this.ws.close()}}const F="Connection closed";class R extends p.EventEmitter{constructor(e,t,o){super(),this.puppet=t,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=w.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:o,error:r,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(o,n);const{callbacks:s}=this;if(t&&s.has(t)){const e=s.get(t);s.delete(t),r?e.reject(Error(r.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(F))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},o=!0){if(o&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const r=x.default(),a=H.default({id:r,method:e,params:t});return this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise(((e,t)=>{try{this.transport.send(a)}catch(e){t(Error(F))}this.callbacks.set(r,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((o,r)=>{const a=new C.default(e);a.addEventListener("open",(()=>{o(new R(new k(a),t,"devtool"))})),a.addEventListener("error",r)}))}static createRuntimeConnection(e,t,o){return new Promise(((r,a)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new C.default.Server({port:e});j.default((async()=>{if(t.runtimeConnection)return!0}),o,1e3).catch((()=>{n.close(),a("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const o=new R(new k(e),t,"runtime");t.setRuntimeConnection(o),r(o)})),t.setRuntimeServer(n)}))}}const D=w.default("automator:devtool");async function S(e,t,o){const{port:r,cliPath:a,timeout:n,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};s&&(t.cwd=s);let o=$.default(c,[]);o=$.default(o,["auto","--project"]),o=$.default(o,[e,"--auto-port",M.default(r)]),i&&(o=$.default(o,["--auto-account",i]));try{D("%s %o %o",a,o,t);const e=E.default.spawn(a,o,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{d=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{d=!0}),15e3);const p=await j.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let o;try{o=await R.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return o}({wsEndpoint:`ws://127.0.0.1:${r}`},o);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${o.devtools.name}, please make sure cliPath is correctly specified`);if(d)throw Error(`Failed to launch ${o.devtools.name} , please make sure http port is open`);return await q.default(5e3),D(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const T={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[y.default?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const o=function(e,t){const o=t.devtools.paths.slice(0);e&&o.unshift(e);for(const e of o)if(b.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let r=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{r=await async function(e,t){const o=await g.default(e||t);if(e&&o!==e)throw Error(`Port ${e} is in use, please specify another port`);return o}(r)}catch(t){e.launch=!1}else{r===await g.default(r)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:r,cliPath:o})},async create(e,t,o){const r=await S(e,t,o);return o.compiled?w.default("automator:devtool")("Waiting for runtime automator"):(w.default("automator:devtool")("initRuntimeAutomator"),r.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),r}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:o}=await e("Tool.enableRemoteDebug",t,!1);return o&&(o=await function(e){const t=new Buffer(e,"base64");return new Promise((async(e,o)=>{const r=await require("jimp").read(t),a=new v.default;a.callback=function(t,r){if(t)return o(t);e(r.result)},a.decode(r.bitmap)}))}(o)),{qrCode:o}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(o=t.functionDeclaration,"}"===o[o.length-1]?o.replace("{","{\nvar uni = wx;\n"):o.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var o}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=T;
"use strict";var e=require("debug"),t=require("licia/isWindows"),a=require("licia/getPort"),o=require("qrcode-reader"),r=require("fs"),n=require("child_process"),s=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/dateFormat"),d=require("ws"),p=require("events"),f=require("licia/uuid"),m=require("licia/stringify");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var w=h(e),y=h(t),g=h(a),v=h(o),b=h(r),E=h(n),q=h(s),M=h(i),j=h(c),$=h(l),P=h(u),C=h(d),x=h(f),H=h(m);/^win/.test(process.platform);class k extends p.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",(e=>{this.emit("message",e.data)})),this.ws.addEventListener("close",(()=>{this.emit("close")}))}send(e){this.ws.send(e)}close(){this.ws.close()}}const F="Connection closed";class R extends p.EventEmitter{constructor(e,t,a){super(),this.puppet=t,this.namespace=a,this.callbacks=new Map,this.transport=e,this.debug=w.default("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:a,error:o,result:r,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(a,n);const{callbacks:s}=this;if(t&&s.has(t)){const e=s.get(t);s.delete(t),o?e.reject(Error(o.message||o.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(F))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},a=!0){if(a&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=x.default(),r=H.default({id:o,method:e,params:t});return this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),new Promise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(F))}this.callbacks.set(o,{resolve:e,reject:t})}))}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise(((a,o)=>{const r=new C.default(e);r.addEventListener("open",(()=>{a(new R(new k(r),t,"devtool"))})),r.addEventListener("error",o)}))}static createRuntimeConnection(e,t,a){return new Promise(((o,r)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const n=new C.default.Server({port:e});j.default((async()=>{if(t.runtimeConnection)return!0}),a,1e3).catch((()=>{n.close(),r("Failed to connect to runtime, please make sure the project is running")})),n.on("connection",(function(e){w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const a=new R(new k(e),t,"runtime");t.setRuntimeConnection(a),o(a)})),t.setRuntimeServer(n)}))}}const D=w.default("automator:devtool");async function S(e,t,a){const{port:o,cliPath:r,timeout:n,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};s&&(t.cwd=s);let a=$.default(c,[]);a=$.default(a,["auto","--project"]),a=$.default(a,[e,"--auto-port",M.default(o)]),i&&(a=$.default(a,["--auto-account",i]));try{D("%s %o %o",r,a,t);const e=E.default.spawn(r,a,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{d=!0}),15e3)})),e.unref()}catch(e){u=!1}}else setTimeout((()=>{d=!0}),15e3);const p=await j.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let a;try{a=await R.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return a}({wsEndpoint:`ws://127.0.0.1:${o}`},a);return e}catch(e){}}),n,1e3);if(u)throw Error(`Failed to launch ${a.devtools.name}, please make sure cliPath is correctly specified`);if(d)throw Error(`Failed to launch ${a.devtools.name} , please make sure http port is open`);return await q.default(5e3),D(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}const T={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[y.default?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const a=function(e,t){const a=t.devtools.paths.slice(0);e&&a.unshift(e);for(const e of a)if(b.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let o=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{o=await async function(e,t){const a=await g.default(e||t);if(e&&a!==e)throw Error(`Port ${e} is in use, please specify another port`);return a}(o)}catch(t){e.launch=!1}else{o===await g.default(o)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:o,cliPath:a})},async create(e,t,a){const o=await S(e,t,a);return a.compiled?w.default("automator:devtool")("Waiting for runtime automator"):(w.default("automator:devtool")("initRuntimeAutomator"),o.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),o}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:a}=await e("Tool.enableRemoteDebug",t,!1);return a&&(a=await function(e){const t=new Buffer(e,"base64");return new Promise((async(e,a)=>{const o=await require("jimp").read(t),r=new v.default;r.callback=function(t,o){if(t)return a(t);e(o.result)},r.decode(o.bitmap)}))}(a)),{qrCode:a}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(a=t.functionDeclaration,"}"===a[a.length-1]?a.replace("{","{\nvar uni = wx;\n"):a.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var a}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=T;
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册