From ef345f1437be89d3ecfa3ac1e7f1aecb29ee9250 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Tue, 16 Jun 2020 17:15:37 +0800 Subject: [PATCH] feat(automator): grant permissions --- packages/uni-app-plus/dist/automator.view.js | 2 +- packages/uni-app-plus/lib/uni.automator.js | 2 +- packages/uni-automator/dist/environment.js | 2 +- packages/uni-automator/dist/index.js | 4 ++-- packages/uni-automator/package.json | 3 ++- packages/uni-h5/dist/automator.js | 2 +- packages/uni-mp-baidu/lib/uni.automator.js | 2 +- packages/uni-mp-weixin/lib/uni.automator.js | 2 +- 8 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/uni-app-plus/dist/automator.view.js b/packages/uni-app-plus/dist/automator.view.js index 677c7c19f..2b97b2ff7 100644 --- a/packages/uni-app-plus/dist/automator.view.js +++ b/packages/uni-app-plus/dist/automator.view.js @@ -12,4 +12,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -function e(){for(var e=0,t=0,r=arguments.length;t]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("t;t++)o(e,e._deferreds[t]);e._deferreds=null}function a(e,t){var n=!1;try{e((function(e){n||(n=!0,i(t,e))}),(function(e){n||(n=!0,u(t,e))}))}catch(e){if(n)return;n=!0,u(t,e)}}var s=setTimeout;r.prototype.catch=function(e){return this.then(null,e)},r.prototype.then=function(e,t){var r=new this.constructor(n);return o(this,new function(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}(e,t,r)),r},r.prototype.finally=e,r.all=function(e){return new r((function(n,r){function o(e,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var c=t.then;if("function"==typeof c)return void c.call(t,(function(t){o(e,t)}),r)}i[e]=t,0==--u&&n(i)}catch(e){r(e)}}if(!t(e))return r(new TypeError("Promise.all accepts an array"));var i=Array.prototype.slice.call(e);if(0===i.length)return n([]);for(var u=i.length,c=0;i.length>c;c++)o(c,i[c])}))},r.resolve=function(e){return e&&"object"==typeof e&&e.constructor===r?e:new r((function(t){t(e)}))},r.reject=function(e){return new r((function(t,n){n(e)}))},r.race=function(e){return new r((function(n,o){if(!t(e))return o(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;u>i;i++)r.resolve(e[i]).then(n,o)}))},r._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){s(e,0)},r._unhandledRejectionFn=function(e){void 0!==console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype.finally||(l.Promise.prototype.finally=e):l.Promise=r}));var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function r(){if(!t)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}for(var o=[],i=0;i<256;++i)o[i]=(i+256).toString(16).substr(1);function u(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var u=(e=e||{}).random||(e.rng||r)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,t)for(var c=0;c<16;++c)t[i+c]=u[c];return t||function(e,t){var n=t||0,r=o;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}(u)}var c=Object.prototype.hasOwnProperty,a=Array.isArray,s=function(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}},l=/-(\w)/g,f=s((function(e){return e.replace(l,(function(e,t){return t?t.toUpperCase():""}))})),d=s((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),p=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function m(e,t){if(a(e))return e;if(t&&(n=t,r=e,c.call(n,r)))return[e];var n,r,o=[];return e.replace(p,(function(e,t,n,r){return o.push(n?r.replace(/\\(\\)?/g,"$1"):t||e),r})),o}function v(e,t){var n,r=m(t,e);for(n=r.shift();null!=n;){if(null==(e=e[n]))return;n=r.shift()}return e}var h=new Map;function g(e){if(!function(e){if(e){var t=e.tagName;return 0===t.indexOf("UNI-")||"BODY"===t}return!1}(e))throw Error("no such element");var t,n,r={elementId:(t=e,n=t._id,n||(n=u(),t._id=n,h.set(n,{id:n,element:t})),n),tagName:e.tagName.toLocaleLowerCase().replace("uni-","")},o=e.__vue__;return o&&(o.$parent&&o.$parent.$el===e&&(o=o.$parent),o&&!o.$options.isReserved&&(r.nodeId=function(e){if(e._$weex)return e._uid;if(e._$id)return e._$id;var t=function(e){for(var t=e.$parent;t;){if(t._$id)return t;t=t.$parent}}(e);if(!e.$parent)return"-1";var n=e.$vnode,r=n.context;return r&&r!==t&&r._$id?r._$id+";"+t._$id+","+n.data.attrs._i:t._$id+","+n.data.attrs._i}(o))),"video"===r.tagName&&(r.videoId=r.nodeId),r}var _={input:{input:function(e,t){var n=e.__vue__;n.valueSync=t,n.$triggerInput({},{value:t})}},textarea:{input:function(e,t){var n=e.__vue__;n.valueSync=t,n.$triggerInput({},{value:t})}},"scroll-view":{scrollTo:function(e,t,n){var r=e.__vue__.$refs.main;r.scrollLeft=t,r.scrollTop=n},scrollTop:function(e){return e.__vue__.$refs.main.scrollTop},scrollLeft:function(e){return e.__vue__.$refs.main.scrollLeft},scrollWidth:function(e){return e.__vue__.$refs.main.scrollWidth},scrollHeight:function(e){return e.__vue__.$refs.main.scrollHeight}},swiper:{swipeTo:function(e,t){e.__vue__.current=t}},"movable-view":{moveTo:function(e,t,n){e.__vue__._animationTo(t,n)}},switch:{tap:function(e){e.click()}},slider:{slideTo:function(e,t){var n=e.__vue__,r=n.$refs["uni-slider"],o=r.offsetWidth,i=r.getBoundingClientRect().left;n.value=t,n._onClick({x:(t-n.min)*o/(n.max-n.min)+i})}}},y={getWindow:function(e){return window},getDocument:function(e){return document},getEl:function(e){var t=h.get(e);if(!t)throw Error("element destroyed");return t.element},getOffset:function(e){var t=e.getBoundingClientRect();return Promise.resolve({left:t.left+window.pageXOffset,top:t.top+window.pageYOffset})},querySelector:function(e,t){return"page"===t&&(t="body"),Promise.resolve(g(e.querySelector(t)))},querySelectorAll:function(e,t){var n=[],r=document.querySelectorAll(t);return[].forEach.call(r,(function(e){try{n.push(g(e))}catch(e){}})),Promise.resolve({elements:n})},queryProperties:function(e,t){return Promise.resolve({properties:t.map((function(t){var n=v(e,t);return"document.documentElement.scrollTop"===t&&0===n&&(n=v(e,"document.body.scrollTop")),n}))})},queryAttributes:function(e,t){return Promise.resolve({attributes:t.map((function(t){return String(e.getAttribute(t))}))})},queryStyles:function(e,t){var n=getComputedStyle(e);return Promise.resolve({styles:t.map((function(e){return n[e]}))})},queryHTML:function(e,t){return Promise.resolve({html:(n="outer"===t?e.outerHTML:e.innerHTML,n.replace(/\n/g,"").replace(/(]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}})}require("address"),require("default-gateway"),require("licia/isStr"),require("licia/getPort");const l=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];require("qrcode-terminal"),require("qrcode-reader");const h=/^win/.test(process.platform),u=s("automator:launcher"),p=o.promisify(e.readdir),d=o.promisify(e.stat);class m{constructor(t){this.id=t.id,this.app=t.executablePath,this.appid=t.appid||"HBuilder",this.package=t.package||"io.dcloud.HBuilder"}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then(()=>(u(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1)).catch(()=>(u(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0))}push(t){return async function t(e){const s=await p(e);return(await Promise.all(s.map(async s=>{const i=n.resolve(e,s);return(await d(i)).isDirectory()?t(i):i}))).reduce((t,e)=>t.concat(e),[])}(t).then(e=>{const s=e.map(e=>{const s=(t=>h?t.replace(/\\/g,"/"):t)(n.join(this.DIR_WWW,n.relative(t,e)));return u(`${a("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 y=s("automator:simctl");class f extends m{async init(){const t=require("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),y(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=(await this.tool.appInfo(this.package)).match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.sdcard?"9.6.96":"")}async install(){return y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.initSDCard(),Promise.resolve(!0)}async start(){try{await this.tool.terminateApp(this.package),await this.tool.launchApp(this.package)}catch(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 r.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(t+" not exists"))}pushFile(t,e){return Promise.resolve(r.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const w=require("adbkit"),g=s("automator:adb");class M extends m{async init(){if(this.tool=w.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(),g(`${a("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]:""})}install(){return g(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),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 g(`${a("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(w.util.readAll).then(t=>{const e=t.toString();return g(`${a("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e})}get DIR_WWW(){return`${this.sdcard}/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}/io.dcloud.PandoraEntry --es ${this.appid} --ez needUpdateApp false --ez reload true`}}const E=s("automator:devtool");let P,A=!1;const $={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>P.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(t,e)=>{const s=await P.captureScreenshot(e);return E("App.captureScreenshot "+s.length),{data:s}}}};!function(t){l.forEach(e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=i(c).processSync(t.selector)),t)}}(e)})}($);const S={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,s){if(t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),P=function(t,e){return"ios"===t?new f(e):new M(e)}(t.platform,t),await P.init(),!await P.version()){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!e.existsSync(t.executablePath))throw Error(t.executablePath+" not exists");A=!0}return t},create:async function(t,e,s){A&&await P.install(),(s.compiled||await P.shouldPush())&&await P.push(t),await P.start()}},adapter:$};module.exports=S; +"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),s=t(require("debug")),i=t(require("postcss-selector-parser")),r=t(require("fs-extra")),a=t(require("licia/dateFormat")),n=require("path"),o=require("util");function l(t){t.walk(t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}})}require("address"),require("default-gateway"),require("licia/isStr"),require("licia/getPort");const c=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];require("qrcode-terminal"),require("qrcode-reader");const h=/^win/.test(process.platform),p=s("automator:launcher"),u=o.promisify(e.readdir),d=o.promisify(e.stat);class m{constructor(t){this.id=t.id,this.app=t.executablePath,this.appid=t.appid||"HBuilder",this.package=t.package||"io.dcloud.HBuilder"}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then(()=>(p(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1)).catch(()=>(p(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0))}push(t){return async function t(e){const s=await u(e);return(await Promise.all(s.map(async s=>{const i=n.resolve(e,s);return(await d(i)).isDirectory()?t(i):i}))).reduce((t,e)=>t.concat(e),[])}(t).then(e=>{const s=e.map(e=>{const s=(t=>h?t.replace(/\\/g,"/"):t)(n.join(this.DIR_WWW,n.relative(t,e)));return p(`${a("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 y=s("automator:simctl");class f extends m{async init(){const t=require("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),y(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=(await this.tool.appInfo(this.package)).match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.sdcard?"9.6.96":"")}async install(){return y(`${a("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),await this.tool.launchApp(this.package)}catch(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 r.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(t+" not exists"))}pushFile(t,e){return Promise.resolve(r.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const g=require("adbkit"),w=s("automator:adb");class M extends m{async init(){if(this.tool=g.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(),w(`${a("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]:""})}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(w(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${t}`),t){const t=require("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 "),w(`${a("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 w(`${a("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(g.util.readAll).then(t=>{const e=t.toString();return w(`${a("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e})}get DIR_WWW(){return`${this.sdcard}/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}/io.dcloud.PandoraEntry --es ${this.appid} --ez needUpdateApp false --ez reload true`}}const P=s("automator:devtool");let E,$=!1;const A={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>E.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(t,e)=>{const s=await E.captureScreenshot(e);return P("App.captureScreenshot "+s.length),{data:s}}}};!function(t){c.forEach(e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=i(l).processSync(t.selector)),t)}}(e)})}(A);const v={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,s){if(t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),E=function(t,e){return"ios"===t?new f(e):new M(e)}(t.platform,t),await E.init(),!await E.version()){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!e.existsSync(t.executablePath))throw Error(t.executablePath+" not exists");$=!0}return t},create:async function(t,e,s){$&&await E.install(),(s.compiled||await E.shouldPush())&&await E.push(t),await E.start()}},adapter:A};module.exports=v; diff --git a/packages/uni-automator/dist/environment.js b/packages/uni-automator/dist/environment.js index 24118d0e0..add7ea443 100644 --- a/packages/uni-automator/dist/environment.js +++ b/packages/uni-automator/dist/environment.js @@ -1 +1 @@ -"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("jest-environment-node"));const s=new(t(require("./index.js")));module.exports=class extends e{constructor(t,e){super(t),process.env.UNI_AUTOMATOR_CONFIG?this.launchOptions=require(process.env.UNI_AUTOMATOR_CONFIG):this.launchOptions=t.testEnvironmentOptions}async setup(){await super.setup();const t=global;t.program||(this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,t.program=await s.launch(this.launchOptions),this.launchOptions.devtools&&this.launchOptions.devtools.remote&&await t.program.remote(!0)),this.global.program=t.program}async teardown(){await super.teardown()}}; +"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("jest-environment-node"));const s=new(t(require("./index.js")));module.exports=class extends e{constructor(t,e){super(t),process.env.UNI_AUTOMATOR_CONFIG?this.launchOptions=require(process.env.UNI_AUTOMATOR_CONFIG):this.launchOptions=t.testEnvironmentOptions}async setup(){await super.setup();const t=global;if(t.__init__){if(!t.program)throw Error("Program init failed")}else t.__init__=!0,this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,t.program=await s.launch(this.launchOptions),this.launchOptions.devtools&&this.launchOptions.devtools.remote&&await t.program.remote(!0);this.global.program=t.program}async teardown(){await super.teardown()}}; diff --git a/packages/uni-automator/dist/index.js b/packages/uni-automator/dist/index.js index b59733692..38db56433 100644 --- a/packages/uni-automator/dist/index.js +++ b/packages/uni-automator/dist/index.js @@ -1,4 +1,4 @@ -"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),n=t(require("path")),s=t(require("debug")),i=t(require("licia/isRelative")),o=t(require("ws")),r=require("events"),a=t(require("licia/uuid")),c=t(require("licia/stringify")),p=t(require("licia/dateFormat")),l=t(require("licia/waitUntil")),u=t(require("licia/fs")),h=t(require("licia/isFn")),d=t(require("licia/trim")),m=t(require("licia/isStr")),g=t(require("licia/startWith")),y=t(require("licia/isNum")),v=t(require("licia/sleep")),w=t(require("licia/isUndef")),f=t(require("address")),P=t(require("default-gateway")),M=t(require("licia/getPort")),k=require("child_process"),E=t(require("licia/toStr"));class b extends r.EventEmitter{constructor(t){super(),this.ws=t,this.ws.addEventListener("message",t=>{this.emit("message",t.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(t){this.ws.send(t)}close(){this.ws.close()}}class I extends r.EventEmitter{constructor(t,e,n){super(),this.puppet=e,this.namespace=n,this.callbacks=new Map,this.transport=t,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=t=>{this.debug(`${p("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${t}`);const{id:e,method:n,error:s,result:i,params:o}=JSON.parse(t);if(!e)return this.puppet.emit(n,o);const{callbacks:r}=this;if(e&&r.has(e)){const t=r.get(e);r.delete(e),s?t.reject(Error(s.message)):t.resolve(i)}},this.onClose=()=>{this.callbacks.forEach(t=>{t.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(t,e={},n=!0){if(n&&this.puppet.adapter.has(t))return this.puppet.adapter.send(this,t,e);const s=a(),i=c({id:s,method:t,params:e});return this.debug(`${p("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${i}`),new Promise((t,e)=>{try{this.transport.send(i)}catch(t){e(Error("Connection closed"))}this.callbacks.set(s,{resolve:t,reject:e})})}dispose(){this.transport.close()}static createDevtoolConnection(t,e){return new Promise((n,s)=>{const i=new o(t);i.addEventListener("open",()=>{n(new I(new b(i),e,"devtool"))}),i.addEventListener("error",s)})}static createRuntimeConnection(t,e,n){return new Promise((i,r)=>{s("automator:runtime")(`${p("yyyy-mm-dd HH:MM:ss:l")} port=${t}`);const a=new o.Server({port:t});l(async()=>{if(e.runtimeConnection)return!0},n,1e3).catch(t=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(t){s("automator:runtime")(p("yyyy-mm-dd HH:MM:ss:l")+" connected");const n=new I(new b(t),e,"runtime");e.setRuntimeConnection(n),i(n)})),e.setRuntimeServer(a)})}}const C=require("qrcode-terminal");require("qrcode-reader"),/^win/.test(process.platform);async function T(t,e){const[n,s]=function(t){return m(t)?[!0,[t]]:[!1,t]}(e),i=await t(s);return n?i[0]:i} +"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),n=t(require("path")),s=t(require("debug")),i=t(require("licia/isRelative")),o=t(require("ws")),r=require("events"),a=t(require("licia/uuid")),c=t(require("licia/stringify")),p=t(require("licia/dateFormat")),l=t(require("licia/waitUntil")),u=t(require("licia/fs")),h=t(require("licia/isFn")),d=t(require("licia/trim")),m=t(require("licia/isStr")),g=t(require("licia/startWith")),y=t(require("licia/isNum")),v=t(require("licia/sleep")),w=t(require("licia/isUndef")),f=t(require("address")),P=t(require("default-gateway")),M=t(require("licia/getPort")),k=require("child_process"),E=t(require("licia/toStr"));class b extends r.EventEmitter{constructor(t){super(),this.ws=t,this.ws.addEventListener("message",t=>{this.emit("message",t.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(t){this.ws.send(t)}close(){this.ws.close()}}class I extends r.EventEmitter{constructor(t,e,n){super(),this.puppet=e,this.namespace=n,this.callbacks=new Map,this.transport=t,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=t=>{this.debug(`${p("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${t}`);const{id:e,method:n,error:s,result:i,params:o}=JSON.parse(t);if(!e)return this.puppet.emit(n,o);const{callbacks:r}=this;if(e&&r.has(e)){const t=r.get(e);r.delete(e),s?t.reject(Error(s.message)):t.resolve(i)}},this.onClose=()=>{this.callbacks.forEach(t=>{t.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(t,e={},n=!0){if(n&&this.puppet.adapter.has(t))return this.puppet.adapter.send(this,t,e);const s=a(),i=c({id:s,method:t,params:e});return this.debug(`${p("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${i}`),new Promise((t,e)=>{try{this.transport.send(i)}catch(t){e(Error("Connection closed"))}this.callbacks.set(s,{resolve:t,reject:e})})}dispose(){this.transport.close()}static createDevtoolConnection(t,e){return new Promise((n,s)=>{const i=new o(t);i.addEventListener("open",()=>{n(new I(new b(i),e,"devtool"))}),i.addEventListener("error",s)})}static createRuntimeConnection(t,e,n){return new Promise((i,r)=>{s("automator:runtime")(`${p("yyyy-mm-dd HH:MM:ss:l")} port=${t}`);const a=new o.Server({port:t});l(async()=>{if(e.runtimeConnection)return!0},n,1e3).catch(()=>{a.close(),r("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(t){s("automator:runtime")(p("yyyy-mm-dd HH:MM:ss:l")+" connected");const n=new I(new b(t),e,"runtime");e.setRuntimeConnection(n),i(n)})),e.setRuntimeServer(a)})}}const C=require("qrcode-terminal");require("qrcode-reader"),/^win/.test(process.platform);async function T(t,e){const[n,s]=function(t){return m(t)?[!0,[t]]:[!1,t]}(e),i=await t(s);return n?i[0]:i} /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use @@ -13,4 +13,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -function D(t,e,n,s){var i,o=arguments.length,r=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}var j;function A(t,e){const n=e.value;return e.value=async function(e){return(await(null==n?void 0:n.call(this,e)))(t)},e}function R(t,e,n){return A(j.RUNTIME,n)}function S(t,e,n){return A(j.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(j||(j={}));class q{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===j.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(t,e):this.puppet.runtimeConnection.send(t,e)}on(t,e){this.puppet.on(t,e)}}class x extends q{constructor(t,e){super(t),this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId,this.videoId=e.videoId}async getData(t){return this.invokeMethod("Element.getData",t)}async setData(t){return this.invokeMethod("Element.setData",t)}async callMethod(t){return this.invokeMethod("Element.callMethod",t)}async getElement(t){return this.invokeMethod("Element.getElement",t)}async getElements(t){return this.invokeMethod("Element.getElements",t)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(t){return this.invokeMethod("Element.getHTML",t)}async getAttributes(t){return this.invokeMethod("Element.getAttributes",t)}async getStyles(t){return this.invokeMethod("Element.getStyles",t)}async getDOMProperties(t){return this.invokeMethod("Element.getDOMProperties",t)}async getProperties(t){return this.invokeMethod("Element.getProperties",t)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(t){return this.invokeMethod("Element.touchstart",t)}async touchmove(t){return this.invokeMethod("Element.touchmove",t)}async touchend(t){return this.invokeMethod("Element.touchend",t)}async triggerEvent(t){return this.invokeMethod("Element.triggerEvent",t)}async callFunction(t){return this.invokeMethod("Element.callFunction",t)}async callContextMethod(t){return this.invokeMethod("Element.callContextMethod",t)}invokeMethod(t,e={}){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.invoke(t,e)}}D([R],x.prototype,"getData",null),D([R],x.prototype,"setData",null),D([R],x.prototype,"callMethod",null),D([S],x.prototype,"getElement",null),D([S],x.prototype,"getElements",null),D([S],x.prototype,"getOffset",null),D([S],x.prototype,"getHTML",null),D([S],x.prototype,"getAttributes",null),D([S],x.prototype,"getStyles",null),D([S],x.prototype,"getDOMProperties",null),D([S],x.prototype,"getProperties",null),D([S],x.prototype,"tap",null),D([S],x.prototype,"longpress",null),D([S],x.prototype,"touchstart",null),D([S],x.prototype,"touchmove",null),D([S],x.prototype,"touchend",null),D([S],x.prototype,"triggerEvent",null),D([S],x.prototype,"callFunction",null),D([S],x.prototype,"callContextMethod",null);const N=require("util");class O{constructor(t,e,n){this.puppet=t,this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId||null,this.videoId=e.videoId||null,this.tagName=e.tagName,this.nvue=e.nvue,this.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new x(t,e)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[N.inspect.custom](){return this.toJSON()}async $(t){try{const e=await this.api.getElement({selector:t});return O.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map(t=>O.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap))}async size(){const[t,e]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:t,height:e}}async offset(){return this.api.getOffset()}async text(){return this.domProperty("innerText")}async attribute(t){if(!m(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.property("value")}async property(t){if(!m(t))throw Error("name must be a string");if(this.puppet.checkProperty){let e=this.publicProps;if(e||(this.publicProps=e=await this._property("__propPublic")),!e[t])throw Error(`${this.tagName}.${t} not exists`)}return this._property(t)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(t){if(!m(t))throw Error("name must be a string");return(await this.api.getStyles({names:[t]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue?this.api.longpress():(await this.touchstart(),await v(350),this.touchend())}async trigger(t,e){const n={type:t};return w(e)||(n.detail=e),this.api.triggerEvent(n)}async touchstart(t){return this.api.touchstart(t)}async touchmove(t){return this.api.touchmove(t)}async touchend(t){return this.api.touchend(t)}async domProperty(t){return T(async t=>(await this.api.getDOMProperties({names:t})).properties,t)}_property(t){return T(async t=>(await this.api.getProperties({names:t})).properties,t)}send(t,e){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.puppet.send(t,e)}async callFunction(t,...e){return(await this.api.callFunction({functionName:t,args:e})).result}static create(t,e,n){let s,i=n.get(e.elementId);if(i)return i;if(e.nodeId)s=U;else switch(e.tagName){case"input":s=$;break;case"textarea":s=_;break;case"scroll-view":s=F;break;case"swiper":s=L;break;case"movable-view":s=H;break;case"switch":s=B;break;case"slider":s=J;break;case"video":s=W;break;default:s=O}return i=new s(t,e,n),n.set(e.elementId,i),i}}class U extends O{async setData(t){return this.api.setData({data:t})}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class $ extends O{async input(t){return this.callFunction("input.input",t)}}class _ extends O{async input(t){return this.callFunction("textarea.input",t)}}class F extends O{async scrollTo(t,e){return this.callFunction("scroll-view.scrollTo",t,e)}async property(t){return"scrollTop"===t?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===t?this.callFunction("scroll-view.scrollLeft"):super.property(t)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class L extends O{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class H extends O{async moveTo(t,e){return this.callFunction("movable-view.moveTo",t,e)}async property(t){return"x"===t?this._property("_translateX"):"y"===t?this._property("_translateY"):super.property(t)}}class B extends O{async tap(){return this.callFunction("switch.tap")}}class J extends O{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class W extends O{async callContextMethod(t,...e){return this.api.callContextMethod({method:t,args:e})}}class V extends q{constructor(t,e){super(t),this.id=e.id}async getData(t){return this.invokeMethod("Page.getData",t)}async setData(t){return this.invokeMethod("Page.setData",t)}async callMethod(t){return this.invokeMethod("Page.callMethod",t)}async getElement(t){return this.invokeMethod("Page.getElement",t)}async getElements(t){return this.invokeMethod("Page.getElements",t)}async getWindowProperties(t){return this.invokeMethod("Page.getWindowProperties",t)}invokeMethod(t,e={}){return e.pageId=this.id,this.invoke(t,e)}}D([R],V.prototype,"getData",null),D([R],V.prototype,"setData",null),D([R],V.prototype,"callMethod",null),D([S],V.prototype,"getElement",null),D([S],V.prototype,"getElements",null),D([S],V.prototype,"getWindowProperties",null);const z=require("util");class G{constructor(t,e){this.puppet=t,this.id=e.id,this.path=e.path,this.query=e.query,this.elementMap=new Map,this.api=new V(t,e)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[z.inspect.custom](){return this.toJSON()}async waitFor(t){return y(t)?await v(t):h(t)?l(t):m(t)?l(async()=>(await this.$$(t)).length>0):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return O.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map(e=>O.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap))}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async setData(t){return this.api.setData({data:t})}async size(){const[t,e]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:t,height:e}}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=m(t);e&&(t=[t]);const{properties:n}=await this.api.getWindowProperties({names:t});return e?n[0]:n}static create(t,e,n){let s=n.get(e.id);return s?(s.query=e.query,s):(s=new G(t,e),n.set(e.id,s),s)}}class X extends q{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(t){return this.invoke("App.callUniMethod",t)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(t){return this.invoke("App.mockUniMethod",t)}async callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",t)}async exit(){return this.invoke("App.exit")}async addBinding(t){return this.invoke("App.addBinding",t)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(t){return this.on("App.logAdded",t)}onBindingCalled(t){return this.on("App.bindingCalled",t)}onExceptionThrown(t){return this.on("App.exceptionThrown",t)}}D([R],X.prototype,"getPageStack",null),D([R],X.prototype,"callUniMethod",null),D([R],X.prototype,"getCurrentPage",null),D([R],X.prototype,"mockUniMethod",null),D([S],X.prototype,"callFunction",null),D([S],X.prototype,"captureScreenshot",null),D([S],X.prototype,"exit",null),D([S],X.prototype,"addBinding",null),D([S],X.prototype,"enableLog",null);class Y extends q{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(t){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(t){this.puppet.once("Tool.onRemoteDebugConnected",t),this.puppet.once("Tool.onPreviewConnected",t)}}function K(t){return new Promise(e=>setTimeout(e,t))}D([S],Y.prototype,"getInfo",null),D([S],Y.prototype,"enableRemoteDebug",null),D([S],Y.prototype,"close",null),D([S],Y.prototype,"getTestAccounts",null);class Q extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new X(t),this.toolApi=new Y(t),this.appApi.onLogAdded(t=>{this.emit("console",t)}),this.appApi.onBindingCalled(({name:t,args:e})=>{try{const n=this.appBindings.get(t);n&&n(...e)}catch(t){}}),this.appApi.onExceptionThrown(t=>{this.emit("exception",t)})}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map(t=>G.create(this.puppet,t,this.pageMap))}async navigateTo(t){return this.changeRoute("navigateTo",t)}async redirectTo(t){return this.changeRoute("redirectTo",t)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(t){return this.changeRoute("reLaunch",t)}async switchTab(t){return this.changeRoute("switchTab",t)}async currentPage(){const{id:t,path:e,query:n}=await this.appApi.getCurrentPage();return G.create(this.puppet,{id:t,path:e,query:n},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(t,...e){return(await this.appApi.callUniMethod({method:t,args:e})).result}async mockUniMethod(t,e,...n){return h(e)||m(s=e)&&(s=d(s),g(s,"function")||g(s,"() =>"))?this.appApi.mockUniMethod({method:t,functionDeclaration:e.toString(),args:n}):this.appApi.mockUniMethod({method:t,result:e});var s}async restoreUniMethod(t){return this.appApi.mockUniMethod({method:t})}async evaluate(t,...e){return(await this.appApi.callFunction({functionDeclaration:t.toString(),args:e})).result}async pageScrollTo(t){await this.callUniMethod("pageScrollTo",{scrollTop:t,duration:0})}async close(){try{await this.appApi.exit()}catch(t){}await K(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){return this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(t){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:e}=await this.toolApi.enableRemoteDebug({auto:t});var n;e&&await(n=e,new Promise(t=>{C.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await K(1e3),t()})}),i=new Promise(t=>{this.puppet.setRemoteRuntimeConnectionCallback(()=>{t()})});return Promise.all([s,i])}disconnect(){this.puppet.dispose()}on(t,e){return"console"===t&&this.appApi.enableLog(),super.on(t,e),this}async exposeFunction(t,e){if(this.appBindings.has(t))throw Error(`Failed to expose function with name ${t}: already exists!`);this.appBindings.set(t,e),await this.appApi.addBinding({name:t})}async checkVersion(){}async screenshot(t){const{data:e}=await this.appApi.captureScreenshot({fullPage:null==t?void 0:t.fullPage});if(!(null==t?void 0:t.path))return e;await u.writeFile(t.path,e,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){return await this.callUniMethod(t,{url:e}),await K(3e3),this.currentPage()}}class Z{constructor(t){this.options=t}has(t){return!!this.options[t]}send(t,e,n){const s=this.options[e];if(!s)return Promise.reject(Error(`adapter for ${e} not found`));const i=s.reflect;return i?(s.params&&(n=s.params(n)),"function"==typeof i?i(t.send.bind(t),n):(e=i,t.send(e,n))):Promise.reject(Error(e+"'s reflect is required"))}}const tt=s("automator:puppet");function et(t){try{return require(t)}catch(t){}}function nt(t,e,s,i){const o=function(t,e,s){let i,o;return process.env.UNI_OUTPUT_DIR?(o=n.join(process.env.UNI_OUTPUT_DIR,"../.automator/"+e,".automator.json"),i=et(o)):(o=n.join(t,`dist/${s}/.automator/${e}`,".automator.json"),i=et(o),i||(o=n.join(t,`unpackage/dist/${s}/.automator/${e}`,".automator.json"),i=et(o))),tt(`${o}=>${JSON.stringify(i)}`),i}(t,s,i);if(!o||!o.wsEndpoint)return!1;const r=require("../package.json").version;if(o.version!==r)return tt(`unmet=>${o.version}!==${r}`),!1;const a=function(t){let e;try{const t=P.v4.sync();e=f.ip(t&&t.interface),e&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(e)||(e=void 0))}catch(t){}return"ws://"+(e||"localhost")+":"+t}(e);return tt("wsEndpoint=>"+a),o.wsEndpoint===a}class st extends r.EventEmitter{constructor(t,e){if(super(),this.target=e||("h5"===t?require("@dcloudio/uni-h5/lib/h5/uni.automator.js"):require(`@dcloudio/uni-${t}/lib/uni.automator.js`)),!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new Z(this.target.adapter||{})}setCompiler(t){this.compiler=t}setRuntimeServer(t){this.wss=t}setRemoteRuntimeConnectionCallback(t){this.remoteRuntimeConnectionCallback=t}setRuntimeConnection(t){this.runtimeConnection=t,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(t){this.devtoolConnection=t}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const s=this.target.devtools.required;return!s||!s.find(s=>!e.existsSync(n.join(t,s)))}validateDevtools(t){const e=this.target.devtools.validate;return e?e(t,this):Promise.resolve(t)}createDevtools(t,e,n){const s=this.target.devtools.create;return s?(e.timeout=n,s(t,e,this)):Promise.resolve()}shouldCompile(t,e,n,s){this.compiled=!0;const i=this.target.shouldCompile;return i?this.compiled=i(n,s):!0===n.compile?this.compiled=!0:this.compiled=!nt(t,e,this.platform,this.mode),this.compiled}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const t=this.target.mode;return t||("production"===process.env.NODE_ENV?"build":"dev")}}const it=s("automator:compiler"),ot=/The\s+(.*)\s+directory is ready/;class rt{constructor(t){this.puppet=t,this.puppet.setCompiler(this)}compile(t){const e=this.puppet.mode,s=this.puppet.platform;let i=t.silent;const o=t.port,r=t.host,a=`${e}:${s}`,c=t.projectPath,[p,l]=this.getSpawnArgs(t,a);l.push("--auto-port"),l.push(E(o)),r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===e?"production":"development"})};return new Promise((t,o)=>{const r=o=>{const r=o.toString().trim();if(!i&&console.log(r),r.includes("- Network")){const e=r.match(/Network:(.*)/)[1].trim();it("url: "+e),t({path:e})}else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(ot);a&&a.length>1&&(o=a[1]),i=!0,this.stop(),t({path:n.join(c,o)})}};it(`${p} ${l.join(" ")} %o`,u),this.cliProcess=k.spawn(p,l,u),this.cliProcess.on("error",t=>{o(t)}),this.cliProcess.stdout.on("data",r),this.cliProcess.stderr.on("data",r)})}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(t,e){let s;const i=t.cliPath;try{s=require(n.join(i,"package.json"))}catch(t){}return s&&s.scripts&&s.scripts[e]?[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",e,"--"]]:(process.env.UNI_INPUT_DIR=t.projectPath,process.env.UNI_OUTPUT_DIR=n.join(t.projectPath,`unpackage/dist/${this.puppet.mode}/${this.puppet.platform}`),[process.env.UNI_NODE_PATH||"node",[n.join(i,"bin/uniapp-cli.js")]])}}class at{async launch(t){let e=t[t.platform]||{};this.puppet=new st(t.platform,e.puppet);const{port:i,cliPath:o,timeout:r,projectPath:a}=await this.validate(t);e=await this.puppet.validateDevtools(e);let c=this.puppet.shouldCompile(a,i,t,e),p=process.env.UNI_OUTPUT_DIR||a;if(c||this.puppet.validateProject(p)||(p=n.join(a,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(p)||(p=n.join(a,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(p)||(c=!0))),c){this.puppet.compiled=t.compile=!0,this.compiler=new rt(this.puppet);const e=await this.compiler.compile({host:t.host,port:i,cliPath:o,projectPath:a,silent:!!t.silent});e.path&&(p=e.path)}const l=[];return l.push(this.createRuntimeConnection(i,r)),l.push(this.puppet.createDevtools(p,e,r)),new Promise((t,n)=>{Promise.all(l).then(([n,i])=>{n&&this.puppet.setRuntimeConnection(n),i&&this.puppet.setDevtoolConnection(i),s("automator:program")("ready");const o=e.teardown||"disconnect";t(new Q(this.puppet,{teardown:o}))}).catch(t=>n(t))})}resolveCliPath(t){if(!t)return t;try{const e=require(n.join(t,"package.json"));if(e.dependencies&&e.dependencies["@dcloudio/vue-cli-plugin-uni"]||e.devDependencies&&e.devDependencies["@dcloudio/vue-cli-plugin-uni"])return t}catch(t){}}resolveProjectPath(t,s){return t||(t=process.env.UNI_INPUT_DIR||process.cwd()),i(t)&&(t=n.resolve(t)),e.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=process.env.UNI_CLI_PATH||t.cliPath;if(n=this.resolveCliPath(n||""),!n&&(n=this.resolveCliPath(process.cwd())),!n&&(n=this.resolveCliPath(e)),!n)throw Error("cliPath is not provided");return{port:await async function(t,e){const n=await M(t||e);if(t&&n!==t)throw Error(`Port ${t} is in use, please specify another port`);return n}(t.port||9520),cliPath:n,timeout:t.timeout||1e5,projectPath:e}}async createRuntimeConnection(t,e){return I.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new at}async launch(t){return this.launcher.launch(t)}}; +function D(t,e,n,s){var i,o=arguments.length,r=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,s);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}var j;function A(t,e){const n=e.value;return e.value=async function(e){return(await(null==n?void 0:n.call(this,e)))(t)},e}function R(t,e,n){return A(j.RUNTIME,n)}function q(t,e,n){return A(j.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(j||(j={}));class S{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===j.DEVTOOL?this.puppet.devtoolConnection:this.puppet.runtimeConnection).send(t,e):this.puppet.runtimeConnection.send(t,e)}on(t,e){this.puppet.on(t,e)}}class x extends S{constructor(t,e){super(t),this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId,this.videoId=e.videoId}async getData(t){return this.invokeMethod("Element.getData",t)}async setData(t){return this.invokeMethod("Element.setData",t)}async callMethod(t){return this.invokeMethod("Element.callMethod",t)}async getElement(t){return this.invokeMethod("Element.getElement",t)}async getElements(t){return this.invokeMethod("Element.getElements",t)}async getOffset(){return this.invokeMethod("Element.getOffset")}async getHTML(t){return this.invokeMethod("Element.getHTML",t)}async getAttributes(t){return this.invokeMethod("Element.getAttributes",t)}async getStyles(t){return this.invokeMethod("Element.getStyles",t)}async getDOMProperties(t){return this.invokeMethod("Element.getDOMProperties",t)}async getProperties(t){return this.invokeMethod("Element.getProperties",t)}async tap(){return this.invokeMethod("Element.tap")}async longpress(){return this.invokeMethod("Element.longpress")}async touchstart(t){return this.invokeMethod("Element.touchstart",t)}async touchmove(t){return this.invokeMethod("Element.touchmove",t)}async touchend(t){return this.invokeMethod("Element.touchend",t)}async triggerEvent(t){return this.invokeMethod("Element.triggerEvent",t)}async callFunction(t){return this.invokeMethod("Element.callFunction",t)}async callContextMethod(t){return this.invokeMethod("Element.callContextMethod",t)}invokeMethod(t,e={}){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.invoke(t,e)}}D([R],x.prototype,"getData",null),D([R],x.prototype,"setData",null),D([R],x.prototype,"callMethod",null),D([q],x.prototype,"getElement",null),D([q],x.prototype,"getElements",null),D([q],x.prototype,"getOffset",null),D([q],x.prototype,"getHTML",null),D([q],x.prototype,"getAttributes",null),D([q],x.prototype,"getStyles",null),D([q],x.prototype,"getDOMProperties",null),D([q],x.prototype,"getProperties",null),D([q],x.prototype,"tap",null),D([q],x.prototype,"longpress",null),D([q],x.prototype,"touchstart",null),D([q],x.prototype,"touchmove",null),D([q],x.prototype,"touchend",null),D([q],x.prototype,"triggerEvent",null),D([q],x.prototype,"callFunction",null),D([q],x.prototype,"callContextMethod",null);const N=require("util");class O{constructor(t,e,n){this.puppet=t,this.id=e.elementId,this.pageId=e.pageId,this.nodeId=e.nodeId||null,this.videoId=e.videoId||null,this.tagName=e.tagName,this.nvue=e.nvue,this.elementMap=n,"body"!==this.tagName&&"page-body"!==this.tagName||(this.tagName="page"),this.api=new x(t,e)}toJSON(){return JSON.stringify({id:this.id,tagName:this.tagName,pageId:this.pageId,nodeId:this.nodeId,videoId:this.videoId})}toString(){return this.toJSON()}[N.inspect.custom](){return this.toJSON()}async $(t){try{const e=await this.api.getElement({selector:t});return O.create(this.puppet,Object.assign({},e,{pageId:this.pageId}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map(t=>O.create(this.puppet,Object.assign({},t,{pageId:this.pageId}),this.elementMap))}async size(){const[t,e]=await this.domProperty(["offsetWidth","offsetHeight"]);return{width:t,height:e}}async offset(){return this.api.getOffset()}async text(){return this.domProperty("innerText")}async attribute(t){if(!m(t))throw Error("name must be a string");return(await this.api.getAttributes({names:[t]})).attributes[0]}async value(){return this.property("value")}async property(t){if(!m(t))throw Error("name must be a string");if(this.puppet.checkProperty){let e=this.publicProps;if(e||(this.publicProps=e=await this._property("__propPublic")),!e[t])throw Error(`${this.tagName}.${t} not exists`)}return this._property(t)}async html(){return(await this.api.getHTML({type:"inner"})).html}async outerHtml(){return(await this.api.getHTML({type:"outer"})).html}async style(t){if(!m(t))throw Error("name must be a string");return(await this.api.getStyles({names:[t]})).styles[0]}async tap(){return this.api.tap()}async longpress(){return this.nvue?this.api.longpress():(await this.touchstart(),await v(350),this.touchend())}async trigger(t,e){const n={type:t};return w(e)||(n.detail=e),this.api.triggerEvent(n)}async touchstart(t){return this.api.touchstart(t)}async touchmove(t){return this.api.touchmove(t)}async touchend(t){return this.api.touchend(t)}async domProperty(t){return T(async t=>(await this.api.getDOMProperties({names:t})).properties,t)}_property(t){return T(async t=>(await this.api.getProperties({names:t})).properties,t)}send(t,e){return e.elementId=this.id,e.pageId=this.pageId,this.nodeId&&(e.nodeId=this.nodeId),this.videoId&&(e.videoId=this.videoId),this.puppet.send(t,e)}async callFunction(t,...e){return(await this.api.callFunction({functionName:t,args:e})).result}static create(t,e,n){let s,i=n.get(e.elementId);if(i)return i;if(e.nodeId)s=U;else switch(e.tagName){case"input":s=$;break;case"textarea":s=_;break;case"scroll-view":s=F;break;case"swiper":s=L;break;case"movable-view":s=H;break;case"switch":s=B;break;case"slider":s=J;break;case"video":s=W;break;default:s=O}return i=new s(t,e,n),n.set(e.elementId,i),i}}class U extends O{async setData(t){return this.api.setData({data:t})}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}}class $ extends O{async input(t){return this.callFunction("input.input",t)}}class _ extends O{async input(t){return this.callFunction("textarea.input",t)}}class F extends O{async scrollTo(t,e){return this.callFunction("scroll-view.scrollTo",t,e)}async property(t){return"scrollTop"===t?this.callFunction("scroll-view.scrollTop"):"scrollLeft"===t?this.callFunction("scroll-view.scrollLeft"):super.property(t)}async scrollWidth(){return this.callFunction("scroll-view.scrollWidth")}async scrollHeight(){return this.callFunction("scroll-view.scrollHeight")}}class L extends O{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class H extends O{async moveTo(t,e){return this.callFunction("movable-view.moveTo",t,e)}async property(t){return"x"===t?this._property("_translateX"):"y"===t?this._property("_translateY"):super.property(t)}}class B extends O{async tap(){return this.callFunction("switch.tap")}}class J extends O{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class W extends O{async callContextMethod(t,...e){return this.api.callContextMethod({method:t,args:e})}}class V extends S{constructor(t,e){super(t),this.id=e.id}async getData(t){return this.invokeMethod("Page.getData",t)}async setData(t){return this.invokeMethod("Page.setData",t)}async callMethod(t){return this.invokeMethod("Page.callMethod",t)}async getElement(t){return this.invokeMethod("Page.getElement",t)}async getElements(t){return this.invokeMethod("Page.getElements",t)}async getWindowProperties(t){return this.invokeMethod("Page.getWindowProperties",t)}invokeMethod(t,e={}){return e.pageId=this.id,this.invoke(t,e)}}D([R],V.prototype,"getData",null),D([R],V.prototype,"setData",null),D([R],V.prototype,"callMethod",null),D([q],V.prototype,"getElement",null),D([q],V.prototype,"getElements",null),D([q],V.prototype,"getWindowProperties",null);const z=require("util");class G{constructor(t,e){this.puppet=t,this.id=e.id,this.path=e.path,this.query=e.query,this.elementMap=new Map,this.api=new V(t,e)}toJSON(){return JSON.stringify({id:this.id,path:this.path,query:this.query})}toString(){return this.toJSON()}[z.inspect.custom](){return this.toJSON()}async waitFor(t){return y(t)?await v(t):h(t)?l(t):m(t)?l(async()=>(await this.$$(t)).length>0):void 0}async $(t){try{const e=await this.api.getElement({selector:t});return O.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap)}catch(t){return null}}async $$(t){const{elements:e}=await this.api.getElements({selector:t});return e.map(e=>O.create(this.puppet,Object.assign({selector:t},e,{pageId:this.id}),this.elementMap))}async data(t){const e={};return t&&(e.path=t),(await this.api.getData(e)).data}async setData(t){return this.api.setData({data:t})}async size(){const[t,e]=await this.windowProperty(["document.documentElement.scrollWidth","document.documentElement.scrollHeight"]);return{width:t,height:e}}async callMethod(t,...e){return(await this.api.callMethod({method:t,args:e})).result}async scrollTop(){return this.windowProperty("document.documentElement.scrollTop")}async windowProperty(t){const e=m(t);e&&(t=[t]);const{properties:n}=await this.api.getWindowProperties({names:t});return e?n[0]:n}static create(t,e,n){let s=n.get(e.id);return s?(s.query=e.query,s):(s=new G(t,e),n.set(e.id,s),s)}}class X extends S{async getPageStack(){return this.invoke("App.getPageStack")}async callUniMethod(t){return this.invoke("App.callUniMethod",t)}async getCurrentPage(){return this.invoke("App.getCurrentPage")}async mockUniMethod(t){return this.invoke("App.mockUniMethod",t)}async callFunction(t){return this.invoke("App.callFunction",t)}async captureScreenshot(t){return this.invoke("App.captureScreenshot",t)}async exit(){return this.invoke("App.exit")}async addBinding(t){return this.invoke("App.addBinding",t)}async enableLog(){return this.invoke("App.enableLog")}onLogAdded(t){return this.on("App.logAdded",t)}onBindingCalled(t){return this.on("App.bindingCalled",t)}onExceptionThrown(t){return this.on("App.exceptionThrown",t)}}D([R],X.prototype,"getPageStack",null),D([R],X.prototype,"callUniMethod",null),D([R],X.prototype,"getCurrentPage",null),D([R],X.prototype,"mockUniMethod",null),D([q],X.prototype,"callFunction",null),D([q],X.prototype,"captureScreenshot",null),D([q],X.prototype,"exit",null),D([q],X.prototype,"addBinding",null),D([q],X.prototype,"enableLog",null);class Y extends S{async getInfo(){return this.invoke("Tool.getInfo")}async enableRemoteDebug(t){return this.invoke("Tool.enableRemoteDebug")}async close(){return this.invoke("Tool.close")}async getTestAccounts(){return this.invoke("Tool.getTestAccounts")}onRemoteDebugConnected(t){this.puppet.once("Tool.onRemoteDebugConnected",t),this.puppet.once("Tool.onPreviewConnected",t)}}function K(t){return new Promise(e=>setTimeout(e,t))}D([q],Y.prototype,"getInfo",null),D([q],Y.prototype,"enableRemoteDebug",null),D([q],Y.prototype,"close",null),D([q],Y.prototype,"getTestAccounts",null);class Q extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new X(t),this.toolApi=new Y(t),this.appApi.onLogAdded(t=>{this.emit("console",t)}),this.appApi.onBindingCalled(({name:t,args:e})=>{try{const n=this.appBindings.get(t);n&&n(...e)}catch(t){}}),this.appApi.onExceptionThrown(t=>{this.emit("exception",t)})}async pageStack(){return(await this.appApi.getPageStack()).pageStack.map(t=>G.create(this.puppet,t,this.pageMap))}async navigateTo(t){return this.changeRoute("navigateTo",t)}async redirectTo(t){return this.changeRoute("redirectTo",t)}async navigateBack(){return this.changeRoute("navigateBack")}async reLaunch(t){return this.changeRoute("reLaunch",t)}async switchTab(t){return this.changeRoute("switchTab",t)}async currentPage(){const{id:t,path:e,query:n}=await this.appApi.getCurrentPage();return G.create(this.puppet,{id:t,path:e,query:n},this.pageMap)}async systemInfo(){return this.callUniMethod("getSystemInfoSync")}async callUniMethod(t,...e){return(await this.appApi.callUniMethod({method:t,args:e})).result}async mockUniMethod(t,e,...n){return h(e)||m(s=e)&&(s=d(s),g(s,"function")||g(s,"() =>"))?this.appApi.mockUniMethod({method:t,functionDeclaration:e.toString(),args:n}):this.appApi.mockUniMethod({method:t,result:e});var s}async restoreUniMethod(t){return this.appApi.mockUniMethod({method:t})}async evaluate(t,...e){return(await this.appApi.callFunction({functionDeclaration:t.toString(),args:e})).result}async pageScrollTo(t){await this.callUniMethod("pageScrollTo",{scrollTop:t,duration:0})}async close(){try{await this.appApi.exit()}catch(t){}await K(1e3),this.puppet.disposeRuntimeServer(),await this.toolApi.close(),this.disconnect()}async teardown(){const t=require("kill-port");return await t(this.options.port),this["disconnect"===this.options.teardown?"disconnect":"close"]()}async remote(t){if(!this.puppet.devtools.remote)return console.warn(`Failed to enable remote, ${this.puppet.devtools.name} is unimplemented`);const{qrCode:e}=await this.toolApi.enableRemoteDebug({auto:t});var n;e&&await(n=e,new Promise(t=>{C.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await K(1e3),t()})}),i=new Promise(t=>{this.puppet.setRemoteRuntimeConnectionCallback(()=>{t()})});return Promise.all([s,i])}disconnect(){this.puppet.dispose()}on(t,e){return"console"===t&&this.appApi.enableLog(),super.on(t,e),this}async exposeFunction(t,e){if(this.appBindings.has(t))throw Error(`Failed to expose function with name ${t}: already exists!`);this.appBindings.set(t,e),await this.appApi.addBinding({name:t})}async checkVersion(){}async screenshot(t){const{data:e}=await this.appApi.captureScreenshot({fullPage:null==t?void 0:t.fullPage});if(!(null==t?void 0:t.path))return e;await u.writeFile(t.path,e,"base64")}async testAccounts(){return(await this.toolApi.getTestAccounts()).accounts}async changeRoute(t,e){return await this.callUniMethod(t,{url:e}),await K(3e3),this.currentPage()}}class Z{constructor(t){this.options=t}has(t){return!!this.options[t]}send(t,e,n){const s=this.options[e];if(!s)return Promise.reject(Error(`adapter for ${e} not found`));const i=s.reflect;return i?(s.params&&(n=s.params(n)),"function"==typeof i?i(t.send.bind(t),n):(e=i,t.send(e,n))):Promise.reject(Error(e+"'s reflect is required"))}}const tt=s("automator:puppet");function et(t){try{return require(t)}catch(t){}}function nt(t,e,s,i){const o=function(t,e,s){let i,o;return process.env.UNI_OUTPUT_DIR?(o=n.join(process.env.UNI_OUTPUT_DIR,"../.automator/"+e,".automator.json"),i=et(o)):(o=n.join(t,`dist/${s}/.automator/${e}`,".automator.json"),i=et(o),i||(o=n.join(t,`unpackage/dist/${s}/.automator/${e}`,".automator.json"),i=et(o))),tt(`${o}=>${JSON.stringify(i)}`),i}(t,s,i);if(!o||!o.wsEndpoint)return!1;const r=require("../package.json").version;if(o.version!==r)return tt(`unmet=>${o.version}!==${r}`),!1;const a=function(t){let e;try{const t=P.v4.sync();e=f.ip(t&&t.interface),e&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(e)||(e=void 0))}catch(t){}return"ws://"+(e||"localhost")+":"+t}(e);return tt("wsEndpoint=>"+a),o.wsEndpoint===a}class st extends r.EventEmitter{constructor(t,e){if(super(),this.target=e||("h5"===t?require("@dcloudio/uni-h5/lib/h5/uni.automator.js"):require(`@dcloudio/uni-${t}/lib/uni.automator.js`)),!this.target)throw Error("puppet is not provided");this.platform=t,this.adapter=new Z(this.target.adapter||{})}setCompiler(t){this.compiler=t}setRuntimeServer(t){this.wss=t}setRemoteRuntimeConnectionCallback(t){this.remoteRuntimeConnectionCallback=t}setRuntimeConnection(t){this.runtimeConnection=t,this.remoteRuntimeConnectionCallback&&(this.remoteRuntimeConnectionCallback(),this.remoteRuntimeConnectionCallback=null)}setDevtoolConnection(t){this.devtoolConnection=t}disposeRuntimeServer(){this.wss&&this.wss.close()}disposeRuntime(){this.runtimeConnection.dispose()}disposeDevtool(){this.compiler&&this.compiler.stop(),this.devtoolConnection&&this.devtoolConnection.dispose()}dispose(){this.disposeRuntime(),this.disposeDevtool(),this.disposeRuntimeServer()}send(t,e){return this.runtimeConnection.send(t,e)}validateProject(t){const s=this.target.devtools.required;return!s||!s.find(s=>!e.existsSync(n.join(t,s)))}validateDevtools(t){const e=this.target.devtools.validate;return e?e(t,this):Promise.resolve(t)}createDevtools(t,e,n){const s=this.target.devtools.create;return s?(e.timeout=n,s(t,e,this)):Promise.resolve()}shouldCompile(t,e,n,s){this.compiled=!0;const i=this.target.shouldCompile;return i?this.compiled=i(n,s):!0===n.compile?this.compiled=!0:this.compiled=!nt(t,e,this.platform,this.mode),this.compiled}get checkProperty(){return"mp-weixin"===this.platform}get devtools(){return this.target.devtools}get mode(){const t=this.target.mode;return t||("production"===process.env.NODE_ENV?"build":"dev")}}const it=s("automator:compiler"),ot=/The\s+(.*)\s+directory is ready/;class rt{constructor(t){this.puppet=t,this.puppet.setCompiler(this)}compile(t){const e=this.puppet.mode,s=this.puppet.platform;let i=t.silent;const o=t.port,r=t.host,a=`${e}:${s}`,c=t.projectPath,[p,l]=this.getSpawnArgs(t,a);l.push("--auto-port"),l.push(E(o)),r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath,env:Object.assign(Object.assign({},process.env),{NODE_ENV:"build"===e?"production":"development"})};return new Promise((t,o)=>{const r=o=>{const r=o.toString().trim();if(!i&&console.log(r),r.includes("- Network")){const e=r.match(/Network:(.*)/)[1].trim();it("url: "+e),t({path:e})}else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(ot);a&&a.length>1&&(o=a[1]),i=!0,this.stop(),t({path:n.join(c,o)})}};it(`${p} ${l.join(" ")} %o`,u),this.cliProcess=k.spawn(p,l,u),this.cliProcess.on("error",t=>{o(t)}),this.cliProcess.stdout.on("data",r),this.cliProcess.stderr.on("data",r)})}stop(){this.cliProcess&&this.cliProcess.kill("SIGTERM")}getSpawnArgs(t,e){let s;const i=t.cliPath;try{s=require(n.join(i,"package.json"))}catch(t){}return s&&s.scripts&&s.scripts[e]?[process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),["run",e,"--"]]:(process.env.UNI_INPUT_DIR=t.projectPath,process.env.UNI_OUTPUT_DIR=n.join(t.projectPath,`unpackage/dist/${this.puppet.mode}/${this.puppet.platform}`),[process.env.UNI_NODE_PATH||"node",[n.join(i,"bin/uniapp-cli.js")]])}}class at{async launch(t){let e=t[t.platform]||{};this.puppet=new st(t.platform,e.puppet);const{port:i,cliPath:o,timeout:r,projectPath:a}=await this.validate(t);e=await this.puppet.validateDevtools(e);let c=this.puppet.shouldCompile(a,i,t,e),p=process.env.UNI_OUTPUT_DIR||a;if(c||this.puppet.validateProject(p)||(p=n.join(a,"dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(p)||(p=n.join(a,"unpackage/dist/"+this.puppet.mode+"/"+this.puppet.platform),this.puppet.validateProject(p)||(c=!0))),c){this.puppet.compiled=t.compile=!0,this.compiler=new rt(this.puppet);const e=await this.compiler.compile({host:t.host,port:i,cliPath:o,projectPath:a,silent:!!t.silent});e.path&&(p=e.path)}const l=[];return l.push(this.createRuntimeConnection(i,r)),l.push(this.puppet.createDevtools(p,e,r)),new Promise((t,n)=>{Promise.all(l).then(([n,o])=>{n&&this.puppet.setRuntimeConnection(n),o&&this.puppet.setDevtoolConnection(o),s("automator:program")("ready");const r=e.teardown||"disconnect";t(new Q(this.puppet,{teardown:r,port:i}))}).catch(t=>n(t))})}resolveCliPath(t){if(!t)return t;try{const e=require(n.join(t,"package.json"));if(e.dependencies&&e.dependencies["@dcloudio/vue-cli-plugin-uni"]||e.devDependencies&&e.devDependencies["@dcloudio/vue-cli-plugin-uni"])return t}catch(t){}}resolveProjectPath(t,s){return t||(t=process.env.UNI_INPUT_DIR||process.cwd()),i(t)&&(t=n.resolve(t)),e.existsSync(t)||function(t){throw Error(t)}(`Project path ${t} doesn't exist`),t}async validate(t){const e=this.resolveProjectPath(t.projectPath,t);let n=process.env.UNI_CLI_PATH||t.cliPath;if(n=this.resolveCliPath(n||""),!n&&(n=this.resolveCliPath(process.cwd())),!n&&(n=this.resolveCliPath(e)),!n)throw Error("cliPath is not provided");return{port:await async function(t,e){const n=await M(t||e);if(t&&n!==t)throw Error(`Port ${t} is in use, please specify another port`);return n}(t.port||9520),cliPath:n,timeout:t.timeout||6e4,projectPath:e}}async createRuntimeConnection(t,e){return I.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new at}async launch(t){return this.launcher.launch(t)}}; diff --git a/packages/uni-automator/package.json b/packages/uni-automator/package.json index 8746cda79..b7e0c30b6 100644 --- a/packages/uni-automator/package.json +++ b/packages/uni-automator/package.json @@ -16,7 +16,8 @@ "dependencies": { "address": "^1.1.2", "debug": "^4.1.1", - "default-gateway": "^6.0.0", + "default-gateway": "^6.0.0", + "kill-port": "^1.6.0", "licia": "^1.21.0", "postcss-selector-parser": "^6.0.2", "qrcode-reader": "^1.0.4", diff --git a/packages/uni-h5/dist/automator.js b/packages/uni-h5/dist/automator.js index 47d0a50dd..6ea75e5e6 100644 --- a/packages/uni-h5/dist/automator.js +++ b/packages/uni-h5/dist/automator.js @@ -12,4 +12,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -function e(){for(var e=0,t=0,n=arguments.length;t]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1":""===e?"":0!==e.indexOf("e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},P=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},j=P(b.SELECTOR),q=P(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader"),/^win/.test(process.platform);class M 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){this.ws.send(e)}close(){this.ws.close()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={stdio:"ignore"};u&&(t.cwd=u);let r=p(h,[]);r=p(r,["--auto"]),r=p(r,[e,"--auto-port",c(s)]),d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.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 r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return r.compiled?s("automator:devtool")("Waiting for runtime automator"):(s("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:(r=t.selector,r.split(" ").map(e=>j(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"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:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("os")),r=e(require("path")),s=e(require("debug")),a=e(require("licia/isWindows")),n=e(require("fs")),o=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),p=e(require("licia/concat")),u=e(require("licia/getPort")),m=e(require("licia/dateFormat"));require("address"),require("default-gateway"),require("licia/isStr");var d=e(require("ws")),h=require("events"),f=e(require("licia/uuid")),g=e(require("licia/stringify"));const w=/(^[a-z][a-z0-9-]*)/i,y=/^navigator/i,E=/^swan-nav$/i;var b;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(b||(b={}));const v={[b.SELECTOR]:[{test:y,processor:e=>e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},P=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},j=P(b.SELECTOR),q=P(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader"),/^win/.test(process.platform);class M 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){this.ws.send(e)}close(){this.ws.close()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(()=>{o.close(),n("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={stdio:"ignore"};u&&(t.cwd=u);let r=p(h,[]);r=p(r,["--auto"]),r=p(r,[e,"--auto-port",c(s)]),d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.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 r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return r.compiled?s("automator:devtool")("Waiting for runtime automator"):(s("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:(r=t.selector,r.split(" ").map(e=>j(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"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:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T; diff --git a/packages/uni-mp-weixin/lib/uni.automator.js b/packages/uni-mp-weixin/lib/uni.automator.js index 1687ab27c..b402266d7 100644 --- a/packages/uni-mp-weixin/lib/uni.automator.js +++ b/packages/uni-mp-weixin/lib/uni.automator.js @@ -1 +1 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows"));require("address"),require("default-gateway"),require("licia/isStr");var o=e(require("licia/getPort")),n=e(require("fs")),s=e(require("child_process")),a=e(require("licia/sleep")),i=e(require("licia/toStr")),c=e(require("licia/waitUntil")),u=e(require("licia/concat")),l=e(require("licia/dateFormat")),d=e(require("ws")),p=require("events"),m=e(require("licia/uuid")),h=e(require("licia/stringify"));require("qrcode-terminal");const w=require("qrcode-reader");/^win/.test(process.platform);class f 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()}}class y extends p.EventEmitter{constructor(e,r,o){super(),this.puppet=r,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:o,result:n,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:a}=this;if(t&&a.has(t)){const e=a.get(t);a.delete(t),o?e.reject(Error(o.message)):e.resolve(n)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=m(),n=h({id:o,method:e,params:t});return this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise((e,t)=>{try{this.transport.send(n)}catch(e){t(Error("Connection closed"))}this.callbacks.set(o,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,o)=>{const n=new d(e);n.addEventListener("open",()=>{r(new y(new f(n),t,"devtool"))}),n.addEventListener("error",o)})}static createRuntimeConnection(e,r,o){return new Promise((n,s)=>{t("automator:runtime")(`${l("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new d.Server({port:e});c(async()=>{if(r.runtimeConnection)return!0},o,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(e){t("automator:runtime")(l("yyyy-mm-dd HH:MM:ss:l")+" connected");const o=new y(new f(e),r,"runtime");r.setRuntimeConnection(o),n(o)})),r.setRuntimeServer(a)})}}const g=t("automator:devtool");async function v(e,t,r){const{port:o,cliPath:n,timeout:d,cwd:p="",account:m="",args:h=[],launch:w=!0}=t;let f=!1,v=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=u(h,[]);r=u(r,["auto","--project"]),r=u(r,[e,"--auto-port",i(o)]),m&&(r=u(r,["--auto-account",m]));try{g("%s %o %o",n,r,t);const e=s.spawn(n,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{v=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{v=!0},15e3);const b=await c(async()=>{try{if(f||v)return!0;return await async function(e,t){let r;try{r=await y.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+o},r)}catch(e){}},d,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(v)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),g(l("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const b={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"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 r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.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 r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await o(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,r,o){const n=await v(e,r,o);return o.compiled?t("automator:devtool")("Waiting for runtime automator"):(t("automator:devtool")("initRuntimeAutomator"),n.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),n}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await require("jimp").read(t),n=new w;n.callback=function(t,o){if(t)return r(t);e(o.result)},n.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=b; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows"));require("address"),require("default-gateway"),require("licia/isStr");var o=e(require("licia/getPort")),n=e(require("fs")),s=e(require("child_process")),a=e(require("licia/sleep")),i=e(require("licia/toStr")),c=e(require("licia/waitUntil")),u=e(require("licia/concat")),l=e(require("licia/dateFormat")),d=e(require("ws")),p=require("events"),m=e(require("licia/uuid")),h=e(require("licia/stringify"));require("qrcode-terminal");const w=require("qrcode-reader");/^win/.test(process.platform);class f 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()}}class y extends p.EventEmitter{constructor(e,r,o){super(),this.puppet=r,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:o,result:n,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:a}=this;if(t&&a.has(t)){const e=a.get(t);a.delete(t),o?e.reject(Error(o.message)):e.resolve(n)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=m(),n=h({id:o,method:e,params:t});return this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise((e,t)=>{try{this.transport.send(n)}catch(e){t(Error("Connection closed"))}this.callbacks.set(o,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,o)=>{const n=new d(e);n.addEventListener("open",()=>{r(new y(new f(n),t,"devtool"))}),n.addEventListener("error",o)})}static createRuntimeConnection(e,r,o){return new Promise((n,s)=>{t("automator:runtime")(`${l("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new d.Server({port:e});c(async()=>{if(r.runtimeConnection)return!0},o,1e3).catch(()=>{a.close(),s("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(e){t("automator:runtime")(l("yyyy-mm-dd HH:MM:ss:l")+" connected");const o=new y(new f(e),r,"runtime");r.setRuntimeConnection(o),n(o)})),r.setRuntimeServer(a)})}}const g=t("automator:devtool");async function v(e,t,r){const{port:o,cliPath:n,timeout:d,cwd:p="",account:m="",args:h=[],launch:w=!0}=t;let f=!1,v=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=u(h,[]);r=u(r,["auto","--project"]),r=u(r,[e,"--auto-port",i(o)]),m&&(r=u(r,["--auto-account",m]));try{g("%s %o %o",n,r,t);const e=s.spawn(n,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{v=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{v=!0},15e3);const b=await c(async()=>{try{if(f||v)return!0;return await async function(e,t){let r;try{r=await y.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+o},r)}catch(e){}},d,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(v)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),g(l("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const b={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"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 r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.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 r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await o(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,r,o){const n=await v(e,r,o);return o.compiled?t("automator:devtool")("Waiting for runtime automator"):(t("automator:devtool")("initRuntimeAutomator"),n.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),n}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await require("jimp").read(t),n=new w;n.callback=function(t,o){if(t)return r(t);e(o.result)},n.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=b; -- GitLab