diff --git a/packages/uni-app-plus/dist/automator.js b/packages/uni-app-plus/dist/automator.js index ca323a845aba8ca8b902b4540657f1fe1c4c98a6..3c080a22a2527fb0f3c055b7f1ceaad4edd8d41b 100644 --- a/packages/uni-app-plus/dist/automator.js +++ b/packages/uni-app-plus/dist/automator.js @@ -1,4 +1,4 @@ -var e,t=Object.prototype.hasOwnProperty,n=Array.isArray,r=function(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}},o=/\B([A-Z])/g,u=r((function(e){return e.replace(o,"-$1").toLowerCase()})),i=/-(\w)/g,c=r((function(e){return e.replace(i,(function(e,t){return t?t.toUpperCase():""}))})),a=r((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),s=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function f(e,r){if(n(e))return e;if(r&&(o=r,u=e,t.call(o,u)))return[e];var o,u,i=[];return e.replace(s,(function(e,t,n,r){return i.push(n?r.replace(/\\(\\)?/g,"$1"):t||e),r})),i}function l(e,t){var n,r=f(t,e);for(n=r.shift();null!=n;){if(null==(e=e[n]))return;n=r.shift()}return e}function p(e){return e.__wxWebviewId__?e.__wxWebviewId__:e.privateProperties?e.privateProperties.slaveId:e.$page?e.$page.id:void 0}function g(e){return e.route||e.uri}function d(e){return e.options||e.$page&&e.$page.options||{}}function m(e){return{id:p(e),path:g(e),query:d(e)}}function v(e){var t=function(e){return getCurrentPages().find((function(t){return p(t)===e}))}(e);return t&&t.$vm}function _(e,t){var n=v(e);return n&&function e(t,n){var r;return t&&(!function(e,t){return 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}(e)===t}(t,n)?t.$children.find((function(t){return r=e(t,n)})):r=t),r}(n,t)}function h(e,t){var n;return e&&(n=t?l(e.$data,t):Object.assign({},e.$data)),Promise.resolve({data:n})}function E(e,t){return e&&Object.keys(t).forEach((function(n){e[n]=t[n]})),Promise.resolve()}function y(t,n,r){return new Promise((function(o,u){if(!t)return u(e.VM_NOT_EXISTS);if(!t[n])return u(e.VM_NOT_EXISTS);var i,c=t[n].apply(t,r);!(i=c)||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then?o({result:c}):c.then((function(e){o({result:e})}))}))}!function(e){e.VM_NOT_EXISTS="VM_NOT_EXISTS",e.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(e||(e={}));var w=/Sync$/;var T={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(e){return m(e)}))})},getCurrentPage:function(){var e=getCurrentPages(),t=e.length;return new Promise((function(n,r){t?n(m(e[t-1])):r(Error("getCurrentPages().length=0"))}))},callUniMethod:function(e){var t=e.method,n=e.args;return new Promise((function(e,r){if(!uni[t])return r(Error("uni."+t+" not exists"));if(function(e){return w.test(e)}(t))return e({result:uni[t].apply(uni,n)});var o=[Object.assign({},n[0]||{},{success:function(n){setTimeout((function(){e({result:n})}),"pageScrollTo"===t?350:0)},fail:function(e){r(Error(e.errMsg.replace(t+":fail ","")))}})];uni[t].apply(uni,o)}))}},S={getData:function(e){return h(v(e.pageId),e.path)},setData:function(e){return E(v(e.pageId),e.data)},callMethod:function(t){var n,r=((n={})[e.VM_NOT_EXISTS]="Page["+t.pageId+"] not exists",n[e.METHOD_NOT_EXISTS]="page."+t.method+" not exists",n);return new Promise((function(e,n){y(v(t.pageId),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(r[e]))}))}))}};function P(e){return e.nodeId||e.elementId}var $={getData:function(e){return h(_(e.pageId,P(e)),e.path)},setData:function(e){return E(_(e.pageId,P(e)),e.data)},callMethod:function(t){var n,r=P(t),o=((n={})[e.VM_NOT_EXISTS]="Component["+t.pageId+":"+r+"] not exists",n[e.METHOD_NOT_EXISTS]="component."+t.method+" not exists",n);return new Promise((function(e,n){y(_(t.pageId,r),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(o[e]))}))}))}}; +var e,t=Object.prototype.hasOwnProperty,n=function(e){return null==e},r=Array.isArray,o=function(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}},u=/\B([A-Z])/g,i=o((function(e){return e.replace(u,"-$1").toLowerCase()})),c=/-(\w)/g,a=o((function(e){return e.replace(c,(function(e,t){return t?t.toUpperCase():""}))})),s=o((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),f=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function l(e,n){if(r(e))return e;if(n&&(o=n,u=e,t.call(o,u)))return[e];var o,u,i=[];return e.replace(f,(function(e,t,n,r){return i.push(n?r.replace(/\\(\\)?/g,"$1"):t||e),r})),i}function d(e,t){var r,o=l(t,e);for(r=o.shift();!n(r);){if(null==(e=e[r]))return;r=o.shift()}return e}function g(e){return e.__wxWebviewId__?e.__wxWebviewId__:e.privateProperties?e.privateProperties.slaveId:e.$page?e.$page.id:void 0}function p(e){return e.route||e.uri}function m(e){return e.options||e.$page&&e.$page.options||{}}function v(e){return{id:g(e),path:p(e),query:m(e)}}function _(e){var t=function(e){return getCurrentPages().find((function(t){return g(t)===e}))}(e);return t&&t.$vm}function h(e,t){var n=_(e);return n&&function e(t,n){var r;return t&&(!function(e,t){return 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}(e)===t}(t,n)?t.$children.find((function(t){return r=e(t,n)})):r=t),r}(n,t)}function E(e,t){var n;return e&&(n=t?d(e.$data,t):Object.assign({},e.$data)),Promise.resolve({data:n})}function y(e,t){return e&&Object.keys(t).forEach((function(n){e[n]=t[n]})),Promise.resolve()}function w(t,n,r){return new Promise((function(o,u){if(!t)return u(e.VM_NOT_EXISTS);if(!t[n])return u(e.VM_NOT_EXISTS);var i,c=t[n].apply(t,r);!(i=c)||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then?o({result:c}):c.then((function(e){o({result:e})}))}))}!function(e){e.VM_NOT_EXISTS="VM_NOT_EXISTS",e.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(e||(e={}));var T=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],x={},P=/Sync$/,S=/^on|^off/;function O(e){return P.test(e)||-1!==T.indexOf(e)}var $={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(e){return v(e)}))})},getCurrentPage:function(){var e=getCurrentPages(),t=e.length;return new Promise((function(n,r){t?n(v(e[t-1])):r(Error("getCurrentPages().length=0"))}))},callUniMethod:function(e){var t=e.method,n=e.args;return new Promise((function(e,r){if(!uni[t])return r(Error("uni."+t+" not exists"));if(O(t))return e({result:uni[t].apply(uni,n)});var o=[Object.assign({},n[0]||{},{success:function(n){setTimeout((function(){e({result:n})}),"pageScrollTo"===t?350:0)},fail:function(e){r(Error(e.errMsg.replace(t+":fail ","")))}})];uni[t].apply(uni,o)}))},mockUniMethod:function(e){var t=e.method;if(!uni[t])throw Error("uni."+t+" not exists");if(!function(e){return!S.test(e)}(t))throw Error("You can't mock uni."+t);var r=e.result;if(n(r))return x[t]&&(uni[t]=x[t],delete x[t]),Promise.resolve();var o=O(t)?function(){return r}:function(e){setTimeout((function(){r.errMsg&&-1!==r.errMsg.indexOf(":fail")?e.fail&&e.fail(r):e.success&&e.success(r),e.complete&&e.complete(r)}),4)};return x[t]||(x[t]=uni[t]),uni[t]=o,Promise.resolve()}},b={getData:function(e){return E(_(e.pageId),e.path)},setData:function(e){return y(_(e.pageId),e.data)},callMethod:function(t){var n,r=((n={})[e.VM_NOT_EXISTS]="Page["+t.pageId+"] not exists",n[e.METHOD_NOT_EXISTS]="page."+t.method+" not exists",n);return new Promise((function(e,n){w(_(t.pageId),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(r[e]))}))}))}};function I(e){return e.nodeId||e.elementId}var M={getData:function(e){return E(h(e.pageId,I(e)),e.path)},setData:function(e){return y(h(e.pageId,I(e)),e.data)},callMethod:function(t){var n,r=I(t),o=((n={})[e.VM_NOT_EXISTS]="Component["+t.pageId+":"+r+"] not exists",n[e.METHOD_NOT_EXISTS]="component."+t.method+" not exists",n);return new Promise((function(e,n){w(h(t.pageId,r),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(o[e]))}))}))}}; /*! ***************************************************************************** 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 O(){for(var e=0,t=0,n=arguments.length;t"+V(H(e,"inner"))+"":V(e.toString()):V(e.pureChildren.map((function(e){return e.toString()})).join(""))}var X={input:{input:function(e,t){e.setValue(t)}},textarea:{input:function(e,t){e.setValue(t)}},"scroll-view":{scrollTo:function(e,t,n){e.scrollTo(n)},scrollTop:function(e){return 0},scrollLeft:function(e){return 0},scrollWidth:function(e){return 0},scrollHeight:function(e){return 0}},swiper:{swipeTo:function(e,t){e.__vue__.current=t}},"movable-view":{moveTo:function(e,t,n){var r=e.__vue__;r.x=t,r.y=n}},switch:{tap:function(e){var t=e.__vue__;t.checked=!t.checked}},slider:{slideTo:function(e,t){e.__vue__.value=t}}};function W(e){return I(e).body}var z={getWindow:function(e){return W(e)},getDocument:function(e){return W(e)},getEl:function(e,t){var n=I(t).getRef(e);if(!n)throw Error("element destroyed");return n},getOffset:function(e){var t=e.__$weex__||e.ownerDocument.__$weex__;return new Promise((function(n){t.requireModule("dom").getComponentRect(e.ref,(function(e){e.result?n({left:e.size.left,top:e.size.top}):n({left:0,top:0})}))}))},querySelector:function(e,t){return Promise.resolve(A(j(e,t)))},querySelectorAll:function(e,t){return Promise.resolve({elements:j(e,t,[]).map((function(e){return A(e)}))})},queryProperties:function(e,t){var n=R.find((function(n){return n.test(t,e)}));return n?n.call(e).then((function(e){return{properties:e}})):Promise.resolve({properties:t.map((function(t){return l(e,t)}))})},queryAttributes:function(e,t){var n=e.attr;return Promise.resolve({attributes:t.map((function(e){return String(n[e]||n[c(e)]||"")}))})},queryStyles:function(e,t){var n=e.style;return Promise.resolve({styles:t.map((function(e){return n[e]}))})},queryHTML:function(e,t){return Promise.resolve({html:H(e,t)})},dispatchTapEvent:function(e){return e.fireEvent("click",{timeStamp:Date.now(),target:e,currentTarget:e},!0),Promise.resolve()},dispatchLongpressEvent:function(e){return e.fireEvent("longpress",{timeStamp:Date.now(),target:e,currentTarget:e},!0),Promise.resolve()},dispatchTouchEvent:function(e,t,n){return n||(n={}),n.touches||(n.touches=[]),n.changedTouches||(n.changedTouches=[]),n.touches.length||n.touches.push({identifier:Date.now(),target:e}),e.fireEvent(t,Object.assign({timeStamp:Date.now(),target:e,currentTarget:e},n),!0),Promise.resolve()},callFunction:function(e,t,n){var r=l(X,t);return r?Promise.resolve({result:r.apply(null,O([e],n))}):Promise.reject(Error(t+" not exists"))},triggerEvent:function(e,t,n){var r=e.__vue__;return r?r.$trigger&&r.$trigger(t,{},n):e.fireEvent(t,{timeStamp:Date.now(),target:e,currentTarget:e},!1,{params:[{detail:n}]}),Promise.resolve()}};var U={};Object.keys(T).forEach((function(e){U["App."+e]=T[e]})),Object.keys(S).forEach((function(e){U["Page."+e]=S[e]})),Object.keys($).forEach((function(e){U["Element."+e]=$[e]}));var L,J,B,F=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function Z(e){B.send({data:JSON.stringify(e)})}function G(e){var t=JSON.parse(e.data),n=t.id,r=t.method,o=t.params,u={id:n},i=U[r];if(!i){if(J){var c=J(n,r,o,u);if(!0===c)return;i=c}if(!i)return u.error={message:r+" unimplemented"},Z(u)}try{i(o).then((function(e){e&&(u.result=e)})).catch((function(e){u.error={message:e.message}})).finally((function(){Z(u)}))}catch(e){u.error={message:e.message},Z(u)}}J=function(e,t,n,r){var o=n.pageId,u=function(e){var t=getCurrentPages();if(!e)return t[t.length-1];return t.find((function(t){return t.$page.id===e}))}(o);return u?!u.$page.meta.isNVue?(UniServiceJSBridge.publishHandler("sendAutoMessage",{id:e,method:t,params:n},o),!0):(L||(L=Object.assign({},function(e){return{"Page.getElement":function(t){return e.querySelector(e.getDocument(t.pageId),t.selector)},"Page.getElements":function(t){return e.querySelectorAll(e.getDocument(t.pageId),t.selector)},"Page.getWindowProperties":function(t){return e.queryProperties(e.getWindow(t.pageId),t.names)}}}(z),function(e){var t=function(t){return e.getEl(t.elementId,t.pageId)};return{"Element.getElement":function(n){return e.querySelector(t(n),n.selector)},"Element.getElements":function(n){return e.querySelectorAll(t(n),n.selector)},"Element.getDOMProperties":function(n){return e.queryProperties(t(n),n.names)},"Element.getProperties":function(n){var r=t(n),o=r.__vue__||r.attr||{};return e.queryProperties(o,n.names)},"Element.getOffset":function(n){return e.getOffset(t(n))},"Element.getAttributes":function(n){return e.queryAttributes(t(n),n.names)},"Element.getStyles":function(n){return e.queryStyles(t(n),n.names)},"Element.getHTML":function(n){return e.queryHTML(t(n),n.type)},"Element.tap":function(n){return e.dispatchTapEvent(t(n))},"Element.longpress":function(n){return e.dispatchLongpressEvent(t(n))},"Element.touchstart":function(n){return e.dispatchTouchEvent(t(n),"touchstart",n)},"Element.touchmove":function(n){return e.dispatchTouchEvent(t(n),"touchmove",n)},"Element.touchend":function(n){return e.dispatchTouchEvent(t(n),"touchend",n)},"Element.callFunction":function(n){return e.callFunction(t(n),n.functionName,n.args)},"Element.triggerEvent":function(n){return e.triggerEvent(t(n),n.type,n.detail)}}}(z))),L[t]):(r.error={message:"page["+o+"] not exists"},Z(r),!0)},UniServiceJSBridge.subscribe("onAutoMessageReceive",(function(e){Z(e)})),setTimeout((function(){var e;global.testMessage=G,void 0===e&&(e={}),(B=uni.connectSocket({url:F,complete:function(){}})).onMessage(G),B.onOpen((function(t){e.success&&e.success(),console.log("已开启自动化测试...")})),B.onError((function(e){console.log("automator.onError",e)})),B.onClose((function(){e.fail&&e.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))}),500); +function C(){for(var e=0,t=0,n=arguments.length;t"+X(W(e,"inner"))+"":X(e.toString()):X(e.pureChildren.map((function(e){return e.toString()})).join(""))}var z={input:{input:function(e,t){e.setValue(t)}},textarea:{input:function(e,t){e.setValue(t)}},"scroll-view":{scrollTo:function(e,t,n){e.scrollTo(n)},scrollTop:function(e){return 0},scrollLeft:function(e){return 0},scrollWidth:function(e){return 0},scrollHeight:function(e){return 0}},swiper:{swipeTo:function(e,t){e.__vue__.current=t}},"movable-view":{moveTo:function(e,t,n){var r=e.__vue__;r.x=t,r.y=n}},switch:{tap:function(e){var t=e.__vue__;t.checked=!t.checked}},slider:{slideTo:function(e,t){e.__vue__.value=t}}};function J(e){return N(e).body}var F={getWindow:function(e){return J(e)},getDocument:function(e){return J(e)},getEl:function(e,t){var n=N(t).getRef(e);if(!n)throw Error("element destroyed");return n},getOffset:function(e){var t=e.__$weex__||e.ownerDocument.__$weex__;return new Promise((function(n){t.requireModule("dom").getComponentRect(e.ref,(function(e){e.result?n({left:e.size.left,top:e.size.top}):n({left:0,top:0})}))}))},querySelector:function(e,t){return Promise.resolve(B(L(e,t)))},querySelectorAll:function(e,t){return Promise.resolve({elements:L(e,t,[]).map((function(e){return B(e)}))})},queryProperties:function(e,t){var n=U.find((function(n){return n.test(t,e)}));return n?n.call(e).then((function(e){return{properties:e}})):Promise.resolve({properties:t.map((function(t){return d(e,t)}))})},queryAttributes:function(e,t){var n=e.attr;return Promise.resolve({attributes:t.map((function(e){return String(n[e]||n[a(e)]||"")}))})},queryStyles:function(e,t){var n=e.style;return Promise.resolve({styles:t.map((function(e){return n[e]}))})},queryHTML:function(e,t){return Promise.resolve({html:W(e,t)})},dispatchTapEvent:function(e){return e.fireEvent("click",{timeStamp:Date.now(),target:e,currentTarget:e},!0),Promise.resolve()},dispatchLongpressEvent:function(e){return e.fireEvent("longpress",{timeStamp:Date.now(),target:e,currentTarget:e},!0),Promise.resolve()},dispatchTouchEvent:function(e,t,n){return n||(n={}),n.touches||(n.touches=[]),n.changedTouches||(n.changedTouches=[]),n.touches.length||n.touches.push({identifier:Date.now(),target:e}),e.fireEvent(t,Object.assign({timeStamp:Date.now(),target:e,currentTarget:e},n),!0),Promise.resolve()},callFunction:function(e,t,n){var r=d(z,t);return r?Promise.resolve({result:r.apply(null,C([e],n))}):Promise.reject(Error(t+" not exists"))},triggerEvent:function(e,t,n){var r=e.__vue__;return r?r.$trigger&&r.$trigger(t,{},n):e.fireEvent(t,{timeStamp:Date.now(),target:e,currentTarget:e},!1,{params:[{detail:n}]}),Promise.resolve()}};var K={};Object.keys($).forEach((function(e){K["App."+e]=$[e]})),Object.keys(b).forEach((function(e){K["Page."+e]=b[e]})),Object.keys(M).forEach((function(e){K["Element."+e]=M[e]}));var Q,Y,Z,G=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function ee(e){Z.send({data:JSON.stringify(e)})}function te(e){var t=JSON.parse(e.data),n=t.id,r=t.method,o=t.params,u={id:n},i=K[r];if(!i){if(Y){var c=Y(n,r,o,u);if(!0===c)return;i=c}if(!i)return u.error={message:r+" unimplemented"},ee(u)}try{i(o).then((function(e){e&&(u.result=e)})).catch((function(e){u.error={message:e.message}})).finally((function(){ee(u)}))}catch(e){u.error={message:e.message},ee(u)}}Y=function(e,t,n,r){var o=n.pageId,u=function(e){var t=getCurrentPages();if(!e)return t[t.length-1];return t.find((function(t){return t.$page.id===e}))}(o);return u?!u.$page.meta.isNVue?(UniServiceJSBridge.publishHandler("sendAutoMessage",{id:e,method:t,params:n},o),!0):(Q||(Q=Object.assign({},function(e){return{"Page.getElement":function(t){return e.querySelector(e.getDocument(t.pageId),t.selector)},"Page.getElements":function(t){return e.querySelectorAll(e.getDocument(t.pageId),t.selector)},"Page.getWindowProperties":function(t){return e.queryProperties(e.getWindow(t.pageId),t.names)}}}(F),function(e){var t=function(t){return e.getEl(t.elementId,t.pageId)};return{"Element.getElement":function(n){return e.querySelector(t(n),n.selector)},"Element.getElements":function(n){return e.querySelectorAll(t(n),n.selector)},"Element.getDOMProperties":function(n){return e.queryProperties(t(n),n.names)},"Element.getProperties":function(n){var r=t(n),o=r.__vue__||r.attr||{};return e.queryProperties(o,n.names)},"Element.getOffset":function(n){return e.getOffset(t(n))},"Element.getAttributes":function(n){return e.queryAttributes(t(n),n.names)},"Element.getStyles":function(n){return e.queryStyles(t(n),n.names)},"Element.getHTML":function(n){return e.queryHTML(t(n),n.type)},"Element.tap":function(n){return e.dispatchTapEvent(t(n))},"Element.longpress":function(n){return e.dispatchLongpressEvent(t(n))},"Element.touchstart":function(n){return e.dispatchTouchEvent(t(n),"touchstart",n)},"Element.touchmove":function(n){return e.dispatchTouchEvent(t(n),"touchmove",n)},"Element.touchend":function(n){return e.dispatchTouchEvent(t(n),"touchend",n)},"Element.callFunction":function(n){return e.callFunction(t(n),n.functionName,n.args)},"Element.triggerEvent":function(n){return e.triggerEvent(t(n),n.type,n.detail)}}}(F))),Q[t]):(r.error={message:"page["+o+"] not exists"},ee(r),!0)},UniServiceJSBridge.subscribe("onAutoMessageReceive",(function(e){ee(e)})),setTimeout((function(){var e;global.testMessage=te,void 0===e&&(e={}),(Z=uni.connectSocket({url:G,complete:function(){}})).onMessage(te),Z.onOpen((function(t){e.success&&e.success(),console.log("已开启自动化测试...")})),Z.onError((function(e){console.log("automator.onError",e)})),Z.onClose((function(){e.fail&&e.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))}),500); diff --git a/packages/uni-automator/dist/index.js b/packages/uni-automator/dist/index.js index adf24a52c8a482242f84eb5a63b05b03dae7481d..aad7688231ac60457d9cafec77b50fdb75f505fe 100644 --- a/packages/uni-automator/dist/index.js +++ b/packages/uni-automator/dist/index.js @@ -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 R;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 x(t,e,n){return A(R.RUNTIME,n)}function j(t,e,n){return A(R.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(R||(R={}));class q{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===R.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 S 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([x],S.prototype,"getData",null),D([x],S.prototype,"setData",null),D([x],S.prototype,"callMethod",null),D([j],S.prototype,"getElement",null),D([j],S.prototype,"getElements",null),D([j],S.prototype,"getOffset",null),D([j],S.prototype,"getHTML",null),D([j],S.prototype,"getAttributes",null),D([j],S.prototype,"getStyles",null),D([j],S.prototype,"getDOMProperties",null),D([j],S.prototype,"getProperties",null),D([j],S.prototype,"tap",null),D([j],S.prototype,"longpress",null),D([j],S.prototype,"touchstart",null),D([j],S.prototype,"touchmove",null),D([j],S.prototype,"touchend",null),D([j],S.prototype,"triggerEvent",null),D([j],S.prototype,"callFunction",null),D([j],S.prototype,"callContextMethod",null);class ${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 S(t,e)}async $(t){try{const e=await this.api.getElement({selector:t});return $.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=>$.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=F;break;case"textarea":s=O;break;case"scroll-view":s=N;break;case"swiper":s=L;break;case"movable-view":s=_;break;case"switch":s=H;break;case"slider":s=B;break;case"video":s=W;break;default:s=$}return i=new s(t,e,n),n.set(e.elementId,i),i}}class U extends ${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 F extends ${async input(t){return this.callFunction("input.input",t)}}class O extends ${async input(t){return this.callFunction("textarea.input",t)}}class N extends ${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 ${async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class _ extends ${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 H extends ${async tap(){return this.callFunction("switch.tap")}}class B extends ${async slideTo(t){return this.callFunction("slider.slideTo",t)}}class W extends ${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([x],V.prototype,"getData",null),D([x],V.prototype,"setData",null),D([x],V.prototype,"callMethod",null),D([j],V.prototype,"getElement",null),D([j],V.prototype,"getElements",null),D([j],V.prototype,"getWindowProperties",null);class z{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)}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 $.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=>$.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 z(t,e),n.set(e.id,s),s)}}class J 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([x],J.prototype,"getPageStack",null),D([x],J.prototype,"callUniMethod",null),D([x],J.prototype,"getCurrentPage",null),D([j],J.prototype,"mockUniMethod",null),D([j],J.prototype,"callFunction",null),D([j],J.prototype,"captureScreenshot",null),D([j],J.prototype,"exit",null),D([j],J.prototype,"addBinding",null),D([j],J.prototype,"enableLog",null);class G 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 X(t){return new Promise(e=>setTimeout(e,t))}D([j],G.prototype,"getInfo",null),D([j],G.prototype,"enableRemoteDebug",null),D([j],G.prototype,"close",null),D([j],G.prototype,"getTestAccounts",null);class Y extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new J(t),this.toolApi=new G(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=>z.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 z.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 X(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=>{I.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await X(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 X(3e3),this.currentPage()}}class K{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 Q=s("automator:puppet");function Z(t){try{return require(t)}catch(t){}}function tt(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=Z(o)):(o=n.join(t,`dist/${s}/.automator/${e}`,".automator.json"),i=Z(o),i||(o=n.join(t,`unpackage/dist/${s}/.automator/${e}`,".automator.json"),i=Z(o))),Q(`${o}=>${JSON.stringify(i)}`),i}(t,s,i);if(!o||!o.wsEndpoint)return!1;const r=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 Q("wsEndpoint=>"+r),o.wsEndpoint===r}class et 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 K(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=!tt(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 nt=s("automator:compiler"),st=/The\s+(.*)\s+directory is ready/;class it{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=process.env.UNI_NPM_PATH||"npm",c=`${e}:${s}`,p=t.projectPath,l=["run",c,"--","--auto-port",E(o)];r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath||t.projectPath,env:process.env};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();nt("url: "+e),t({path:e})}else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(st);a&&a.length>1&&(o=a[1]),i=!0,this.stop(),t({path:n.join(p,o)})}};nt(`${a} ${l.join(" ")}`),this.cliProcess=k.spawn(a,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")}}class ot{async launch(t){let e=t[t.platform]||{};this.puppet=new et(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 it(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 Y(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.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 C.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new ot}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 R;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 j(t,e,n){return A(R.RUNTIME,n)}function x(t,e,n){return A(R.DEVTOOL,n)}!function(t){t.RUNTIME="runtime",t.DEVTOOL="devtool"}(R||(R={}));class q{constructor(t){this.puppet=t}invoke(t,e){return async n=>this.puppet.devtoolConnection?(n===R.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 $ 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([j],$.prototype,"getData",null),D([j],$.prototype,"setData",null),D([j],$.prototype,"callMethod",null),D([x],$.prototype,"getElement",null),D([x],$.prototype,"getElements",null),D([x],$.prototype,"getOffset",null),D([x],$.prototype,"getHTML",null),D([x],$.prototype,"getAttributes",null),D([x],$.prototype,"getStyles",null),D([x],$.prototype,"getDOMProperties",null),D([x],$.prototype,"getProperties",null),D([x],$.prototype,"tap",null),D([x],$.prototype,"longpress",null),D([x],$.prototype,"touchstart",null),D([x],$.prototype,"touchmove",null),D([x],$.prototype,"touchend",null),D([x],$.prototype,"triggerEvent",null),D([x],$.prototype,"callFunction",null),D([x],$.prototype,"callContextMethod",null);class S{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 $(t,e)}async $(t){try{const e=await this.api.getElement({selector:t});return S.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=>S.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=F;break;case"textarea":s=O;break;case"scroll-view":s=N;break;case"swiper":s=L;break;case"movable-view":s=_;break;case"switch":s=H;break;case"slider":s=B;break;case"video":s=W;break;default:s=S}return i=new s(t,e,n),n.set(e.elementId,i),i}}class U extends S{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 F extends S{async input(t){return this.callFunction("input.input",t)}}class O extends S{async input(t){return this.callFunction("textarea.input",t)}}class N extends S{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 S{async swipeTo(t){return this.callFunction("swiper.swipeTo",t)}}class _ extends S{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 H extends S{async tap(){return this.callFunction("switch.tap")}}class B extends S{async slideTo(t){return this.callFunction("slider.slideTo",t)}}class W extends S{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([j],V.prototype,"getData",null),D([j],V.prototype,"setData",null),D([j],V.prototype,"callMethod",null),D([x],V.prototype,"getElement",null),D([x],V.prototype,"getElements",null),D([x],V.prototype,"getWindowProperties",null);class z{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)}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 S.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=>S.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 z(t,e),n.set(e.id,s),s)}}class J 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([j],J.prototype,"getPageStack",null),D([j],J.prototype,"callUniMethod",null),D([j],J.prototype,"getCurrentPage",null),D([j],J.prototype,"mockUniMethod",null),D([x],J.prototype,"callFunction",null),D([x],J.prototype,"captureScreenshot",null),D([x],J.prototype,"exit",null),D([x],J.prototype,"addBinding",null),D([x],J.prototype,"enableLog",null);class G 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 X(t){return new Promise(e=>setTimeout(e,t))}D([x],G.prototype,"getInfo",null),D([x],G.prototype,"enableRemoteDebug",null),D([x],G.prototype,"close",null),D([x],G.prototype,"getTestAccounts",null);class Y extends r.EventEmitter{constructor(t,e){super(),this.puppet=t,this.options=e,this.pageMap=new Map,this.appBindings=new Map,this.appApi=new J(t),this.toolApi=new G(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=>z.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 z.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 X(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=>{I.generate(n,{small:!0},e=>{process.stdout.write(e),t()})}));const s=new Promise(t=>{this.toolApi.onRemoteDebugConnected(async()=>{await X(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 X(3e3),this.currentPage()}}class K{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 Q=s("automator:puppet");function Z(t){try{return require(t)}catch(t){}}function tt(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=Z(o)):(o=n.join(t,`dist/${s}/.automator/${e}`,".automator.json"),i=Z(o),i||(o=n.join(t,`unpackage/dist/${s}/.automator/${e}`,".automator.json"),i=Z(o))),Q(`${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 Q(`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 Q("wsEndpoint=>"+a),o.wsEndpoint===a}class et 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 K(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=!tt(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 nt=s("automator:compiler"),st=/The\s+(.*)\s+directory is ready/;class it{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=process.env.UNI_NPM_PATH||(/^win/.test(process.platform)?"npm.cmd":"npm"),c=`${e}:${s}`,p=t.projectPath,l=["run",c,"--","--auto-port",E(o)];r&&(l.push("--auto-host"),l.push(r));const u={cwd:t.cliPath||t.projectPath,env:process.env};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();nt("url: "+e),t({path:e})}else if(r.includes("DONE Build complete")){let o=`unpackage/dist/${e}/${s}`;const a=r.match(st);a&&a.length>1&&(o=a[1]),i=!0,this.stop(),t({path:n.join(p,o)})}};nt(`${a} ${l.join(" ")}`),this.cliProcess=k.spawn(a,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")}}class ot{async launch(t){let e=t[t.platform]||{};this.puppet=new et(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 it(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 Y(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.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 C.createRuntimeConnection(t,this.puppet,e)}}module.exports=class{constructor(){this.launcher=new ot}async launch(t){return this.launcher.launch(t)}}; diff --git a/packages/uni-h5/dist/automator.js b/packages/uni-h5/dist/automator.js index e1354f447a5ecc088de91a3b3467f09b898db46f..01e4dc4bb1f1f097e33bc76fb50515f393b45fe9 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-","")}]},j=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},P=j(b.SELECTOR),q=j(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader");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 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=>P(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("jimp"),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-","")}]},j=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},P=j(b.SELECTOR),q=j(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader");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=>P(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/dist/automator.js b/packages/uni-mp-weixin/dist/automator.js index 9cf318043fa9bf1f54dc5dc0f7bd69937804e4f5..c3ecc955718292243f973725abd8895bb721fd5c 100644 --- a/packages/uni-mp-weixin/dist/automator.js +++ b/packages/uni-mp-weixin/dist/automator.js @@ -1 +1 @@ -var n,e=Object.prototype.hasOwnProperty,t=Array.isArray,r=function(n){var e=Object.create(null);return function(t){return e[t]||(e[t]=n(t))}},o=/-(\w)/g,u=r((function(n){return n.replace(o,(function(n,e){return e?e.toUpperCase():""}))})),i=r((function(n){return n.charAt(0).toUpperCase()+n.slice(1)})),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function c(n,r){if(t(n))return n;if(r&&(o=r,u=n,e.call(o,u)))return[n];var o,u,i=[];return n.replace(a,(function(n,e,t,r){return i.push(t?r.replace(/\\(\\)?/g,"$1"):e||n),r})),i}function s(n){return n.__wxWebviewId__?n.__wxWebviewId__:n.privateProperties?n.privateProperties.slaveId:n.$page?n.$page.id:void 0}function f(n){return n.route||n.uri}function p(n){return n.options||n.$page&&n.$page.options||{}}function l(n){return{id:s(n),path:f(n),query:p(n)}}function d(n){var e=function(n){return getCurrentPages().find((function(e){return s(e)===n}))}(n);return e&&e.$vm}function g(n,e){var t=d(n);return t&&function n(e,t){var r;return e&&(!function(n,e){return n.$scope&&((t=n.$scope).__wxExparserNodeId__||t.nodeId||t.id)===e;var t}(e,t)?e.$children.find((function(e){return r=n(e,t)})):r=e),r}(t,e)}function m(n,e){var t;return n&&(t=e?function(n,e){var t,r=c(e,n);for(t=r.shift();null!=t;){if(null==(n=n[t]))return;t=r.shift()}return n}(n.$data,e):Object.assign({},n.$data)),Promise.resolve({data:t})}function v(n,e){return n&&Object.keys(e).forEach((function(t){n[t]=e[t]})),Promise.resolve()}function h(e,t,r){return new Promise((function(o,u){if(!e)return u(n.VM_NOT_EXISTS);if(!e[t])return u(n.VM_NOT_EXISTS);var i,a=e[t].apply(e,r);!(i=a)||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then?o({result:a}):a.then((function(n){o({result:n})}))}))}!function(n){n.VM_NOT_EXISTS="VM_NOT_EXISTS",n.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(n||(n={}));var _=/Sync$/;var y={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(n){return l(n)}))})},getCurrentPage:function(){var n=getCurrentPages(),e=n.length;return new Promise((function(t,r){e?t(l(n[e-1])):r(Error("getCurrentPages().length=0"))}))},callUniMethod:function(n){var e=n.method,t=n.args;return new Promise((function(n,r){if(!uni[e])return r(Error("uni."+e+" not exists"));if(function(n){return _.test(n)}(e))return n({result:uni[e].apply(uni,t)});var o=[Object.assign({},t[0]||{},{success:function(t){setTimeout((function(){n({result:t})}),"pageScrollTo"===e?350:0)},fail:function(n){r(Error(n.errMsg.replace(e+":fail ","")))}})];uni[e].apply(uni,o)}))}},T={getData:function(n){return m(d(n.pageId),n.path)},setData:function(n){return v(d(n.pageId),n.data)},callMethod:function(e){var t,r=((t={})[n.VM_NOT_EXISTS]="Page["+e.pageId+"] not exists",t[n.METHOD_NOT_EXISTS]="page."+e.method+" not exists",t);return new Promise((function(n,t){h(d(e.pageId),e.method,e.args).then((function(e){return n(e)})).catch((function(n){t(Error(r[n]))}))}))}};function O(n){return n.nodeId||n.elementId}for(var S={getData:function(n){return m(g(n.pageId,O(n)),n.path)},setData:function(n){return v(g(n.pageId,O(n)),n.data)},callMethod:function(e){var t,r=O(e),o=((t={})[n.VM_NOT_EXISTS]="Component["+e.pageId+":"+r+"] not exists",t[n.METHOD_NOT_EXISTS]="component."+e.method+" not exists",t);return new Promise((function(n,t){h(g(e.pageId,r),e.method,e.args).then((function(e){return n(e)})).catch((function(n){t(Error(o[n]))}))}))}},E=("undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),[]),I=0;I<256;++I)E[I]=(I+256).toString(16).substr(1);["movable-view","picker","ad","button","checkbox-group","checkbox","form","icon","label","movable-area","navigator","picker-view-column","picker-view","progress","radio-group","radio","rich-text","u-slider","swiper-item","swiper","switch"].map((function(n){return i(u(n))}));var b={};Object.keys(y).forEach((function(n){b["App."+n]=y[n]})),Object.keys(T).forEach((function(n){b["Page."+n]=T[n]})),Object.keys(S).forEach((function(n){b["Element."+n]=S[n]}));var w,P=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function $(n){w.send({data:JSON.stringify(n)})}function M(n){var e=JSON.parse(n.data),t=e.id,r=e.method,o=e.params,u={id:t},i=b[r];if(!i&&!i)return u.error={message:r+" unimplemented"},$(u);try{i(o).then((function(n){n&&(u.result=n)})).catch((function(n){u.error={message:n.message}})).finally((function(){$(u)}))}catch(n){u.error={message:n.message},$(u)}}wx.$$initRuntimeAutomator=function(n){void 0===n&&(n={}),(w=uni.connectSocket({url:P,complete:function(){}})).onMessage(M),w.onOpen((function(e){n.success&&n.success(),console.log("已开启自动化测试...")})),w.onError((function(n){console.log("automator.onError",n)})),w.onClose((function(){n.fail&&n.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500); +var e,t=Object.prototype.hasOwnProperty,n=function(e){return null==e},r=Array.isArray,o=function(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}},i=/-(\w)/g,a=o((function(e){return e.replace(i,(function(e,t){return t?t.toUpperCase():""}))})),u=o((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),c=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function s(e,n){if(r(e))return e;if(n&&(o=n,i=e,t.call(o,i)))return[e];var o,i,a=[];return e.replace(c,(function(e,t,n,r){return a.push(n?r.replace(/\\(\\)?/g,"$1"):t||e),r})),a}function f(e){return e.__wxWebviewId__?e.__wxWebviewId__:e.privateProperties?e.privateProperties.slaveId:e.$page?e.$page.id:void 0}function p(e){return e.route||e.uri}function d(e){return e.options||e.$page&&e.$page.options||{}}function l(e){return{id:f(e),path:p(e),query:d(e)}}function g(e){var t=function(e){return getCurrentPages().find((function(t){return f(t)===e}))}(e);return t&&t.$vm}function m(e,t){var n=g(e);return n&&function e(t,n){var r;return t&&(!function(e,t){return e.$scope&&((n=e.$scope).__wxExparserNodeId__||n.nodeId||n.id)===t;var n}(t,n)?t.$children.find((function(t){return r=e(t,n)})):r=t),r}(n,t)}function v(e,t){var r;return e&&(r=t?function(e,t){var r,o=s(t,e);for(r=o.shift();!n(r);){if(null==(e=e[r]))return;r=o.shift()}return e}(e.$data,t):Object.assign({},e.$data)),Promise.resolve({data:r})}function h(e,t){return e&&Object.keys(t).forEach((function(n){e[n]=t[n]})),Promise.resolve()}function T(t,n,r){return new Promise((function(o,i){if(!t)return i(e.VM_NOT_EXISTS);if(!t[n])return i(e.VM_NOT_EXISTS);var a,u=t[n].apply(t,r);!(a=u)||"object"!=typeof a&&"function"!=typeof a||"function"!=typeof a.then?o({result:u}):u.then((function(e){o({result:e})}))}))}!function(e){e.VM_NOT_EXISTS="VM_NOT_EXISTS",e.METHOD_NOT_EXISTS="METHOD_NOT_EXISTS"}(e||(e={}));var _=["stopRecord","getRecorderManager","pauseVoice","stopVoice","pauseBackgroundAudio","stopBackgroundAudio","getBackgroundAudioManager","createAudioContext","createInnerAudioContext","createVideoContext","createCameraContext","createMapContext","canIUse","startAccelerometer","stopAccelerometer","startCompass","stopCompass","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","navigateBack","createAnimation","pageScrollTo","createSelectorQuery","createCanvasContext","createContext","drawCanvas","hideKeyboard","stopPullDownRefresh","arrayBufferToBase64","base64ToArrayBuffer"],y={},O=/Sync$/,S=/^on|^off/;function E(e){return O.test(e)||-1!==_.indexOf(e)}var I={getPageStack:function(){return Promise.resolve({pageStack:getCurrentPages().map((function(e){return l(e)}))})},getCurrentPage:function(){var e=getCurrentPages(),t=e.length;return new Promise((function(n,r){t?n(l(e[t-1])):r(Error("getCurrentPages().length=0"))}))},callUniMethod:function(e){var t=e.method,n=e.args;return new Promise((function(e,r){if(!uni[t])return r(Error("uni."+t+" not exists"));if(E(t))return e({result:uni[t].apply(uni,n)});var o=[Object.assign({},n[0]||{},{success:function(n){setTimeout((function(){e({result:n})}),"pageScrollTo"===t?350:0)},fail:function(e){r(Error(e.errMsg.replace(t+":fail ","")))}})];uni[t].apply(uni,o)}))},mockUniMethod:function(e){var t=e.method;if(!uni[t])throw Error("uni."+t+" not exists");if(!function(e){return!S.test(e)}(t))throw Error("You can't mock uni."+t);var r=e.result;if(n(r))return y[t]&&(uni[t]=y[t],delete y[t]),Promise.resolve();var o=E(t)?function(){return r}:function(e){setTimeout((function(){r.errMsg&&-1!==r.errMsg.indexOf(":fail")?e.fail&&e.fail(r):e.success&&e.success(r),e.complete&&e.complete(r)}),4)};return y[t]||(y[t]=uni[t]),uni[t]=o,Promise.resolve()}},C={getData:function(e){return v(g(e.pageId),e.path)},setData:function(e){return h(g(e.pageId),e.data)},callMethod:function(t){var n,r=((n={})[e.VM_NOT_EXISTS]="Page["+t.pageId+"] not exists",n[e.METHOD_NOT_EXISTS]="page."+t.method+" not exists",n);return new Promise((function(e,n){T(g(t.pageId),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(r[e]))}))}))}};function w(e){return e.nodeId||e.elementId}for(var x={getData:function(e){return v(m(e.pageId,w(e)),e.path)},setData:function(e){return h(m(e.pageId,w(e)),e.data)},callMethod:function(t){var n,r=w(t),o=((n={})[e.VM_NOT_EXISTS]="Component["+t.pageId+":"+r+"] not exists",n[e.METHOD_NOT_EXISTS]="component."+t.method+" not exists",n);return new Promise((function(e,n){T(m(t.pageId,r),t.method,t.args).then((function(t){return e(t)})).catch((function(e){n(Error(o[e]))}))}))}},M=("undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),[]),P=0;P<256;++P)M[P]=(P+256).toString(16).substr(1);["movable-view","picker","ad","button","checkbox-group","checkbox","form","icon","label","movable-area","navigator","picker-view-column","picker-view","progress","radio-group","radio","rich-text","u-slider","swiper-item","swiper","switch"].map((function(e){return u(a(e))}));var b={};Object.keys(I).forEach((function(e){b["App."+e]=I[e]})),Object.keys(C).forEach((function(e){b["Page."+e]=C[e]})),Object.keys(x).forEach((function(e){b["Element."+e]=x[e]}));var $,k=process.env.UNI_AUTOMATOR_WS_ENDPOINT;function A(e){$.send({data:JSON.stringify(e)})}function N(e){var t=JSON.parse(e.data),n=t.id,r=t.method,o=t.params,i={id:n},a=b[r];if(!a&&!a)return i.error={message:r+" unimplemented"},A(i);try{a(o).then((function(e){e&&(i.result=e)})).catch((function(e){i.error={message:e.message}})).finally((function(){A(i)}))}catch(e){i.error={message:e.message},A(i)}}wx.$$initRuntimeAutomator=function(e){void 0===e&&(e={}),($=uni.connectSocket({url:k,complete:function(){}})).onMessage(N),$.onOpen((function(t){e.success&&e.success(),console.log("已开启自动化测试...")})),$.onError((function(e){console.log("automator.onError",e)})),$.onClose((function(){e.fail&&e.fail({errMsg:"$$initRuntimeAutomator:fail"}),console.log("automator.onClose")}))},setTimeout((function(){wx.$$initRuntimeAutomator()}),500); diff --git a/packages/uni-mp-weixin/lib/uni.automator.js b/packages/uni-mp-weixin/lib/uni.automator.js index adb54134c78a27772f2395badbc3edaed52ba143..b6f4857cc8140427c572a46961f2d03ca82de856 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");var n=e(require("jimp"));require("licia/isStr");var o=e(require("licia/getPort")),s=e(require("fs")),a=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),u=e(require("licia/waitUntil")),l=e(require("licia/concat")),d=e(require("licia/dateFormat")),p=e(require("ws")),h=require("events"),m=e(require("licia/uuid")),w=e(require("licia/stringify"));require("qrcode-terminal");const f=require("qrcode-reader");class y 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 g extends h.EventEmitter{constructor(e,r,n){super(),this.puppet=r,this.namespace=n,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:n,result:o,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),n?e.reject(Error(n.message)):e.resolve(o)}},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 n=m(),o=w({id:n,method:e,params:t});return this.debug(`${d("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${o}`),new Promise((e,t)=>{try{this.transport.send(o)}catch(e){t(Error("Connection closed"))}this.callbacks.set(n,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,n)=>{const o=new p(e);o.addEventListener("open",()=>{r(new g(new y(o),t,"devtool"))}),o.addEventListener("error",n)})}static createRuntimeConnection(e,r,n){return new Promise((o,s)=>{t("automator:runtime")(`${d("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new p.Server({port:e});u(async()=>{if(r.runtimeConnection)return!0},n,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")(d("yyyy-mm-dd HH:MM:ss:l")+" connected");const n=new g(new y(e),r,"runtime");r.setRuntimeConnection(n),o(n)})),r.setRuntimeServer(a)})}}const v=t("automator:devtool");async function b(e,t,r){const{port:n,cliPath:o,timeout:s,cwd:p="",account:h="",args:m=[],launch:w=!0}=t;let f=!1,y=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=l(m,[]);r=l(r,["auto","--project"]),r=l(r,[e,"--auto-port",c(n)]),h&&(r=l(r,["--auto-account",h]));try{v("%s %o %o",o,r,t);const e=a.spawn(o,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{y=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{y=!0},15e3);const b=await u(async()=>{try{if(f||y)return!0;return await async function(e,t){let r;try{r=await g.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:"+n},r)}catch(e){}},s,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(y)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),v(d("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const q={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(s.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let n=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{n=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}(n)}catch(t){e.launch=!1}else{n===await o(n)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:n,cliPath:r})},async create(e,r,n){const o=await b(e,r,n);return t("automator:devtool")("initRuntimeAutomator"),o.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]}),o}},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 n.read(t),s=new f;s.callback=function(t,n){if(t)return r(t);e(n.result)},s.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=q; +"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");var o=e(require("jimp"));require("licia/isStr");var n=e(require("licia/getPort")),s=e(require("fs")),a=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),u=e(require("licia/waitUntil")),l=e(require("licia/concat")),d=e(require("licia/dateFormat")),p=e(require("ws")),m=require("events"),h=e(require("licia/uuid")),w=e(require("licia/stringify"));require("qrcode-terminal");const f=require("qrcode-reader");class y extends m.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 g extends m.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(`${d("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=h(),n=w({id:o,method:e,params:t});return this.debug(`${d("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 p(e);n.addEventListener("open",()=>{r(new g(new y(n),t,"devtool"))}),n.addEventListener("error",o)})}static createRuntimeConnection(e,r,o){return new Promise((n,s)=>{t("automator:runtime")(`${d("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new p.Server({port:e});u(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")(d("yyyy-mm-dd HH:MM:ss:l")+" connected");const o=new g(new y(e),r,"runtime");r.setRuntimeConnection(o),n(o)})),r.setRuntimeServer(a)})}}const v=t("automator:devtool");async function b(e,t,r){const{port:o,cliPath:n,timeout:s,cwd:p="",account:m="",args:h=[],launch:w=!0}=t;let f=!1,y=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=l(h,[]);r=l(r,["auto","--project"]),r=l(r,[e,"--auto-port",c(o)]),m&&(r=l(r,["--auto-account",m]));try{v("%s %o %o",n,r,t);const e=a.spawn(n,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{y=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{y=!0},15e3);const b=await u(async()=>{try{if(f||y)return!0;return await async function(e,t){let r;try{r=await g.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){}},s,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(y)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),v(d("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const q={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(s.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let o=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{o=await async function(e,t){const r=await n(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(o)}catch(t){e.launch=!1}else{o===await n(o)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:o,cliPath:r})},async create(e,r,o){const n=await b(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 n=await o.read(t),s=new f;s.callback=function(t,o){if(t)return r(t);e(o.result)},s.decode(n.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=q; diff --git a/packages/vue-cli-plugin-uni/generator.js b/packages/vue-cli-plugin-uni/generator.js index 2b60082c52495057a1f8376a78649d5395ae1b01..73039bf59ecbd78a1ba4292b37cd7bbfab683129 100644 --- a/packages/vue-cli-plugin-uni/generator.js +++ b/packages/vue-cli-plugin-uni/generator.js @@ -44,9 +44,9 @@ module.exports = (api, options, rootOptions) => { '@dcloudio/uni-mp-weixin': version, '@dcloudio/uni-mp-baidu': version, '@dcloudio/uni-mp-alipay': version, - '@dcloudio/uni-mp-toutiao': version, - '@dcloudio/uni-quickapp-webview': version, + '@dcloudio/uni-mp-toutiao': version, '@dcloudio/uni-quickapp-native': version, + '@dcloudio/uni-quickapp-webview': version, '@dcloudio/uni-stat': version, flyio: '^0.6.2', vuex: '^3.2.0' diff --git a/packages/vue-cli-plugin-uni/lib/configure-webpack.js b/packages/vue-cli-plugin-uni/lib/configure-webpack.js index ad682bdc8566048f9e9061996338b31039a7adde..3f30dc2bb95d13c7466944955f15f9633f278c15 100644 --- a/packages/vue-cli-plugin-uni/lib/configure-webpack.js +++ b/packages/vue-cli-plugin-uni/lib/configure-webpack.js @@ -207,6 +207,7 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt transform (content) { if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) { return JSON.stringify({ + version: require('@dcloudio/uni-automator/package.json').version, wsEndpoint: process.env.UNI_AUTOMATOR_WS_ENDPOINT }) }