varCALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){returnnull==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;functiongetPaths(path,data){if(isArray(path))returnpath;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];varval,key,res=[];returnpath.replace(PATH_RE,(function(match,p1,offset,string){returnres.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}functiongetPageId(page){returnpage.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void0}functiongetPagePath(page){returnpage.route||page.uri}functiongetPageQuery(page){returnpage.options||page.$page&&page.$page.options||{}}functionparsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}functiongetPageVm(id){varpage=function(id){returngetCurrentPages().find((function(page){returngetPageId(page)===id}))}(id);returnpage&&page.$vm}functionfindComponentVm(vm,nodeId){varres;returnvm&&(!function(vm,nodeId){returnvm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;varscope}(vm,nodeId)?vm.$children.find((function(child){returnres=findComponentVm(child,nodeId)})):res=vm),res}functiongetComponentVm(pageId,nodeId){varpageVm=getPageVm(pageId);returnpageVm&&findComponentVm(pageVm,nodeId)}functiongetData(vm,path){vardata;returnvm&&(data=path?function(data,path){vardataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}returndata}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}functionsetData(vm,data){returnvm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}functioncallMethod(vm,method,args){returnnewPromise((function(resolve,reject){if(!vm)returnreject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])returnreject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);varobj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeofobj&&"function"!=typeofobj||"function"!=typeofobj.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={}));varSYNC_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/;functionisSyncApi(method){returnSYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}varApp$1={getPageStack:function(){returnPromise.resolve({pageStack:getCurrentPages().map((function(page){returnparsePage(page)}))})},getCurrentPage:function(){varpages=getCurrentPages(),len=pages.length;returnnewPromise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){varmethod=params.method,args=params.args;returnnewPromise((function(resolve,reject){if(!uni[method])returnreject(Error("uni."+method+" not exists"));if(isSyncApi(method))returnresolve({result:uni[method].apply(uni,args)});varparams=[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){varmethod=params.method;if(!uni[method])throwError("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throwError("You can't mock uni."+method);varmockFn,result=params.result,functionDeclaration=params.functionDeclaration;returnisUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],deleteoriginUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){returnresult}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(varargs=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];returnnewFunction("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){returnnewPromise((function(resolve,reject){varpages=getCurrentPages(),len=pages.length;if(len){varpage=pages[len-1];if(page){varwebview=page.$getAppWebview(),bitmap_1=newplus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){vardata=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})}}elsereject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){returngetData(getPageVm(params.pageId),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){returnresolve(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]})}))}};functiongetNodeId(params){returnparams.nodeId||params.elementId}varElement$1={getData:function(params){returngetData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){returnresolve(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]}));varsocketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;functionsend(data){socketTask.send({data:JSON.stringify(data)})}functiononMessage(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)returndata.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];returnparams.args.push((function(result){null!==result&&(data.result=result),send(data)})),voidfn(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){void0===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);
varCALL_METHOD_ERROR,__assign=function(){return__assign=Object.assign||function(t){for(vars,i=1,n=arguments.length;i<n;i++)for(varpins=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);returnt},__assign.apply(this,arguments)},hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){returnnull==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;functiongetPaths(path,data){if(isArray(path))returnpath;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];varval,key,res=[];returnpath.replace(PATH_RE,(function(match,p1,offset,string){returnres.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}functiongetPageId(page){returnpage.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void0}functiongetPagePath(page){returnpage.route||page.uri}functiongetPageQuery(page){returnpage.options||page.$page&&page.$page.options||{}}functionparsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}functiongetPageVm(id){varpage=function(id){returngetCurrentPages().find((function(page){returngetPageId(page)===id}))}(id);returnpage&&page.$vm}functionfindComponentVm(vm,nodeId){varres;returnvm&&(!function(vm,nodeId){returnvm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;varscope}(vm,nodeId)?vm.$children.find((function(child){returnres=findComponentVm(child,nodeId)})):res=vm),res}functiongetComponentVm(pageId,nodeId){varpageVm=getPageVm(pageId);returnpageVm&&findComponentVm(pageVm,nodeId)}functiongetData(vm,path){vardata;returnvm&&(data=path?function(data,path){vardataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}returndata}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}functionsetData(vm,data){returnvm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}functioncallMethod(vm,method,args){returnnewPromise((function(resolve,reject){if(!vm)returnreject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])returnreject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);varobj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeofobj&&"function"!=typeofobj||"function"!=typeofobj.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={}));varSYNC_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"],onApisEventMap=newMap,ON_APIS=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;functionisSyncApi(method){returnSYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}varApp$1={getPageStack:function(){returnPromise.resolve({pageStack:getCurrentPages().map((function(page){returnparsePage(page)}))})},getCurrentPage:function(){varpages=getCurrentPages(),len=pages.length;returnnewPromise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){varmethod=params.method,args=params.args;returnnewPromise((function(resolve,reject){if(ON_APIS.includes(method)){onApisEventMap.has(method)||onApisEventMap.set(method,newMap);varuuid_1=args[0],callback=function(res){send({id:uuid_1,result:__assign({method:method},res)})};returnonApisEventMap.get(method).set(uuid_1,callback),uni[method](callback),resolve({result:null})}if(method.startsWith("off")&&ON_APIS.includes(method.replace("off","on"))){varonMethod=method.replace("off","on");if(onApisEventMap.has(onMethod)){varuuid=args[0];if(void0!==uuid){callback=onApisEventMap.get(onMethod).get(uuid);uni[method](callback),onApisEventMap.get(onMethod).delete(uuid)}else{onApisEventMap.get(onMethod).forEach((function(callback){uni[method](callback)})),onApisEventMap.delete(onMethod)}}returnresolve({result:null})}if(!uni[method])returnreject(Error("uni."+method+" not exists"));if(isSyncApi(method))returnresolve({result:uni[method].apply(uni,args)});varparams=[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){varmethod=params.method;if(!uni[method])throwError("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throwError("You can't mock uni."+method);varmockFn,result=params.result,functionDeclaration=params.functionDeclaration;returnisUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],deleteoriginUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){returnresult}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(varargs=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];returnnewFunction("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){returnnewPromise((function(resolve,reject){varpages=getCurrentPages(),len=pages.length;if(len){varpage=pages[len-1];if(page){varwebview=page.$getAppWebview(),bitmap_1=newplus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){vardata=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})}}elsereject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){returngetData(getPageVm(params.pageId),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){returnresolve(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]})}))}};functiongetNodeId(params){returnparams.nodeId||params.elementId}varElement$1={getData:function(params){returngetData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){returnresolve(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]}));varsocketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;functionsend(data){socketTask.send({data:JSON.stringify(data)})}functiononMessage(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)returndata.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];returnparams.args.push((function(result){null!==result&&(data.result=result),send(data)})),voidfn(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){void0===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);export{send};
"use strict";vare=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");functiong(e){returne&&"object"==typeofe&&"default"ine?e:{default:e}}varw=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);constL=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;varN;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));constk={[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=>{consts=(k[e]||[]).filter((e=>e.test.test(t)));for(consteofs)t=e.processor(t);returnt},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);classBextendsd.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()}}constG="Connection closed";classWextendsd.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=newMap,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)returnthis.puppet.emit(s,n);const{callbacks:o}=this;if(t&&o.has(t)){conste=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))returnthis.puppet.adapter.send(this,e,t);consta=S.default(),r=T.default({id:a,method:e,params:t});returnthis.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),newPromise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}staticcreateDevtoolConnection(e,t){returnnewPromise(((s,a)=>{constr=newA.default(e);r.addEventListener("open",(()=>{s(newW(newB(r),t,"devtool"))})),r.addEventListener("error",a)}))}staticcreateRuntimeConnection(e,t,s){returnnewPromise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);constn=newA.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`);consts=newW(newB(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}constz=E.default("automator:devtool");asyncfunctionJ(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;letu=!1,p=!1;if(!1!==l){constt={stdio:"ignore"};o&&(t.cwd=o);lets=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);conste=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}}elsesetTimeout((()=>{p=!0}),15e3);constm=await$.default((async()=>{try{if(u||p)return!0;conste=awaitasyncfunction(e,t){lets;try{s=awaitW.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throwError(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}returns}({wsEndpoint:`ws://127.0.0.1:${a}`},s);returne}catch(e){}}),n,1e3);if(u)throwError(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throwError(`Failed to launch ${s.devtools.name} , please make sure http port is open`);returnawaitj.default(5e3),z(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}constU=[];["","-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`)}));constV={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:U,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:asyncfunction(e,t){consts=function(e,t){consts=t.devtools.paths.slice(0);e&&s.unshift(e);for(consteofs)if(v.default.existsSync(e))returne;throwError(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);leta=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=awaitasyncfunction(e,t){consts=awaitq.default(e||t);if(e&&s!==e)throwError(`Port ${e} is in use, please specify another port`);returns}(a)}catch(t){e.launch=!1}else{a===awaitq.default(a)&&(e.launch=!0)}returnObject.assign(Object.assign({},e),{port:a,cliPath:s})},asynccreate(e,t,s){consta=awaitJ(e,t,s);returns.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:asynce=>({qrCode:(awaite("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(awaite("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(awaite("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split("").map((e=>D(e))).join(""))}))).map((e=>{constt=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};vars}},"Page.getWindowProperties":{reflect:async(e,t)=>{consts=t.names.map((e=>e.replace("document.documentElement.",""))),a=(awaite("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{consts=[t.type+"HTML"];return{html:(awaite("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(awaite("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=awaite("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId}${t.selector}`}));returns.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:awaite("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:awaite("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=V;
"use strict";vare=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");functiong(e){returne&&"object"==typeofe&&"default"ine?e:{default:e}}varw=g(e),y=g(t),E=g(s),v=g(a),b=g(r),P=g(n),j=g(o),M=g(i),O=g(c),$=g(l),q=g(u),C=g(p),A=g(m),S=g(f),T=g(h);constL=/(^[a-z][a-z0-9-]*)/i,H=/^navigator/i,R=/^swan-nav$/i;varN;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(N||(N={}));constk={[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=>{consts=(k[e]||[]).filter((e=>e.test.test(t)));for(consteofs)t=e.processor(t);returnt},D=x(N.SELECTOR),F=x(N.TAGNAME),I=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});/^win/.test(process.platform);classWextendsd.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()}}constB=newMap,G="Connection closed";classzextendsd.EventEmitter{constructor(e,t,s){super(),this.puppet=t,this.namespace=s,this.callbacks=newMap,this.transport=e,this.debug=E.default("automator:protocol:"+this.namespace),this.onMessage=e=>{vart;this.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:s,method:a,error:r,result:n,params:o}=JSON.parse(e);if(null===(t=null==n?void0:n.method)||void0===t?void0:t.startsWith("on"))returnvoid((e,t,s)=>{consta=B.get(e);a.has(t)&&a.get(t)(s)})(n.method,s,n);if(!s)returnthis.puppet.emit(a,o);const{callbacks:i}=this;if(s&&i.has(s)){conste=i.get(s);i.delete(s),r?e.reject(Error(r.message||r.detailMessage)):e.resolve(n)}},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))returnthis.puppet.adapter.send(this,e,t);consta=S.default(),r=T.default({id:a,method:e,params:t});returnthis.debug(`${C.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),newPromise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(G))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}staticcreateDevtoolConnection(e,t){returnnewPromise(((s,a)=>{constr=newA.default(e);r.addEventListener("open",(()=>{s(newz(newW(r),t,"devtool"))})),r.addEventListener("error",a)}))}staticcreateRuntimeConnection(e,t,s){returnnewPromise(((a,r)=>{E.default("automator:runtime")(`${C.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);constn=newA.default.Server({port:e});O.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`);consts=newz(newW(e),t,"runtime");t.setRuntimeConnection(s),a(s)})),t.setRuntimeServer(n)}))}}constJ=E.default("automator:devtool");asyncfunctionU(e,t,s){const{port:a,cliPath:r,timeout:n,cwd:o="",account:i="",args:c=[],launch:l=!0}=t;letu=!1,p=!1;if(!1!==l){constt={stdio:"ignore"};o&&(t.cwd=o);lets=$.default(c,[]);s=$.default(s,["--auto"]),s=$.default(s,[e,"--auto-port",M.default(a)]),i&&(s=$.default(s,["--auto-account",i]));try{J("%s %o %o",r,s,t);conste=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}}elsesetTimeout((()=>{p=!0}),15e3);constm=awaitO.default((async()=>{try{if(u||p)return!0;conste=awaitasyncfunction(e,t){lets;try{s=awaitz.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throwError(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}returns}({wsEndpoint:`ws://127.0.0.1:${a}`},s);returne}catch(e){}}),n,1e3);if(u)throwError(`Failed to launch ${s.devtools.name}, please make sure cliPath is correctly specified`);if(p)throwError(`Failed to launch ${s.devtools.name} , please make sure http port is open`);returnawaitj.default(5e3),J(`${C.default("yyyy-mm-dd HH:MM:ss:l")} connected`),m}constV=[];["","-rc"].forEach((e=>{v.default?(V.push(y.default.join(w.default.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),V.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):V.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)}));const_={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:V,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:asyncfunction(e,t){consts=function(e,t){consts=t.devtools.paths.slice(0);e&&s.unshift(e);for(consteofs)if(b.default.existsSync(e))returne;throwError(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);leta=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=awaitasyncfunction(e,t){consts=awaitq.default(e||t);if(e&&s!==e)throwError(`Port ${e} is in use, please specify another port`);returns}(a)}catch(t){e.launch=!1}else{a===awaitq.default(a)&&(e.launch=!0)}returnObject.assign(Object.assign({},e),{port:a,cliPath:s})},asynccreate(e,t,s){consta=awaitU(e,t,s);returns.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:asynce=>({qrCode:(awaite("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(awaite("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(awaite("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(s=t.selector,s.split("").map((e=>D(e))).join(""))}))).map((e=>{constt=e.properties;return{elementId:t.id,nodeId:t.id,tagName:F(t.tagName)}}))};vars}},"Page.getWindowProperties":{reflect:async(e,t)=>{consts=t.names.map((e=>e.replace("document.documentElement.",""))),a=(awaite("smartapp.element.getBySelector",{properties:s,selector:"html"}))[0];return{properties:s.map((e=>a.properties[e]))}}},"Element.getHTML":{reflect:async(e,t)=>{consts=[t.type+"HTML"];return{html:(awaite("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:s}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(awaite("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:s}=awaite("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId}${t.selector}`}));returns.forEach((e=>{e.nodeId=e.id})),{elements:s}}},"Element.getAttributes":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{attributes:s}},params:I},"Element.getStyles":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getComputedStyle",Object.assign({style:a},t)));return{styles:s}},params:I},"Element.getDOMProperties":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getProperty",Object.assign({property:a},t)));return{properties:s}},params:I},"Element.getProperties":{reflect:async(e,t)=>{consts=[];for(constaoft.names)s.push(awaite("smartapp.element.getAttribute",Object.assign({attribute:a},t)));return{properties:s}},params:I},"Element.getOffset":{reflect:async(e,t)=>({left:awaite("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:awaite("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:I},"Element.tap":{reflect:"smartapp.element.touch",params:I}}};module.exports=_;
varCALL_METHOD_ERROR,hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){returnnull==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;functiongetPaths(path,data){if(isArray(path))returnpath;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];varval,key,res=[];returnpath.replace(PATH_RE,(function(match,p1,offset,string){returnres.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}functiongetPageId(page){returnpage.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void0}functiongetPagePath(page){returnpage.route||page.uri}functiongetPageQuery(page){returnpage.options||page.$page&&page.$page.options||{}}functionparsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}functiongetPageVm(id){varpage=function(id){returngetCurrentPages().find((function(page){returngetPageId(page)===id}))}(id);returnpage&&page.$vm}functionfindComponentVm(vm,nodeId){varres;returnvm&&(!function(vm,nodeId){returnvm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;varscope}(vm,nodeId)?vm.$children.find((function(child){returnres=findComponentVm(child,nodeId)})):res=vm),res}functiongetComponentVm(pageId,nodeId){varpageVm=getPageVm(pageId);returnpageVm&&findComponentVm(pageVm,nodeId)}functiongetData(vm,path){vardata;returnvm&&(data=path?function(data,path){vardataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}returndata}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}functionsetData(vm,data){returnvm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}functioncallMethod(vm,method,args){returnnewPromise((function(resolve,reject){if(!vm)returnreject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])returnreject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);varobj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeofobj&&"function"!=typeofobj||"function"!=typeofobj.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={}));varSYNC_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/;functionisSyncApi(method){returnSYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}varApp$1={getPageStack:function(){returnPromise.resolve({pageStack:getCurrentPages().map((function(page){returnparsePage(page)}))})},getCurrentPage:function(){varpages=getCurrentPages(),len=pages.length;returnnewPromise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){varmethod=params.method,args=params.args;returnnewPromise((function(resolve,reject){if(!uni[method])returnreject(Error("uni."+method+" not exists"));if(isSyncApi(method))returnresolve({result:uni[method].apply(uni,args)});varparams=[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){varmethod=params.method;if(!uni[method])throwError("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throwError("You can't mock uni."+method);varmockFn,result=params.result,functionDeclaration=params.functionDeclaration;returnisUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],deleteoriginUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){returnresult}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(varargs=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];returnnewFunction("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){returnnewPromise((function(resolve,reject){varpages=getCurrentPages(),len=pages.length;if(len){varpage=pages[len-1];if(page){varwebview=page.$getAppWebview(),bitmap_1=newplus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){vardata=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})}}elsereject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){returngetData(getPageVm(params.pageId),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){returnresolve(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]})}))}};functiongetNodeId(params){returnparams.nodeId||params.elementId}varElement$1={getData:function(params){returngetData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){returnresolve(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]}));varsocketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;functionsend(data){socketTask.send({data:JSON.stringify(data)})}functiononMessage(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)returndata.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];returnparams.args.push((function(result){null!==result&&(data.result=result),send(data)})),voidfn(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){void0===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);
varCALL_METHOD_ERROR,__assign=function(){return__assign=Object.assign||function(t){for(vars,i=1,n=arguments.length;i<n;i++)for(varpins=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);returnt},__assign.apply(this,arguments)},hasOwnProperty=Object.prototype.hasOwnProperty,isUndef=function(v){returnnull==v},isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;functiongetPaths(path,data){if(isArray(path))returnpath;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];varval,key,res=[];returnpath.replace(PATH_RE,(function(match,p1,offset,string){returnres.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}functiongetPageId(page){returnpage.__wxWebviewId__?page.__wxWebviewId__:page.privateProperties?page.privateProperties.slaveId:page.$page?page.$page.id:void0}functiongetPagePath(page){returnpage.route||page.uri}functiongetPageQuery(page){returnpage.options||page.$page&&page.$page.options||{}}functionparsePage(page){return{id:getPageId(page),path:getPagePath(page),query:getPageQuery(page)}}functiongetPageVm(id){varpage=function(id){returngetCurrentPages().find((function(page){returngetPageId(page)===id}))}(id);returnpage&&page.$vm}functionfindComponentVm(vm,nodeId){varres;returnvm&&(!function(vm,nodeId){returnvm.$scope&&((scope=vm.$scope).__wxExparserNodeId__||scope.nodeId||scope.id)===nodeId;varscope}(vm,nodeId)?vm.$children.find((function(child){returnres=findComponentVm(child,nodeId)})):res=vm),res}functiongetComponentVm(pageId,nodeId){varpageVm=getPageVm(pageId);returnpageVm&&findComponentVm(pageVm,nodeId)}functiongetData(vm,path){vardata;returnvm&&(data=path?function(data,path){vardataPath,paths=getPaths(path,data);for(dataPath=paths.shift();!isUndef(dataPath);){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}returndata}(vm.$data,path):Object.assign({},vm.$data)),Promise.resolve({data:data})}functionsetData(vm,data){returnvm&&Object.keys(data).forEach((function(name){vm[name]=data[name]})),Promise.resolve()}functioncallMethod(vm,method,args){returnnewPromise((function(resolve,reject){if(!vm)returnreject(CALL_METHOD_ERROR.VM_NOT_EXISTS);if(!vm[method])returnreject(CALL_METHOD_ERROR.METHOD_NOT_EXISTS);varobj,ret=vm[method].apply(vm,args);!(obj=ret)||"object"!=typeofobj&&"function"!=typeofobj||"function"!=typeofobj.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={}));varSYNC_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"],onApisEventMap=newMap,ON_APIS=["onCompassChange","onThemeChange","onUserCaptureScreen","onWindowResize","onMemoryWarning","onAccelerometerChange","onKeyboardHeightChange","onNetworkStatusChange","onPushMessage","onLocationChange","onGetWifiList","onWifiConnected","onWifiConnectedWithPartialInfo"],originUni={},SYNC_API_RE=/Sync$/,MOCK_API_BLACKLIST_RE=/^on|^off/;functionisSyncApi(method){returnSYNC_API_RE.test(method)||-1!==SYNC_APIS.indexOf(method)}varApp$1={getPageStack:function(){returnPromise.resolve({pageStack:getCurrentPages().map((function(page){returnparsePage(page)}))})},getCurrentPage:function(){varpages=getCurrentPages(),len=pages.length;returnnewPromise((function(resolve,reject){len?resolve(parsePage(pages[len-1])):reject(Error("getCurrentPages().length=0"))}))},callUniMethod:function(params){varmethod=params.method,args=params.args;returnnewPromise((function(resolve,reject){if(ON_APIS.includes(method)){onApisEventMap.has(method)||onApisEventMap.set(method,newMap);varuuid_1=args[0],callback=function(res){send({id:uuid_1,result:__assign({method:method},res)})};returnonApisEventMap.get(method).set(uuid_1,callback),uni[method](callback),resolve({result:null})}if(method.startsWith("off")&&ON_APIS.includes(method.replace("off","on"))){varonMethod=method.replace("off","on");if(onApisEventMap.has(onMethod)){varuuid=args[0];if(void0!==uuid){callback=onApisEventMap.get(onMethod).get(uuid);uni[method](callback),onApisEventMap.get(onMethod).delete(uuid)}else{onApisEventMap.get(onMethod).forEach((function(callback){uni[method](callback)})),onApisEventMap.delete(onMethod)}}returnresolve({result:null})}if(!uni[method])returnreject(Error("uni."+method+" not exists"));if(isSyncApi(method))returnresolve({result:uni[method].apply(uni,args)});varparams=[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){varmethod=params.method;if(!uni[method])throwError("uni."+method+" not exists");if(!function(method){return!MOCK_API_BLACKLIST_RE.test(method)}(method))throwError("You can't mock uni."+method);varmockFn,result=params.result,functionDeclaration=params.functionDeclaration;returnisUndef(result)&&isUndef(functionDeclaration)?(originUni[method]&&(uni[method]=originUni[method],deleteoriginUni[method]),Promise.resolve()):(mockFn=isUndef(functionDeclaration)?isSyncApi(method)?function(){returnresult}:function(params){setTimeout((function(){result.errMsg&&-1!==result.errMsg.indexOf(":fail")?params.fail&¶ms.fail(result):params.success&¶ms.success(result),params.complete&¶ms.complete(result)}),4)}:function(){for(varargs=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];returnnewFunction("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){returnnewPromise((function(resolve,reject){varpages=getCurrentPages(),len=pages.length;if(len){varpage=pages[len-1];if(page){varwebview=page.$getAppWebview(),bitmap_1=newplus.nativeObj.Bitmap("captureScreenshot","captureScreenshot.png");webview.draw(bitmap_1,(function(res){vardata=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})}}elsereject(Error("getCurrentPage fail."))}))}},Page$1={getData:function(params){returngetData(getPageVm(params.pageId),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getPageVm(params.pageId),params.method,params.args).then((function(res){returnresolve(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]})}))}};functiongetNodeId(params){returnparams.nodeId||params.elementId}varElement$1={getData:function(params){returngetData(getComponentVm(params.pageId,getNodeId(params)),params.path)},setData:function(params){returnsetData(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);returnnewPromise((function(resolve,reject){callMethod(getComponentVm(params.pageId,nodeId),params.method,params.args).then((function(res){returnresolve(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]}));varsocketTask,wsEndpoint=process.env.UNI_AUTOMATOR_WS_ENDPOINT;functionsend(data){socketTask.send({data:JSON.stringify(data)})}functiononMessage(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)returndata.error={message:method+" unimplemented"},send(data);try{if("Page.callMethodWithCallback"===method){params.args=params.args||[];returnparams.args.push((function(result){null!==result&&(data.result=result),send(data)})),voidfn(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){void0===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);export{send};
"use strict";vare=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");functionh(e){returne&&"object"==typeofe&&"default"ine?e:{default:e}}varw=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);classkextendsp.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()}}constF="Connection closed";classRextendsp.EventEmitter{constructor(e,t,a){super(),this.puppet=t,this.namespace=a,this.callbacks=newMap,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)returnthis.puppet.emit(a,n);const{callbacks:s}=this;if(t&&s.has(t)){conste=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))returnthis.puppet.adapter.send(this,e,t);consto=x.default(),r=H.default({id:o,method:e,params:t});returnthis.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${r}`),newPromise(((e,t)=>{try{this.transport.send(r)}catch(e){t(Error(F))}this.callbacks.set(o,{resolve:e,reject:t})}))}dispose(){this.transport.close()}staticcreateDevtoolConnection(e,t){returnnewPromise(((a,o)=>{constr=newC.default(e);r.addEventListener("open",(()=>{a(newR(newk(r),t,"devtool"))})),r.addEventListener("error",o)}))}staticcreateRuntimeConnection(e,t,a){returnnewPromise(((o,r)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);constn=newC.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`);consta=newR(newk(e),t,"runtime");t.setRuntimeConnection(a),o(a)})),t.setRuntimeServer(n)}))}}constD=w.default("automator:devtool");asyncfunctionS(e,t,a){const{port:o,cliPath:r,timeout:n,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;letu=!1,d=!1;if(!1!==l){constt={stdio:"ignore",detached:!0};s&&(t.cwd=s);leta=$.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);conste=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}}elsesetTimeout((()=>{d=!0}),15e3);constp=awaitj.default((async()=>{try{if(u||d)return!0;conste=awaitasyncfunction(e,t){leta;try{a=awaitR.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throwError(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}returna}({wsEndpoint:`ws://127.0.0.1:${o}`},a);returne}catch(e){}}),n,1e3);if(u)throwError(`Failed to launch ${a.devtools.name}, please make sure cliPath is correctly specified`);if(d)throwError(`Failed to launch ${a.devtools.name} , please make sure http port is open`);returnawaitq.default(5e3),D(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}constT={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:asyncfunction(e,t){consta=function(e,t){consta=t.devtools.paths.slice(0);e&&a.unshift(e);for(consteofa)if(b.default.existsSync(e))returne;throwError(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);leto=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{o=awaitasyncfunction(e,t){consta=awaitg.default(e||t);if(e&&a!==e)throwError(`Port ${e} is in use, please specify another port`);returna}(o)}catch(t){e.launch=!1}else{o===awaitg.default(o)&&(e.launch=!0)}returnObject.assign(Object.assign({},e),{port:o,cliPath:a})},asynccreate(e,t,a){consto=awaitS(e,t,a);returna.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}=awaite("Tool.enableRemoteDebug",t,!1);returna&&(a=awaitfunction(e){constt=newBuffer(e,"base64");returnnewPromise((async(e,a)=>{consto=awaitrequire("jimp").read(t),r=newv.default;r.callback=function(t,o){if(t)returna(t);e(o.result)},r.decode(o.bitmap)}))}(a)),{qrCode:a}}},"App.callFunction":{reflect:async(e,t)=>{returne("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);vara}},"Element.getHTML":{reflect:async(e,t)=>({html:(awaite("Element.getWXML",t,!1)).wxml})}}};module.exports=T;
"use strict";vare=require("debug"),t=require("licia/isWindows"),o=require("licia/getPort"),a=require("qrcode-reader"),n=require("fs"),r=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");functionh(e){returne&&"object"==typeofe&&"default"ine?e:{default:e}}varw=h(e),y=h(t),v=h(o),g=h(a),b=h(n),E=h(r),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);classkextendsp.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()}}constF=newMap,R="Connection closed";classDextendsp.EventEmitter{constructor(e,t,o){super(),this.puppet=t,this.namespace=o,this.callbacks=newMap,this.transport=e,this.debug=w.default("automator:protocol:"+this.namespace),this.onMessage=e=>{vart;this.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:o,method:a,error:n,result:r,params:s}=JSON.parse(e);if(null===(t=null==r?void0:r.method)||void0===t?void0:t.startsWith("on"))returnvoid((e,t,o)=>{consta=F.get(e);a.has(t)&&a.get(t)(o)})(r.method,o,r);if(!o)returnthis.puppet.emit(a,s);const{callbacks:i}=this;if(o&&i.has(o)){conste=i.get(o);i.delete(o),n?e.reject(Error(n.message||n.detailMessage)):e.resolve(r)}},this.onClose=()=>{this.callbacks.forEach((e=>{e.reject(Error(R))}))},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},o=!0){if(o&&this.puppet.adapter.has(e))returnthis.puppet.adapter.send(this,e,t);consta=x.default(),n=H.default({id:a,method:e,params:t});returnthis.debug(`${P.default("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),newPromise(((e,t)=>{try{this.transport.send(n)}catch(e){t(Error(R))}this.callbacks.set(a,{resolve:e,reject:t})}))}dispose(){this.transport.close()}staticcreateDevtoolConnection(e,t){returnnewPromise(((o,a)=>{constn=newC.default(e);n.addEventListener("open",(()=>{o(newD(newk(n),t,"devtool"))})),n.addEventListener("error",a)}))}staticcreateRuntimeConnection(e,t,o){returnnewPromise(((a,n)=>{w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);constr=newC.default.Server({port:e});j.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){w.default("automator:runtime")(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`);consto=newD(newk(e),t,"runtime");t.setRuntimeConnection(o),a(o)})),t.setRuntimeServer(r)}))}}constS=w.default("automator:devtool");asyncfunctionT(e,t,o){const{port:a,cliPath:n,timeout:r,cwd:s="",account:i="",args:c=[],launch:l=!0}=t;letu=!1,d=!1;if(!1!==l){constt={stdio:"ignore",detached:!0};s&&(t.cwd=s);leto=$.default(c,[]);o=$.default(o,["auto","--project"]),o=$.default(o,[e,"--auto-port",M.default(a)]),i&&(o=$.default(o,["--auto-account",i]));try{S("%s %o %o",n,o,t);conste=E.default.spawn(n,o,t);e.on("error",(e=>{u=!0})),e.on("exit",(()=>{setTimeout((()=>{d=!0}),15e3)})),e.unref()}catch(e){u=!1}}elsesetTimeout((()=>{d=!0}),15e3);constp=awaitj.default((async()=>{try{if(u||d)return!0;conste=awaitasyncfunction(e,t){leto;try{o=awaitD.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throwError(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}returno}({wsEndpoint:`ws://127.0.0.1:${a}`},o);returne}catch(e){}}),r,1e3);if(u)throwError(`Failed to launch ${o.devtools.name}, please make sure cliPath is correctly specified`);if(d)throwError(`Failed to launch ${o.devtools.name} , please make sure http port is open`);returnawaitq.default(5e3),S(`${P.default("yyyy-mm-dd HH:MM:ss:l")} connected`),p}constA={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:asyncfunction(e,t){consto=function(e,t){consto=t.devtools.paths.slice(0);e&&o.unshift(e);for(consteofo)if(b.default.existsSync(e))returne;throwError(`${t.devtools.name} not found, please specify executablePath option`)}(e.executablePath,t);leta=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{a=awaitasyncfunction(e,t){consto=awaitv.default(e||t);if(e&&o!==e)throwError(`Port ${e} is in use, please specify another port`);returno}(a)}catch(t){e.launch=!1}else{a===awaitv.default(a)&&(e.launch=!0)}returnObject.assign(Object.assign({},e),{port:a,cliPath:o})},asynccreate(e,t,o){consta=awaitT(e,t,o);returno.compiled?w.default("automator:devtool")("Waiting for runtime automator"):(w.default("automator:devtool")("initRuntimeAutomator"),a.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:o}=awaite("Tool.enableRemoteDebug",t,!1);returno&&(o=awaitfunction(e){constt=newBuffer(e,"base64");returnnewPromise((async(e,o)=>{consta=awaitrequire("jimp").read(t),n=newg.default;n.callback=function(t,a){if(t)returno(t);e(a.result)},n.decode(a.bitmap)}))}(o)),{qrCode:o}}},"App.callFunction":{reflect:async(e,t)=>{returne("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);varo}},"Element.getHTML":{reflect:async(e,t)=>({html:(awaite("Element.getWXML",t,!1)).wxml})}}};module.exports=A;