提交 879fd428 编写于 作者: fxy060608's avatar fxy060608

Merge branch 'dev' of https://github.com/dcloudio/uni-app into alpha

# Conflicts:
#	packages/uni-automator/package.json
......@@ -12,4 +12,4 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function e(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),o=0;for(t=0;t<r;t++)for(var u=arguments[t],i=0,c=u.length;i<c;i++,o++)n[o]=u[i];return n}var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),r=new Uint8Array(16);function n(){if(!t)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(r)}for(var o=[],u=0;u<256;++u)o[u]=(u+256).toString(16).substr(1);function i(e,t,r){var u=t&&r||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||n)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var c=0;c<16;++c)t[u+c]=i[c];return t||function(e,t){var r=t||0,n=o;return[n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]]].join("")}(i)}var c=Object.prototype.hasOwnProperty,a=Array.isArray,s=function(e){var t=Object.create(null);return function(r){return t[r]||(t[r]=e(r))}},l=/-(\w)/g,f=s((function(e){return e.replace(l,(function(e,t){return t?t.toUpperCase():""}))})),p=s((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function d(e,t){if(a(e))return e;if(t&&(r=t,n=e,c.call(r,n)))return[e];var r,n,o=[];return e.replace(g,(function(e,t,r,n){return o.push(r?n.replace(/\\(\\)?/g,"$1"):t||e),n})),o}function m(e,t){var r,n=d(t,e);for(r=n.shift();null!=r;){if(null==(e=e[r]))return;r=n.shift()}return e}var v=new Map;function h(e){if(!function(e){if(e){var t=e.tagName;return 0===t.indexOf("UNI-")||"BODY"===t}return!1}(e))throw Error("no such element");var t,r,n={elementId:(t=e,r=t._id,r||(r=i(),t._id=r,v.set(r,{id:r,element:t})),r),tagName:e.tagName.toLocaleLowerCase().replace("uni-","")},o=e.__vue__;return o&&(o.$parent&&o.$parent.$el===e&&(o=o.$parent),o&&!o.$options.isReserved&&(n.nodeId=function(e){if(e._$weex)return e._uid;if(e._$id)return e._$id;var t=function(e){for(var t=e.$parent;t;){if(t._$id)return t;t=t.$parent}}(e);if(!e.$parent)return"-1";var r=e.$vnode,n=r.context;return n&&n!==t&&n._$id?n._$id+";"+t._$id+","+r.data.attrs._i:t._$id+","+r.data.attrs._i}(o))),"video"===n.tagName&&(n.videoId=n.nodeId),console.log(n),n}var _={input:{input:function(e,t){var r=e.__vue__;r.valueSync=t,r.$triggerInput({},{value:t})}},textarea:{input:function(e,t){var r=e.__vue__;r.valueSync=t,r.$triggerInput({},{value:t})}},"scroll-view":{scrollTo:function(e,t,r){var n=e.__vue__.$refs.main;n.scrollLeft=t,n.scrollTop=r},scrollTop:function(e){return e.__vue__.$refs.main.scrollTop},scrollLeft:function(e){return e.__vue__.$refs.main.scrollLeft},scrollWidth:function(e){return e.__vue__.$refs.main.scrollWidth},scrollHeight:function(e){return e.__vue__.$refs.main.scrollHeight}},swiper:{swipeTo:function(e,t){e.__vue__.current=t}},"movable-view":{moveTo:function(e,t,r){e.__vue__._animationTo(t,r)}},switch:{tap:function(e){e.click()}},slider:{slideTo:function(e,t){var r=e.__vue__,n=r.$refs["uni-slider"],o=n.offsetWidth,u=n.getBoundingClientRect().left;r.value=t,r._onClick({x:(t-r.min)*o/(r.max-r.min)+u})}}},y={getWindow:function(e){return window},getDocument:function(e){return document},getEl:function(e){var t=v.get(e);if(!t)throw Error("element destroyed");return t.element},getOffset:function(e){var t=e.getBoundingClientRect();return Promise.resolve({left:t.left+window.pageXOffset,top:t.top+window.pageYOffset})},querySelector:function(e,t){return"page"===t&&(t="body"),Promise.resolve(h(e.querySelector(t)))},querySelectorAll:function(e,t){var r=[],n=document.querySelectorAll(t);return[].forEach.call(n,(function(e){try{r.push(h(e))}catch(e){}})),Promise.resolve({elements:r})},queryProperties:function(e,t){return Promise.resolve({properties:t.map((function(t){var r=m(e,t);return"document.documentElement.scrollTop"===t&&0===r&&(r=m(e,"document.body.scrollTop")),r}))})},queryAttributes:function(e,t){return Promise.resolve({attributes:t.map((function(t){return String(e.getAttribute(t))}))})},queryStyles:function(e,t){var r=getComputedStyle(e);return Promise.resolve({styles:t.map((function(e){return r[e]}))})},queryHTML:function(e,t){return Promise.resolve({html:(r="outer"===t?e.outerHTML:e.innerHTML,r.replace(/\n/g,"").replace(/(<uni-text[^>]*>)(<span[^>]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1<e.indexOf("<body")?"<page>":"</body>"===e?"</page>":0!==e.indexOf("<uni-")&&0!==e.indexOf("</uni-")?"":e.replace(/uni-/g,"").replace(/ role=""/g,"").replace(/ aria-label=""/g,"")})))});var r},dispatchTapEvent:function(e){return e.click(),Promise.resolve()},dispatchLongpressEvent:function(e){return Promise.resolve()},dispatchTouchEvent:function(e,t,r){r||(r={}),r.touches||(r.touches=[]),r.changedTouches||(r.changedTouches=[]),r.touches.length||r.touches.push({identifier:Date.now(),target:e});var n=r.touches.map((function(e){return new Touch(e)})),o=r.changedTouches.map((function(e){return new Touch(e)}));return e.dispatchEvent(new TouchEvent(t,{cancelable:!0,bubbles:!0,touches:n,targetTouches:[],changedTouches:o})),Promise.resolve()},callFunction:function(t,r,n){var o=m(_,r);return o?Promise.resolve({result:o.apply(null,e([t],n))}):Promise.reject(Error(r+" not exists"))},triggerEvent:function(e,t,r){var n=e.__vue__;return n.$trigger&&n.$trigger(t,{},r),Promise.resolve()}};["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 p(f(e))}));var E=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)}}}(y),function(e){var t=function(t){return e.getEl(t.elementId,t.pageId)};return{"Element.getElement":function(r){return e.querySelector(t(r),r.selector)},"Element.getElements":function(r){return e.querySelectorAll(t(r),r.selector)},"Element.getDOMProperties":function(r){return e.queryProperties(t(r),r.names)},"Element.getProperties":function(r){var n=t(r),o=n.__vue__||n.attr||{};return e.queryProperties(o,r.names)},"Element.getOffset":function(r){return e.getOffset(t(r))},"Element.getAttributes":function(r){return e.queryAttributes(t(r),r.names)},"Element.getStyles":function(r){return e.queryStyles(t(r),r.names)},"Element.getHTML":function(r){return e.queryHTML(t(r),r.type)},"Element.tap":function(r){return e.dispatchTapEvent(t(r))},"Element.longpress":function(r){return e.dispatchLongpressEvent(t(r))},"Element.touchstart":function(r){return e.dispatchTouchEvent(t(r),"touchstart",r)},"Element.touchmove":function(r){return e.dispatchTouchEvent(t(r),"touchmove",r)},"Element.touchend":function(r){return e.dispatchTouchEvent(t(r),"touchend",r)},"Element.callFunction":function(r){return e.callFunction(t(r),r.functionName,r.args)},"Element.triggerEvent":function(r){return e.triggerEvent(t(r),r.type,r.detail)}}}(y));function w(e){return UniViewJSBridge.publishHandler("onAutoMessageReceive",e)}UniViewJSBridge.subscribe("sendAutoMessage",(function(e){var t=e.id,r=e.method,n=e.params,o={id:t},u=E[r];if(!u)return o.error={message:r+" unimplemented"},w(o);try{u(n).then((function(e){e&&(o.result=e)})).catch((function(e){o.error={message:e.message}})).finally((function(){w(o)}))}catch(e){o.error={message:e.message},w(o)}}));
function e(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),o=0;for(t=0;t<n;t++)for(var i=arguments[t],u=0,c=i.length;u<c;u++,o++)r[o]=i[u];return r}!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t():"function"==typeof define&&define.amd?define(t):t()}(0,(function(){function e(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){return t.reject(n)}))}))}function t(e){return!(!e||void 0===e.length)}function n(){}function r(e){if(!(this instanceof r))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],a(e,this)}function o(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,r._immediateFn((function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void u(t.promise,e)}i(t.promise,r)}else(1===e._state?i:u)(t.promise,e._value)}))):e._deferreds.push(t)}function i(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof r)return e._state=3,e._value=t,void c(e);if("function"==typeof n)return void a(function(e,t){return function(){e.apply(t,arguments)}}(n,t),e)}e._state=1,e._value=t,c(e)}catch(t){u(e,t)}}function u(e,t){e._state=2,e._value=t,c(e)}function c(e){2===e._state&&0===e._deferreds.length&&r._immediateFn((function(){e._handled||r._unhandledRejectionFn(e._value)}));for(var t=0,n=e._deferreds.length;n>t;t++)o(e,e._deferreds[t]);e._deferreds=null}function a(e,t){var n=!1;try{e((function(e){n||(n=!0,i(t,e))}),(function(e){n||(n=!0,u(t,e))}))}catch(e){if(n)return;n=!0,u(t,e)}}var s=setTimeout;r.prototype.catch=function(e){return this.then(null,e)},r.prototype.then=function(e,t){var r=new this.constructor(n);return o(this,new function(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}(e,t,r)),r},r.prototype.finally=e,r.all=function(e){return new r((function(n,r){function o(e,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var c=t.then;if("function"==typeof c)return void c.call(t,(function(t){o(e,t)}),r)}i[e]=t,0==--u&&n(i)}catch(e){r(e)}}if(!t(e))return r(new TypeError("Promise.all accepts an array"));var i=Array.prototype.slice.call(e);if(0===i.length)return n([]);for(var u=i.length,c=0;i.length>c;c++)o(c,i[c])}))},r.resolve=function(e){return e&&"object"==typeof e&&e.constructor===r?e:new r((function(t){t(e)}))},r.reject=function(e){return new r((function(t,n){n(e)}))},r.race=function(e){return new r((function(n,o){if(!t(e))return o(new TypeError("Promise.race accepts an array"));for(var i=0,u=e.length;u>i;i++)r.resolve(e[i]).then(n,o)}))},r._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){s(e,0)},r._unhandledRejectionFn=function(e){void 0!==console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype.finally||(l.Promise.prototype.finally=e):l.Promise=r}));var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function r(){if(!t)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}for(var o=[],i=0;i<256;++i)o[i]=(i+256).toString(16).substr(1);function u(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var u=(e=e||{}).random||(e.rng||r)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,t)for(var c=0;c<16;++c)t[i+c]=u[c];return t||function(e,t){var n=t||0,r=o;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}(u)}var c=Object.prototype.hasOwnProperty,a=Array.isArray,s=function(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}},l=/-(\w)/g,f=s((function(e){return e.replace(l,(function(e,t){return t?t.toUpperCase():""}))})),d=s((function(e){return e.charAt(0).toUpperCase()+e.slice(1)})),p=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function m(e,t){if(a(e))return e;if(t&&(n=t,r=e,c.call(n,r)))return[e];var n,r,o=[];return e.replace(p,(function(e,t,n,r){return o.push(n?r.replace(/\\(\\)?/g,"$1"):t||e),r})),o}function v(e,t){var n,r=m(t,e);for(n=r.shift();null!=n;){if(null==(e=e[n]))return;n=r.shift()}return e}var h=new Map;function g(e){if(!function(e){if(e){var t=e.tagName;return 0===t.indexOf("UNI-")||"BODY"===t}return!1}(e))throw Error("no such element");var t,n,r={elementId:(t=e,n=t._id,n||(n=u(),t._id=n,h.set(n,{id:n,element:t})),n),tagName:e.tagName.toLocaleLowerCase().replace("uni-","")},o=e.__vue__;return o&&(o.$parent&&o.$parent.$el===e&&(o=o.$parent),o&&!o.$options.isReserved&&(r.nodeId=function(e){if(e._$weex)return e._uid;if(e._$id)return e._$id;var t=function(e){for(var t=e.$parent;t;){if(t._$id)return t;t=t.$parent}}(e);if(!e.$parent)return"-1";var n=e.$vnode,r=n.context;return r&&r!==t&&r._$id?r._$id+";"+t._$id+","+n.data.attrs._i:t._$id+","+n.data.attrs._i}(o))),"video"===r.tagName&&(r.videoId=r.nodeId),r}var _={input:{input:function(e,t){var n=e.__vue__;n.valueSync=t,n.$triggerInput({},{value:t})}},textarea:{input:function(e,t){var n=e.__vue__;n.valueSync=t,n.$triggerInput({},{value:t})}},"scroll-view":{scrollTo:function(e,t,n){var r=e.__vue__.$refs.main;r.scrollLeft=t,r.scrollTop=n},scrollTop:function(e){return e.__vue__.$refs.main.scrollTop},scrollLeft:function(e){return e.__vue__.$refs.main.scrollLeft},scrollWidth:function(e){return e.__vue__.$refs.main.scrollWidth},scrollHeight:function(e){return e.__vue__.$refs.main.scrollHeight}},swiper:{swipeTo:function(e,t){e.__vue__.current=t}},"movable-view":{moveTo:function(e,t,n){e.__vue__._animationTo(t,n)}},switch:{tap:function(e){e.click()}},slider:{slideTo:function(e,t){var n=e.__vue__,r=n.$refs["uni-slider"],o=r.offsetWidth,i=r.getBoundingClientRect().left;n.value=t,n._onClick({x:(t-n.min)*o/(n.max-n.min)+i})}}},y={getWindow:function(e){return window},getDocument:function(e){return document},getEl:function(e){var t=h.get(e);if(!t)throw Error("element destroyed");return t.element},getOffset:function(e){var t=e.getBoundingClientRect();return Promise.resolve({left:t.left+window.pageXOffset,top:t.top+window.pageYOffset})},querySelector:function(e,t){return"page"===t&&(t="body"),Promise.resolve(g(e.querySelector(t)))},querySelectorAll:function(e,t){var n=[],r=document.querySelectorAll(t);return[].forEach.call(r,(function(e){try{n.push(g(e))}catch(e){}})),Promise.resolve({elements:n})},queryProperties:function(e,t){return Promise.resolve({properties:t.map((function(t){var n=v(e,t);return"document.documentElement.scrollTop"===t&&0===n&&(n=v(e,"document.body.scrollTop")),n}))})},queryAttributes:function(e,t){return Promise.resolve({attributes:t.map((function(t){return String(e.getAttribute(t))}))})},queryStyles:function(e,t){var n=getComputedStyle(e);return Promise.resolve({styles:t.map((function(e){return n[e]}))})},queryHTML:function(e,t){return Promise.resolve({html:(n="outer"===t?e.outerHTML:e.innerHTML,n.replace(/\n/g,"").replace(/(<uni-text[^>]*>)(<span[^>]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(e){return-1<e.indexOf("<body")?"<page>":"</body>"===e?"</page>":0!==e.indexOf("<uni-")&&0!==e.indexOf("</uni-")?"":e.replace(/uni-/g,"").replace(/ role=""/g,"").replace(/ aria-label=""/g,"")})))});var n},dispatchTapEvent:function(e){return e.click(),Promise.resolve()},dispatchLongpressEvent:function(e){return Promise.resolve()},dispatchTouchEvent:function(e,t,n){n||(n={}),n.touches||(n.touches=[]),n.changedTouches||(n.changedTouches=[]),n.touches.length||n.touches.push({identifier:Date.now(),target:e});var r=n.touches.map((function(e){return new Touch(e)})),o=n.changedTouches.map((function(e){return new Touch(e)}));return e.dispatchEvent(new TouchEvent(t,{cancelable:!0,bubbles:!0,touches:r,targetTouches:[],changedTouches:o})),Promise.resolve()},callFunction:function(t,n,r){var o=v(_,n);return o?Promise.resolve({result:o.apply(null,e([t],r))}):Promise.reject(Error(n+" not exists"))},triggerEvent:function(e,t,n){var r=e.__vue__;return r.$trigger&&r.$trigger(t,{},n),Promise.resolve()}};["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 d(f(e))}));var w=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)}}}(y),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)}}}(y));function E(e){return UniViewJSBridge.publishHandler("onAutoMessageReceive",e)}UniViewJSBridge.subscribe("sendAutoMessage",(function(e){var t=e.id,n=e.method,r=e.params,o={id:t},i=w[n];if(!i)return o.error={message:n+" unimplemented"},E(o);try{i(r).then((function(e){e&&(o.result=e)})).catch((function(e){o.error={message:e.message}})).finally((function(){E(o)}))}catch(e){o.error={message:e.message},E(o)}}));
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),s=t(require("debug")),i=t(require("postcss-selector-parser")),r=t(require("fs-extra")),a=t(require("licia/dateFormat")),n=require("path"),o=require("util");function c(t){t.walk(t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}})}require("address"),require("default-gateway"),require("licia/isStr"),require("licia/getPort");const l=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];require("qrcode-terminal"),require("qrcode-reader");const h=/^win/.test(process.platform),u=s("automator:launcher"),p=o.promisify(e.readdir),d=o.promisify(e.stat);class m{constructor(t){this.id=t.id,this.app=t.executablePath,this.appid=t.appid||"HBuilder",this.package=t.package||"io.dcloud.HBuilder"}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then(()=>(u(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1)).catch(()=>(u(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0))}push(t){return async function t(e){const s=await p(e);return(await Promise.all(s.map(async s=>{const i=n.resolve(e,s);return(await d(i)).isDirectory()?t(i):i}))).reduce((t,e)=>t.concat(e),[])}(t).then(e=>{const s=e.map(e=>{const s=(t=>h?t.replace(/\\/g,"/"):t)(n.join(this.DIR_WWW,n.relative(t,e)));return u(`${a("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${s}`),this.pushFile(e,s)});return Promise.all(s)}).then(t=>!0)}get FILE_APP_SERVICE(){return this.DIR_WWW+"/app-service.js"}}const y=s("automator:simctl");class f extends m{async init(){const t=require("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),y(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=(await this.tool.appInfo(this.package)).match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.sdcard?"9.6.96":"")}async install(){return y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.initSDCard(),Promise.resolve(!0)}async start(){try{await this.tool.terminateApp(this.package),await this.tool.launchApp(this.package)}catch(t){}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(){return Promise.resolve(await this.tool.getScreenshot())}exists(t){return r.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(t+" not exists"))}pushFile(t,e){return Promise.resolve(r.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const w=require("adbkit"),g=s("automator:adb");class M extends m{async init(){if(this.tool=w.createClient(),!this.id){const t=await this.tool.listDevices();if(!t.length)throw Error("Device not found");this.id=t[0].id}this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),g(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}version(){return this.shell(this.COMMAND_VERSION).then(t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""})}install(){return g(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),this.tool.install(this.id,this.app).then(()=>this.init())}start(){return this.exit().then(()=>this.shell(this.COMMAND_START))}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(){return this.tool.screencap(this.id).then(t=>new Promise(e=>{const s=[];t.on("data",(function(t){s.push(t)})),t.on("end",(function(){e(Buffer.concat(s).toString("base64"))}))}))}exists(t){return this.tool.stat(this.id,t)}pushFile(t,e){return this.tool.push(this.id,t,e)}shell(t){return g(`${a("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(w.util.readAll).then(t=>{const e=t.toString();return g(`${a("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e})}get DIR_WWW(){return`${this.sdcard}/Android/data/${this.package}/apps/${this.appid}/www`}get COMMAND_EXTERNAL(){return"echo $EXTERNAL_STORAGE"}get COMMAND_VERSION(){return"dumpsys package "+this.package}get COMMAND_STOP(){return"am force-stop "+this.package}get COMMAND_START(){return`am start -n ${this.package}/io.dcloud.PandoraEntry --es ${this.appid} --ez needUpdateApp false --ez reload true`}}const E=s("automator:devtool");let P,A=!1;const $={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>P.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(t,e)=>{const s=await P.captureScreenshot(e);return E("App.captureScreenshot "+s.length),{data:s}}}};!function(t){l.forEach(e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=i(c).processSync(t.selector)),t)}}(e)})}($);const S={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,s){if(t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),P=function(t,e){return"ios"===t?new f(e):new M(e)}(t.platform,t),await P.init(),!await P.version()){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!e.existsSync(t.executablePath))throw Error(t.executablePath+" not exists");A=!0}return t},create:async function(t,e,s){A&&await P.install(),(s.compiled||await P.shouldPush())&&await P.push(t),await P.start()}},adapter:$};module.exports=S;
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("fs")),s=t(require("debug")),i=t(require("postcss-selector-parser")),r=t(require("fs-extra")),a=t(require("licia/dateFormat")),n=require("path"),o=require("util");function l(t){t.walk(t=>{if("tag"===t.type){const e=t.value;t.value="page"===e?"body":"uni-"+e}})}require("address"),require("default-gateway"),require("licia/isStr"),require("licia/getPort");const c=["Page.getElement","Page.getElements","Element.getElement","Element.getElements"];require("qrcode-terminal"),require("qrcode-reader");const h=/^win/.test(process.platform),p=s("automator:launcher"),u=o.promisify(e.readdir),d=o.promisify(e.stat);class m{constructor(t){this.id=t.id,this.app=t.executablePath,this.appid=t.appid||"HBuilder",this.package=t.package||"io.dcloud.HBuilder"}shouldPush(){return this.exists(this.FILE_APP_SERVICE).then(()=>(p(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} exists`),!1)).catch(()=>(p(`${a("yyyy-mm-dd HH:MM:ss:l")} ${this.FILE_APP_SERVICE} not exists`),!0))}push(t){return async function t(e){const s=await u(e);return(await Promise.all(s.map(async s=>{const i=n.resolve(e,s);return(await d(i)).isDirectory()?t(i):i}))).reduce((t,e)=>t.concat(e),[])}(t).then(e=>{const s=e.map(e=>{const s=(t=>h?t.replace(/\\/g,"/"):t)(n.join(this.DIR_WWW,n.relative(t,e)));return p(`${a("yyyy-mm-dd HH:MM:ss:l")} push ${e} ${s}`),this.pushFile(e,s)});return Promise.all(s)}).then(t=>!0)}get FILE_APP_SERVICE(){return this.DIR_WWW+"/app-service.js"}}const y=s("automator:simctl");class f extends m{async init(){const t=require("node-simctl").Simctl;this.tool=new t({udid:this.id});try{await this.tool.bootDevice()}catch(t){}await this.initSDCard(),y(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id}`)}async initSDCard(){const t=(await this.tool.appInfo(this.package)).match(/DataContainer\s+=\s+"(.*)"/);if(!t)return Promise.resolve("");this.sdcard=t[1].replace("file:",""),y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.sdcard}`)}async version(){return Promise.resolve(this.sdcard?"9.6.96":"")}async install(){return y(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app}`),await this.tool.installApp(this.app),await this.tool.grantPermission(this.package,"all"),await this.initSDCard(),Promise.resolve(!0)}async start(){try{await this.tool.terminateApp(this.package),await this.tool.launchApp(this.package)}catch(t){}return Promise.resolve(!0)}async exit(){return await this.tool.terminateApp(this.package),await this.tool.shutdownDevice(),Promise.resolve(!0)}async captureScreenshot(){return Promise.resolve(await this.tool.getScreenshot())}exists(t){return r.existsSync(t)?Promise.resolve(!0):Promise.reject(Error(t+" not exists"))}pushFile(t,e){return Promise.resolve(r.copySync(t,e))}get DIR_WWW(){return`${this.sdcard}/Documents/Pandora/apps/${this.appid}/www/`}}const g=require("adbkit"),w=s("automator:adb");class M extends m{async init(){if(this.tool=g.createClient(),!this.id){const t=await this.tool.listDevices();if(!t.length)throw Error("Device not found");this.id=t[0].id}this.sdcard=(await this.shell(this.COMMAND_EXTERNAL)).trim(),w(`${a("yyyy-mm-dd HH:MM:ss:l")} init ${this.id} ${this.sdcard}`)}version(){return this.shell(this.COMMAND_VERSION).then(t=>{const e=t.match(/versionName=(.*)/);return e&&e.length>1?e[1]:""})}async install(){let t=!0;try{const e=(await this.tool.getProperties(this.id))["ro.build.version.release"].split(".")[0];parseInt(e)<6&&(t=!1)}catch(t){}if(w(`${a("yyyy-mm-dd HH:MM:ss:l")} install ${this.app} permission=${t}`),t){const t=require("adbkit/lib/adb/command.js"),e=t.prototype._send;t.prototype._send=function(t){return 0===t.indexOf("shell:pm install -r ")&&(t=t.replace("shell:pm install -r ","shell:pm install -r -g "),w(`${a("yyyy-mm-dd HH:MM:ss:l")} ${t} `)),e.call(this,t)}}return this.tool.install(this.id,this.app).then(()=>this.init())}start(){return this.exit().then(()=>this.shell(this.COMMAND_START))}exit(){return this.shell(this.COMMAND_STOP)}captureScreenshot(){return this.tool.screencap(this.id).then(t=>new Promise(e=>{const s=[];t.on("data",(function(t){s.push(t)})),t.on("end",(function(){e(Buffer.concat(s).toString("base64"))}))}))}exists(t){return this.tool.stat(this.id,t)}pushFile(t,e){return this.tool.push(this.id,t,e)}shell(t){return w(`${a("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${t}`),this.tool.shell(this.id,t).then(g.util.readAll).then(t=>{const e=t.toString();return w(`${a("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`),e})}get DIR_WWW(){return`${this.sdcard}/Android/data/${this.package}/apps/${this.appid}/www`}get COMMAND_EXTERNAL(){return"echo $EXTERNAL_STORAGE"}get COMMAND_VERSION(){return"dumpsys package "+this.package}get COMMAND_STOP(){return"am force-stop "+this.package}get COMMAND_START(){return`am start -n ${this.package}/io.dcloud.PandoraEntry --es ${this.appid} --ez needUpdateApp false --ez reload true`}}const P=s("automator:devtool");let E,$=!1;const A={"Tool.close":{reflect:async()=>{}},"App.exit":{reflect:async()=>E.exit()},"App.enableLog":{reflect:()=>Promise.resolve()},"App.captureScreenshot":{reflect:async(t,e)=>{const s=await E.captureScreenshot(e);return P("App.captureScreenshot "+s.length),{data:s}}}};!function(t){c.forEach(e=>{t[e]=function(t){return{reflect:async(e,s)=>e(t,s,!1),params:t=>(t.selector&&(t.selector=i(l).processSync(t.selector)),t)}}(e)})}(A);const v={devtools:{name:"App",paths:[],required:["manifest.json","app-service.js"],validate:async function(t,s){if(t.platform=(t.platform||process.env.UNI_OS_NAME).toLocaleLowerCase(),Object.assign(t,t[t.platform]),E=function(t,e){return"ios"===t?new f(e):new M(e)}(t.platform,t),await E.init(),!await E.version()){if(!t.executablePath)throw Error(`app-plus->${t.platform}->executablePath is not provided`);if(!e.existsSync(t.executablePath))throw Error(t.executablePath+" not exists");$=!0}return t},create:async function(t,e,s){$&&await E.install(),(s.compiled||await E.shouldPush())&&await E.push(t),await E.start()}},adapter:A};module.exports=v;
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("jest-environment-node"));const s=new(t(require("./index.js")));module.exports=class extends e{constructor(t,e){super(t),process.env.UNI_AUTOMATOR_CONFIG?this.launchOptions=require(process.env.UNI_AUTOMATOR_CONFIG):this.launchOptions=t.testEnvironmentOptions}async setup(){await super.setup();const t=global;t.program||(this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,t.program=await s.launch(this.launchOptions),this.launchOptions.devtools&&this.launchOptions.devtools.remote&&await t.program.remote(!0)),this.global.program=t.program}async teardown(){await super.teardown()}};
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var e=t(require("jest-environment-node"));const s=new(t(require("./index.js")));module.exports=class extends e{constructor(t,e){super(t),process.env.UNI_AUTOMATOR_CONFIG?this.launchOptions=require(process.env.UNI_AUTOMATOR_CONFIG):this.launchOptions=t.testEnvironmentOptions}async setup(){await super.setup();const t=global;if(t.__init__){if(!t.program)throw Error("Program init failed")}else t.__init__=!0,this.launchOptions.platform=this.launchOptions.platform||process.env.UNI_PLATFORM,t.program=await s.launch(this.launchOptions),this.launchOptions.devtools&&this.launchOptions.devtools.remote&&await t.program.remote(!0);this.global.program=t.program}async teardown(){await super.teardown()}};
{
"name": "@dcloudio/uni-automator",
"version": "2.0.0-alpha-27920200613003",
"version": "2.0.0-alpha-26920200407011",
"description": "uni-app automator",
"main": "dist/index.js",
"repository": {
......@@ -17,6 +17,7 @@
"address": "^1.1.2",
"debug": "^4.1.1",
"default-gateway": "^6.0.0",
"kill-port": "^1.6.0",
"licia": "^1.21.0",
"postcss-selector-parser": "^6.0.2",
"qrcode-reader": "^1.0.4",
......@@ -28,6 +29,5 @@
"jimp": "^0.10.1",
"node-simctl": "^6.1.0",
"puppeteer": "^3.0.1"
},
"gitHead": "e62f0398362f2f9de0bf5726046d7951c88d6b1d"
}
}
此差异已折叠。
......@@ -15,6 +15,11 @@ describe('wxml:compiler', () => {
`<uni-transition bind:click="click" bindtouchstart="startDrag" catchtouchmove="{{ catchMove ? 'noop' : '' }}"/>`,
`<uni-shadow-root><uni-transition @click="click" @touchstart.native="startDrag" @touchmove.native.stop.prevent="_$self[(catchMove ? 'noop' : '')||'_$noop']($event)"></uni-transition></uni-shadow-root>`
)
assertCodegen(
'<template name="toolbar"><view bindtap="emit"></view></template>',
// `<view @click="_$self.$parent[(emit)||'_$noop']($event)"></view>`
`<uni-shadow-root><template v-if="wxTemplateName === 'toolbar'"><view @click="_$self.$parent[('emit')]($event)"></view></template></uni-shadow-root>`
)
})
it('generate class', () => {
assertCodegen(
......@@ -63,5 +68,27 @@ describe('wxml:compiler', () => {
'<slot></slot>',
`<uni-shadow-root><slot></slot></uni-shadow-root>`
)
assertCodegen(
`<import src="./toolbar.wxml" /><view></view>
<wxs></wxs>`,
`<uni-shadow-root><view></view></uni-shadow-root>`
)
assertCodegen(
'<view><template is="toolbar" data="{{ showToolbar, cancelButtonText, title, confirmButtonText }}"></template></view>',
`<uni-shadow-root><view><toolbar v-bind="{showToolbar, cancelButtonText, title, confirmButtonText}" wx-template-name="toolbar"></toolbar></view></uni-shadow-root>`
)
assertCodegen(
'<template name="toolbar"><view></view></template>',
// `<view></view>`
`<uni-shadow-root><template v-if="wxTemplateName === 'toolbar'"><view></view></template></uni-shadow-root>`
)
assertCodegen(
'<template name="toolbar1"><view></view></template><template name="toolbar2"><view></view></template>',
`<uni-shadow-root><template v-if="wxTemplateName === 'toolbar1'"><view></view></template><template v-if="wxTemplateName === 'toolbar2'"><view></view></template></uni-shadow-root>`
)
})
})
const fs = require('fs')
const path = require('path')
const parse = require('./template-transformer/parser')
function getTemplate (content) {
const template = []
const node = parse(content)
node.children.forEach(node => {
if (node.name === 'template') {
const name = node.attribs.name
if (name) {
template.push(name)
}
}
})
return template
}
module.exports = function (filepath, options) {
filepath = path.join(path.dirname(options.filepath), filepath)
return getTemplate(fs.readFileSync(filepath, 'utf8').toString().trim())
}
\ No newline at end of file
const fs = require('fs')
const importTemplate = require('./import-template')
function transformScript(content, route, code) {
function transformScript (content, route, code) {
return `${code}
global['__wxRoute'] = '${route}'
${content}
export default global['__wxComponents']['${route}']`
}
function genJsCode(components, code, state) {
const wxTemplateComponentProps = '__wxTemplateComponentProps'
const props = state.props
const importCode = []
const propsCode = []
const componentsCode = []
components.forEach((node, index) => {
const src = node.attribs.src
const templates = importTemplate(src, state)
const identifier = `__wxTemplateComponent${index}`
importCode.push(`import ${identifier} from '${src.replace(/.wxml$/, '.vue')}'`)
templates.forEach(template => {
// TODO 改为在 template 编译时静态分析
propsCode.push(`${wxTemplateComponentProps}['${template}'] && ${wxTemplateComponentProps}['${template}'].forEach(prop => ${identifier}.props[prop] = {type: null})`)
componentsCode.push(`'${template}' : ${identifier}`)
})
})
return components.length ? `
const ${wxTemplateComponentProps} = ${JSON.stringify(props)}
${importCode.join('\n')}
${propsCode.join('\n')}
${code.trim().replace(/\}\}$/, '')},${componentsCode.join(',')}}}
`: code
}
module.exports = {
transformScript,
transformScriptFile(filepath, code, options, deps) {
let content = ''
if (options.components.length) {
code = genJsCode(options.components, code, options)
}
if (!fs.existsSync(filepath)) {
content = `
Component({})
......
......@@ -3,6 +3,12 @@ const generate = require('./generate')
module.exports = function transform(ast, options) {
options.wxs = []
options.shouldWrapper = options.shouldWrapper || function noop() {}
// wxml 中使用 import 导入的组件
options.components = []
// wxml 中使用 <template name> 声明的模板
options.templates = []
// wxml 中 <template is> 分析得到的 props
options.props = {}
options.shouldWrapper = options.shouldWrapper || function noop () { }
return generate(traverse(ast, options), options)
}
const {
parse
} = require('mustache')
const recast = require('recast')
const TAGS = [
'ad',
......@@ -163,8 +164,12 @@ function transformEvent(name, value, attribs, state) {
event = transformEventName(name.replace(captureCatchRE, ''), state) + '.stop.prevent.capture'
}
if (event !== name) {
let newValue = parseMustache(value, true)
if (newValue !== value) {
// 模板 <template name> 中用到的方法在其父组件
let newValue = parseMustache(value, !state.isTemplate)
if (state.isTemplate) {
// TODO 改为运行时判断
newValue = `_$self.$parent${process.env.UNI_PLATFORM === 'h5' ? '.$parent' : ''}[(${newValue})]($event)`
} else if (newValue !== value) {
newValue = `_$self[(${newValue})||'_$noop']($event)`
}
attribs[event] = newValue
......@@ -201,9 +206,11 @@ function transformAttrs(node, state) {
}
transformFor(attribs)
const isComponent = !TAGS.includes(node.name)
const isTemplate = state.templates.length
Object.keys(attribs).forEach(name => {
transformAttr(name, attribs[name], attribs, {
isComponent
isComponent,
isTemplate
})
})
}
......@@ -212,7 +219,40 @@ function transformChildren(node, state) {
node.children = node.children.filter(childNode => transformNode(childNode, state))
}
function transformTemplate(node, state) {
const attribs = node.attribs
if (attribs.name) {
const name = attribs.name
// 用于处理一个 wxml 文件内包含多个 template
attribs['v-if'] = `wxTemplateName === '${name}'`
delete attribs.name
state.templates.push(name)
} else if (attribs.is) {
const name = attribs.is
delete attribs.is
node.name = name
attribs['wx-template-name'] = name
const data = attribs.data
if (data && data.indexOf('{{') !== -1) {
const object = `{${parseMustache(data)}}`
attribs['v-bind'] = object
const ast = recast.parse(`const object = ${object}`)
const props = state.props[name] || ['wxTemplateName']
ast.program.body[0].declarations[0].init.properties.forEach(property => props.push(property.key.name))
state.props[name] = [...new Set(props)]
delete attribs.data
}
}
}
function transformNode(node, state) {
if (node.name === 'import') {
state.components.push(node)
return false
}
if (node.name === 'template') {
transformTemplate(node, state)
}
if (node.name === 'wxs') {
state.wxs.push(node)
return false
......
......@@ -25,6 +25,7 @@
"commander": "^4.0.1",
"fs-extra": "^8.1.0",
"mustache": "^3.1.0",
"stricter-htmlparser2": "^3.9.6"
"stricter-htmlparser2": "^3.9.6",
"recast": "*"
}
}
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("os")),r=e(require("path")),s=e(require("debug")),a=e(require("licia/isWindows")),n=e(require("fs")),o=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),p=e(require("licia/concat")),u=e(require("licia/getPort")),m=e(require("licia/dateFormat"));require("address"),require("default-gateway"),require("licia/isStr");var d=e(require("ws")),h=require("events"),f=e(require("licia/uuid")),g=e(require("licia/stringify"));const w=/(^[a-z][a-z0-9-]*)/i,y=/^navigator/i,E=/^swan-nav$/i;var b;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(b||(b={}));const v={[b.SELECTOR]:[{test:y,processor:e=>e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},P=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},j=P(b.SELECTOR),q=P(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader"),/^win/.test(process.platform);class M extends h.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",e=>{this.emit("message",e.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(e){this.ws.send(e)}close(){this.ws.close()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={stdio:"ignore"};u&&(t.cwd=u);let r=p(h,[]);r=p(r,["--auto"]),r=p(r,[e,"--auto-port",c(s)]),d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return r.compiled?s("automator:devtool")("Waiting for runtime automator"):(s("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(r=t.selector,r.split(" ").map(e=>j(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T;
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("os")),r=e(require("path")),s=e(require("debug")),a=e(require("licia/isWindows")),n=e(require("fs")),o=e(require("child_process")),i=e(require("licia/sleep")),c=e(require("licia/toStr")),l=e(require("licia/waitUntil")),p=e(require("licia/concat")),u=e(require("licia/getPort")),m=e(require("licia/dateFormat"));require("address"),require("default-gateway"),require("licia/isStr");var d=e(require("ws")),h=require("events"),f=e(require("licia/uuid")),g=e(require("licia/stringify"));const w=/(^[a-z][a-z0-9-]*)/i,y=/^navigator/i,E=/^swan-nav$/i;var b;!function(e){e.SELECTOR="selector",e.TAGNAME="tagName"}(b||(b={}));const v={[b.SELECTOR]:[{test:y,processor:e=>e.replace(y,"nav")},{test:w,processor:e=>"swan-"+e}],[b.TAGNAME]:[{test:E,processor:e=>e.replace(E,"swan-navigator")},{test:w,processor:e=>e.toLocaleLowerCase().replace("swan-","")}]},P=e=>t=>{const r=(v[e]||[]).filter(e=>e.test.test(t));for(const e of r)t=e.processor(t);return t},j=P(b.SELECTOR),q=P(b.TAGNAME),O=e=>Object.assign({},e,{type:"id",info:{id:e.elementId}});require("qrcode-terminal"),require("qrcode-reader"),/^win/.test(process.platform);class M extends h.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",e=>{this.emit("message",e.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(e){this.ws.send(e)}close(){this.ws.close()}}class C extends h.EventEmitter{constructor(e,t,r){super(),this.puppet=t,this.namespace=r,this.callbacks=new Map,this.transport=e,this.debug=s("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:s,result:a,params:n}=JSON.parse(e);if(!t)return this.puppet.emit(r,n);const{callbacks:o}=this;if(t&&o.has(t)){const e=o.get(t);o.delete(t),s?e.reject(Error(s.message)):e.resolve(a)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const s=f(),a=g({id:s,method:e,params:t});return this.debug(`${m("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${a}`),new Promise((e,t)=>{try{this.transport.send(a)}catch(e){t(Error("Connection closed"))}this.callbacks.set(s,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,s)=>{const a=new d(e);a.addEventListener("open",()=>{r(new C(new M(a),t,"devtool"))}),a.addEventListener("error",s)})}static createRuntimeConnection(e,t,r){return new Promise((a,n)=>{s("automator:runtime")(`${m("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const o=new d.Server({port:e});l(async()=>{if(t.runtimeConnection)return!0},r,1e3).catch(()=>{o.close(),n("Failed to connect to runtime, please make sure the project is running")}),o.on("connection",(function(e){s("automator:runtime")(m("yyyy-mm-dd HH:MM:ss:l")+" connected");const r=new C(new M(e),t,"runtime");t.setRuntimeConnection(r),a(r)})),t.setRuntimeServer(o)})}}const $=s("automator:devtool");async function S(e,t,r){const{port:s,cliPath:a,timeout:n,cwd:u="",account:d="",args:h=[],launch:f=!0}=t;let g=!1,w=!1;if(!1!==f){const t={stdio:"ignore"};u&&(t.cwd=u);let r=p(h,[]);r=p(r,["--auto"]),r=p(r,[e,"--auto-port",c(s)]),d&&(r=p(r,["--auto-account",d]));try{$("%s %o %o",a,r,t);const e=o.spawn(a,r,t);e.on("error",e=>{g=!0}),e.on("exit",()=>{setTimeout(()=>{w=!0},15e3)}),e.unref()}catch(e){g=!1}}else setTimeout(()=>{w=!0},15e3);const y=await l(async()=>{try{if(g||w)return!0;return await async function(e,t){let r;try{r=await C.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+s},r)}catch(e){}},n,1e3);if(g)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(w)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await i(5e3),$(m("yyyy-mm-dd HH:MM:ss:l")+" connected"),y}const A=[];["","-rc"].forEach(e=>{a?(A.push(r.join(t.homedir(),`AppData/Local/Programs/swan-ide-gui${e}/cli.bat`)),A.push(`C:/Program Files/swan-ide-gui${e}/cli.bat`)):A.push(`/Applications/百度开发者工具${e}.app/Contents/MacOS/cli`)});const T={devtools:{name:"Baidu DevTools",remote:!0,automator:!0,paths:A,required:["project.swan.json","app.json","app.js"],defaultPort:9430,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await u(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await u(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,t,r){const a=await S(e,t,r);return r.compiled?s("automator:devtool")("Waiting for runtime automator"):(s("automator:devtool")("initRuntimeAutomator"),a.send("smartapp.swan",{api:"$$initRuntimeAutomator",params:[]})),a}},adapter:{"Tool.enableRemoteDebug":{reflect:async e=>({qrCode:(await e("Tool.enablePreview")).url})},"App.exit":{reflect:async()=>Promise.resolve()},"Page.getElement":{reflect:async(e,t)=>(await e("Page.getElements",t)).elements[0]},"Page.getElements":{reflect:async(e,t)=>{return{elements:(await e("smartapp.element.getBySelector",Object.assign(Object.assign({},t),{properties:["id","tagName"],selector:(r=t.selector,r.split(" ").map(e=>j(e)).join(" "))}))).map(e=>{const t=e.properties;return{elementId:t.id,nodeId:t.id,tagName:q(t.tagName)}})};var r}},"Page.getWindowProperties":{reflect:async(e,t)=>{const r=t.names.map(e=>e.replace("document.documentElement.","")),s=(await e("smartapp.element.getBySelector",{properties:r,selector:"html"}))[0];return{properties:r.map(e=>s.properties[e])}}},"Element.getHTML":{reflect:async(e,t)=>{const r=[t.type+"HTML"];return{html:(await e("Element.getDOMProperties",Object.assign(Object.assign({},t),{names:r}))).properties[0]}}},"Element.getElement":{reflect:async(e,t)=>(await e("Element.getElements",t)).elements[0]},"Element.getElements":{reflect:async(e,t)=>{const{elements:r}=await e("Page.getElements",Object.assign(Object.assign({},t),{selector:`#${t.elementId} ${t.selector}`}));return r.forEach(e=>{e.nodeId=e.id}),{elements:r}}},"Element.getAttributes":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{attributes:r}},params:O},"Element.getStyles":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getComputedStyle",Object.assign({style:s},t)));return{styles:r}},params:O},"Element.getDOMProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getProperty",Object.assign({property:s},t)));return{properties:r}},params:O},"Element.getProperties":{reflect:async(e,t)=>{const r=[];for(const s of t.names)r.push(await e("smartapp.element.getAttribute",Object.assign({attribute:s},t)));return{properties:r}},params:O},"Element.getOffset":{reflect:async(e,t)=>({left:await e("smartapp.element.getProperty",Object.assign({property:"offsetLeft"},t)),top:await e("smartapp.element.getProperty",Object.assign({property:"offsetTop"},t))}),params:O},"Element.tap":{reflect:"smartapp.element.touch",params:O}}};module.exports=T;
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows"));require("address"),require("default-gateway"),require("licia/isStr");var o=e(require("licia/getPort")),n=e(require("fs")),s=e(require("child_process")),a=e(require("licia/sleep")),i=e(require("licia/toStr")),c=e(require("licia/waitUntil")),u=e(require("licia/concat")),l=e(require("licia/dateFormat")),d=e(require("ws")),p=require("events"),m=e(require("licia/uuid")),h=e(require("licia/stringify"));require("qrcode-terminal");const w=require("qrcode-reader");/^win/.test(process.platform);class f extends p.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",e=>{this.emit("message",e.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(e){this.ws.send(e)}close(){this.ws.close()}}class y extends p.EventEmitter{constructor(e,r,o){super(),this.puppet=r,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:o,result:n,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:a}=this;if(t&&a.has(t)){const e=a.get(t);a.delete(t),o?e.reject(Error(o.message)):e.resolve(n)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=m(),n=h({id:o,method:e,params:t});return this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise((e,t)=>{try{this.transport.send(n)}catch(e){t(Error("Connection closed"))}this.callbacks.set(o,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,o)=>{const n=new d(e);n.addEventListener("open",()=>{r(new y(new f(n),t,"devtool"))}),n.addEventListener("error",o)})}static createRuntimeConnection(e,r,o){return new Promise((n,s)=>{t("automator:runtime")(`${l("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new d.Server({port:e});c(async()=>{if(r.runtimeConnection)return!0},o,1e3).catch(e=>{throw Error("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(e){t("automator:runtime")(l("yyyy-mm-dd HH:MM:ss:l")+" connected");const o=new y(new f(e),r,"runtime");r.setRuntimeConnection(o),n(o)})),r.setRuntimeServer(a)})}}const g=t("automator:devtool");async function v(e,t,r){const{port:o,cliPath:n,timeout:d,cwd:p="",account:m="",args:h=[],launch:w=!0}=t;let f=!1,v=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=u(h,[]);r=u(r,["auto","--project"]),r=u(r,[e,"--auto-port",i(o)]),m&&(r=u(r,["--auto-account",m]));try{g("%s %o %o",n,r,t);const e=s.spawn(n,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{v=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{v=!0},15e3);const b=await c(async()=>{try{if(f||v)return!0;return await async function(e,t){let r;try{r=await y.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+o},r)}catch(e){}},d,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(v)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),g(l("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const b={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await o(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,r,o){const n=await v(e,r,o);return o.compiled?t("automator:devtool")("Waiting for runtime automator"):(t("automator:devtool")("initRuntimeAutomator"),n.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),n}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await require("jimp").read(t),n=new w;n.callback=function(t,o){if(t)return r(t);e(o.result)},n.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=b;
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("debug")),r=e(require("licia/isWindows"));require("address"),require("default-gateway"),require("licia/isStr");var o=e(require("licia/getPort")),n=e(require("fs")),s=e(require("child_process")),a=e(require("licia/sleep")),i=e(require("licia/toStr")),c=e(require("licia/waitUntil")),u=e(require("licia/concat")),l=e(require("licia/dateFormat")),d=e(require("ws")),p=require("events"),m=e(require("licia/uuid")),h=e(require("licia/stringify"));require("qrcode-terminal");const w=require("qrcode-reader");/^win/.test(process.platform);class f extends p.EventEmitter{constructor(e){super(),this.ws=e,this.ws.addEventListener("message",e=>{this.emit("message",e.data)}),this.ws.addEventListener("close",()=>{this.emit("close")})}send(e){this.ws.send(e)}close(){this.ws.close()}}class y extends p.EventEmitter{constructor(e,r,o){super(),this.puppet=r,this.namespace=o,this.callbacks=new Map,this.transport=e,this.debug=t("automator:protocol:"+this.namespace),this.onMessage=e=>{this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} ◀ RECV ${e}`);const{id:t,method:r,error:o,result:n,params:s}=JSON.parse(e);if(!t)return this.puppet.emit(r,s);const{callbacks:a}=this;if(t&&a.has(t)){const e=a.get(t);a.delete(t),o?e.reject(Error(o.message)):e.resolve(n)}},this.onClose=()=>{this.callbacks.forEach(e=>{e.reject(Error("Connection closed"))})},this.transport.on("message",this.onMessage),this.transport.on("close",this.onClose)}send(e,t={},r=!0){if(r&&this.puppet.adapter.has(e))return this.puppet.adapter.send(this,e,t);const o=m(),n=h({id:o,method:e,params:t});return this.debug(`${l("yyyy-mm-dd HH:MM:ss:l")} SEND ► ${n}`),new Promise((e,t)=>{try{this.transport.send(n)}catch(e){t(Error("Connection closed"))}this.callbacks.set(o,{resolve:e,reject:t})})}dispose(){this.transport.close()}static createDevtoolConnection(e,t){return new Promise((r,o)=>{const n=new d(e);n.addEventListener("open",()=>{r(new y(new f(n),t,"devtool"))}),n.addEventListener("error",o)})}static createRuntimeConnection(e,r,o){return new Promise((n,s)=>{t("automator:runtime")(`${l("yyyy-mm-dd HH:MM:ss:l")} port=${e}`);const a=new d.Server({port:e});c(async()=>{if(r.runtimeConnection)return!0},o,1e3).catch(()=>{a.close(),s("Failed to connect to runtime, please make sure the project is running")}),a.on("connection",(function(e){t("automator:runtime")(l("yyyy-mm-dd HH:MM:ss:l")+" connected");const o=new y(new f(e),r,"runtime");r.setRuntimeConnection(o),n(o)})),r.setRuntimeServer(a)})}}const g=t("automator:devtool");async function v(e,t,r){const{port:o,cliPath:n,timeout:d,cwd:p="",account:m="",args:h=[],launch:w=!0}=t;let f=!1,v=!1;if(!1!==w){const t={stdio:"ignore",detached:!0};p&&(t.cwd=p);let r=u(h,[]);r=u(r,["auto","--project"]),r=u(r,[e,"--auto-port",i(o)]),m&&(r=u(r,["--auto-account",m]));try{g("%s %o %o",n,r,t);const e=s.spawn(n,r,t);e.on("error",e=>{f=!0}),e.on("exit",()=>{setTimeout(()=>{v=!0},15e3)}),e.unref()}catch(e){f=!1}}else setTimeout(()=>{v=!0},15e3);const b=await c(async()=>{try{if(f||v)return!0;return await async function(e,t){let r;try{r=await y.createDevtoolConnection(e.wsEndpoint,t)}catch(t){throw Error(`Failed connecting to ${e.wsEndpoint}, check if target project window is opened with automation enabled`)}return r}({wsEndpoint:"ws://127.0.0.1:"+o},r)}catch(e){}},d,1e3);if(f)throw Error(`Failed to launch ${r.devtools.name}, please make sure cliPath is correctly specified`);if(v)throw Error(`Failed to launch ${r.devtools.name} , please make sure http port is open`);return await a(5e3),g(l("yyyy-mm-dd HH:MM:ss:l")+" connected"),b}const b={devtools:{name:"Wechat web devTools",remote:!0,automator:!0,paths:[r?"C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat":"/Applications/wechatwebdevtools.app/Contents/MacOS/cli"],required:["project.config.json","app.json","app.js"],defaultPort:9420,validate:async function(e,t){const r=function(e,t){const r=t.devtools.paths.slice(0);e&&r.unshift(e);for(const e of r)if(n.existsSync(e))return e;throw Error(t.devtools.name+" not found, please specify executablePath option")}(e.executablePath,t);let s=e.port||t.devtools.defaultPort;if(!1!==e.launch)try{s=await async function(e,t){const r=await o(e||t);if(e&&r!==e)throw Error(`Port ${e} is in use, please specify another port`);return r}(s)}catch(t){e.launch=!1}else{s===await o(s)&&(e.launch=!0)}return Object.assign(Object.assign({},e),{port:s,cliPath:r})},async create(e,r,o){const n=await v(e,r,o);return o.compiled?t("automator:devtool")("Waiting for runtime automator"):(t("automator:devtool")("initRuntimeAutomator"),n.send("App.callWxMethod",{method:"$$initRuntimeAutomator",args:[]})),n}},adapter:{"Tool.enableRemoteDebug":{reflect:async(e,t)=>{let{qrCode:r}=await e("Tool.enableRemoteDebug",t,!1);return r&&(r=await function(e){const t=new Buffer(e,"base64");return new Promise(async(e,r)=>{const o=await require("jimp").read(t),n=new w;n.callback=function(t,o){if(t)return r(t);e(o.result)},n.decode(o.bitmap)})}(r)),{qrCode:r}}},"App.callFunction":{reflect:async(e,t)=>{return e("App.callFunction",Object.assign(Object.assign({},t),{functionDeclaration:(r=t.functionDeclaration,"}"===r[r.length-1]?r.replace("{","{\nvar uni = wx;\n"):r.replace("=>","=>{\nvar uni = wx;\nreturn ")+"}")}),!1);var r}},"Element.getHTML":{reflect:async(e,t)=>({html:(await e("Element.getWXML",t,!1)).wxml})}}};module.exports=b;
......@@ -55,24 +55,23 @@ module.exports = function generateApp (compilation) {
const runtimeJsPath = 'common/runtime.js'
const asset = compilation.assets[runtimeJsPath]
if ( // app 和 baidu 不需要
process.env.UNI_PLATFORM !== 'app-plus' &&
process.env.UNI_PLATFORM !== 'mp-baidu' &&
compilation.assets[runtimeJsPath]
asset &&
!asset.source.__$wrappered
) {
const source =
`
!function(){try{var a=Function("return this")();a&&!a.Math&&(Object.assign(a,{isFinite:isFinite,Array:Array,Date:Date,Error:Error,Function:Function,Math:Math,Object:Object,RegExp:RegExp,String:String,TypeError:TypeError,setTimeout:setTimeout,clearTimeout:clearTimeout,setInterval:setInterval,clearInterval:clearInterval}),"undefined"!=typeof Reflect&&(a.Reflect=Reflect))}catch(a){}}();
${compilation.assets[runtimeJsPath].source()}
${asset.source()}
`
compilation.assets[runtimeJsPath] = {
size () {
return Buffer.byteLength(source, 'utf8')
},
source () {
const newSource = function () {
return source
}
}
newSource.__$wrappered = true
compilation.assets[runtimeJsPath].source = newSource
}
const specialMethods = getSpecialMethods()
......
......@@ -12,6 +12,8 @@ const {
restoreNodeModules
} = require('../shared')
const EMPTY_COMPONENT_LEN = 'Component({})'.length
const uniPath = normalizePath(require.resolve('@dcloudio/uni-' + process.env.UNI_PLATFORM))
function findModule (modules, resource, altResource) {
......@@ -66,6 +68,11 @@ module.exports = function generateComponent (compilation) {
Object.keys(assets).forEach(name => {
if (components.has(name.replace('.js', ''))) {
curComponents.push(name.replace('.js', ''))
if (assets[name].source.__$wrappered) {
return
}
const chunkName = name.replace('.js', '-create-component')
let moduleId = ''
......@@ -80,7 +87,7 @@ module.exports = function generateComponent (compilation) {
}
const origSource = assets[name].source()
if (origSource.length !== 'Component({})'.length) { // 不是空组件
if (origSource.length !== EMPTY_COMPONENT_LEN) { // 不是空组件
const globalVar = process.env.UNI_PLATFORM === 'mp-alipay' ? 'my' : 'global'
// 主要是为了解决支付宝旧版本, Component 方法只在组件 js 里有,需要挂在 my.defineComponent
let beforeCode = ''
......@@ -99,14 +106,11 @@ module.exports = function generateComponent (compilation) {
[['${chunkName}']]
]);
`
assets[name] = {
size () {
return Buffer.byteLength(source, 'utf8')
},
source () {
const newSource = function () {
return source
}
}
newSource.__$wrappered = true
assets[name].source = newSource
}
}
})
......
......@@ -15,7 +15,7 @@ class UploadTask {
}
abort () {
invokeMethod('operateRequestTask', {
invokeMethod('operateUploadTask', {
uploadTaskId: this.id,
operationType: 'abort'
})
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册