2 lines
8.4 KiB
JavaScript
2 lines
8.4 KiB
JavaScript
"use strict";var e=require("debug"),t=require("licia/isWindows"),o=require("licia/getPort"),s=require("qrcode-reader"),n=require("fs"),r=require("child_process"),a=require("licia/sleep"),i=require("licia/toStr"),c=require("licia/waitUntil"),l=require("licia/concat"),u=require("licia/dateFormat"),d=require("ws"),h=require("events"),p=require("licia/uuid"),m=require("licia/stringify"),f=require("os");function w(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var g=w(e),v=w(t),y=w(o),b=w(s),E=w(n),C=w(r),M=w(a),A=w(i),q=w(c),P=w(l),H=w(u),x=w(d),T=w(p),$=w(m),j=w(f);/^win/.test(process.platform);class k extends h.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,t){this.ws.send(e,t)}close(){this.ws.close()}}const S=new Map,R=new Map,_="Connection closed";class D extends h.EventEmitter{constructor(e,t,o){super(),this.puppet=t,this.namespace=o,this.callbacks=new Map,this.transport=e,this.isAlive=!0,this.id=Date.now(),this.exConnectionClosed=!1,this.debug=g.default("automator:protocol:"+this.namespace),this.onMessage=e=>{var t,o,s;if(this.isAlive=!0,"true"===process.env.UNI_APP_X&&'"pong"'===e)return;const{id:n,method:r,error:a,result:i,params:c}=JSON.parse(e);if((null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.length)>10240){let e=JSON.stringify({id:n,method:r,error:a,result:Object.assign(Object.assign({},i),{data:i.data.substring(0,30)+"...<more>"}),params:c});this.debug(`${H.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`)}else this.debug(`${H.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);if(null===(o=null==i?void 0:i.method)||void 0===o?void 0:o.startsWith("on"))return void((e,t)=>{const o=S.get(e.method);(null==o?void 0:o.has(t))&&o.get(t)(e.data)})(i,n);if(null===(s=null==i?void 0:i.method)||void 0===s?void 0:s.startsWith("Socket.")){return void((e,t,o)=>{const s=R.get(t);(null==s?void 0:s.has(e))&&s.get(e)(o)})(i.method.replace("Socket.",""),i.id,i.data)}if(!n)return this.puppet.emit(r,c);const{callbacks:l}=this;if(n&&l.has(n)){const e=l.get(n);l.delete(n),a?e.reject(Error(a.message||a.detailMessage||a.errMsg)):e.resolve(i)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(_))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}isBroken(){return!!this.exConnectionClosed}send(e,t={},o=!0){if(o&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);if(this.exConnectionClosed)throw this.exConnectionClosed;const s=T.default(),n=$.default({id:s,method:e,params:t});return"ping"!==e&&this.debug(`${H.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise(((e,t)=>{try{this.transport.send(n,(e=>{e&&t(Error(_))}))}catch(e){t(Error(_))}this.callbacks.set(s,{resolve:e,reject:t})})).catch((e=>{throw e.message===_&&(this.exConnectionClosed=e),e}))}dispose(){this.callbacks.clear(),this.transport.close()}startHeartbeat(){"true"===process.env.UNI_APP_X&&("android"===process.env.UNI_APP_PLATFORM?this.startXAndroidHeartbeat():"ios"===process.env.UNI_APP_PLATFORM&&this.startXIosHeartbeat())}startXAndroidHeartbeat(){const e=new Map,t=function(e){try{return require(e)}catch(t){return require(require.resolve(e,{paths:[process.cwd()]}))}}("adbkit"),o=j.default.platform();let s="",n="";"darwin"===o?(s='ps | grep "u0_a"',n="logcat -b crash | grep -C 10 io.dcloud.uniappx"):"win32"===o&&(s='dumpsys activity | findstr "Run"',n="logcat | findstr UncaughtExceptionHandler"),e.set(this.id,setInterval((async()=>{if(!this.isAlive){const r=t.createClient(),a=await r.listDevices();if(!a.length)throw Error("Device not found");const i=a[0].id,c=await r.getProperties(i);return("1"===c["ro.kernel.qemu"]||"goldfish"===c["ro.hardware"])&&"win32"===o&&(n="logcat | grep UncaughtExceptionHandler"),r.shell(i,s).then((function(e){let t,o="";e.on("data",(function(e){o+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{o.includes("io.dcloud.uniapp")||(r.shell(i,"screencap -p /sdcard/uni-automator-screenshot-when-uniapp-un-active.png"),console.log("ADBCommandAppIsLaunch",s),console.log("ADBCommandAppIsLaunch res",o),console.log("Stop the test process."))}),50)}))})),r.shell(i,n).then((e=>{let t,o="";e.on("data",(e=>{o+=e.toString(),t&&clearTimeout(t),t=setTimeout((()=>{console.log(`crash log: ${o}`)}),50)}))})),clearInterval(e.get(this.id)),e.delete(this.id),void this.dispose()}this.send("ping").catch((e=>{})),this.isAlive=!1}),5e3))}startXIosHeartbeat(){const e=new Map;e.set(this.id,setInterval((async()=>{if(!this.isAlive)return console.log("Stop the test process."),clearInterval(e.get(this.id)),e.delete(this.id),void this.dispose();this.send("ping").catch((e=>{})),this.isAlive=!1}),5e3))}static createDevtoolConnection(e,t){return new Promise(((o,s)=>{const n=new x.default(e);n.addEventListener("open",(()=>{o(new D(new k(n),t,"devtool"))})),n.addEventListener("error",s)}))}static createRuntimeConnection(e,t,o){return new Promise(((s,n)=>{g.default("automator:runtime")(`${H.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const r=new x.default.Server({port:e});q.default((async()=>{if(t.runtimeConnection)return!0}),o,1e3).catch((()=>{r.close(),n("Failed to connect to runtime, please make sure the project is running")})),r.on("connection",(function(e){g.default("automator:runtime")(`${H.default("yyyy-mm-dd HH:MM:ss:l")} connected`);const o=new D(new k(e),t,"runtime");t.setRuntimeConnection(o),process.env.UNI_AUTOMATOR_NEED_RESTART_BETWEEN_TEST?global.socketConnected=!0:o.startHeartbeat(),s(o)})),t.setRuntimeServer(r)}))}}const I=g.default("automator:devtool");async function O(e,t,o){const{port:s,cliPath:n,timeout:r,cwd:a="",account:i="",args:c=[],launch:l=!0}=t;let u=!1,d=!1;if(!1!==l){const t={stdio:"ignore",detached:!0};a&&(t.cwd=a);let o=P.default(c,[]);o=P.default(o,["auto","--project"]),o=P.default(o,[e,"--auto-port",A.default(s)]),i&&(o=P.default(o,["--auto-account",i]));try{I("%s %o %o",n,o,t);const e=C.default.spawn(n,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 h=await q.default((async()=>{try{if(u||d)return!0;const e=await async function(e,t){let o;try{o=await D.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:${s}`},o);return e}catch(e){}}),r,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 M.default(5e3),I(`${H.default("yyyy-mm-dd HH:MM:ss:l")} connected`),h}const F={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[v.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(E.default.existsSync(e))return e;throw Error(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const o=await y.default(e||t);if(e&&o!==e)throw Error(`Port ${e} is in use, please specify another port`);return o}(s)}catch(t){e.launch=!1}else{s===await y.default(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:o})},async create(e,t,o){const s=await O(e,t,o);return o.compiled?g.default("automator:devtool")("Waiting for runtime automator"):(g.default("automator:devtool")("initRuntimeAutomator"),s.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),s}},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 s=await require("jimp").read(t),n=new b.default;n.callback=function(t,s){if(t)return o(t);e(s.result)},n.decode(s.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=F;
|