UNPKG

@mitojs/utils

Version:
2 lines (1 loc) 11.6 kB
var MITO=function(e){"use strict";var n=function(){return(n=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var o in n=arguments[t])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)};function t(e,n,t){if(t||2===arguments.length)for(var r,o=0,i=n.length;o<i;o++)!r&&o in n||(r||(r=Array.prototype.slice.call(n,0,o)),r[o]=n[o]);return e.concat(r||Array.prototype.slice.call(n))}var r=Object.prototype.toString;function o(e){return function(n){return r.call(n)==="[object "+e+"]"}}var i={isNumber:o("Number"),isString:o("String"),isBoolean:o("Boolean"),isNull:o("Null"),isUndefined:o("Undefined"),isSymbol:o("Symbol"),isFunction:o("Function"),isObject:o("Object"),isArray:o("Array"),isProcess:o("process"),isWindow:o("Window")};function a(e,n){try{return e instanceof n}catch(e){return!1}}var c=i.isProcess("undefined"!=typeof process?process:0),s=i.isObject("undefined"!=typeof wx?wx:0)&&i.isFunction("undefined"!=typeof App?App:0),u=i.isWindow("undefined"!=typeof window?window:0);function l(){return u?window:s?wx:c?process:void 0}var f=l(),p=(f.__MITO__=f.__MITO__||{},f.__MITO__);var d="MITO Logger",g=function(){function e(){var e=this;if(this.enabled=!1,this._console={},f.console=console||f.console,console||f.console){["log","debug","info","warn","error","assert"].forEach((function(n){n in f.console&&(e._console[n]=f.console[n])}))}}return e.prototype.disable=function(){this.enabled=!1},e.prototype.bindOptions=function(e){this.enabled=!!e},e.prototype.enable=function(){this.enabled=!0},e.prototype.getEnableStatus=function(){return this.enabled},e.prototype.log=function(){for(var e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];this.enabled&&(e=this._console).log.apply(e,t([d+"[Log]:"],n,!1))},e.prototype.warn=function(){for(var e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];this.enabled&&(e=this._console).warn.apply(e,t([d+"[Warn]:"],n,!1))},e.prototype.error=function(){for(var e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];(e=this._console).error.apply(e,t([d+"[Error]:"],n,!1))},e}(),h=p.logger||(p.logger=new g);function y(){return"undefined"==typeof document||null==document.location?"":document.location.href}function m(){return s?S():u?y():""}function v(){return Date.now()}function b(e,n){return r.call(e)==="[object "+n+"]"}function O(e,n,t){return!!b(e,t)||(void 0!==e&&h.error(n+"期望传入:"+t+"类型,当前是:"+r.call(e)+"类型"),!1)}function x(e,n){var t=[];return Object.keys(n).forEach((function(e){t.push(e+"="+n[e])})),e=-1!==e.indexOf("?")?e+"&"+t.join("&"):e+"?"+t.join("&")}function S(){if(!i.isFunction(getCurrentPages))return"";var e=getCurrentPages();if(!e.length)return"App";var n=e.pop();return x(n.route,n.options)}var w,N=function(){function e(){this.stack=[],this.isFlushing=!1,"Promise"in f&&(this.micro=Promise.resolve())}return e.prototype.addTask=function(e){var n=this;"function"==typeof e&&("Promise"in f?(this.stack.push(e),this.isFlushing||(this.isFlushing=!0,this.micro.then((function(){return n.flushStack()})))):e())},e.prototype.clear=function(){this.stack=[]},e.prototype.getStack=function(){return this.stack},e.prototype.flushStack=function(){var e=this.stack.slice(0);this.stack.length=0,this.isFlushing=!1;for(var n=0,t=e;n<t.length;n++){(0,t[n])()}},e}();e.Severity=void 0,(w=e.Severity||(e.Severity={})).Else="else",w.Error="error",w.Warning="warning",w.Info="info",w.Debug="debug",w.Low="low",w.Normal="normal",w.High="high",w.Critical="critical",function(e){e.fromString=function(n){switch(n){case"debug":return e.Debug;case"info":case"log":case"assert":return e.Info;case"warn":case"warning":return e.Warning;case e.Low:case e.Normal:case e.High:case e.Critical:case"error":return e.Error;default:return e.Else}}}(e.Severity||(e.Severity={}));var _={};function j(e){return Object.keys(e).sort().reduce((function(n,t){return i.isObject(e[t])?n[t]=j(e[t]):n[t]=e[t],n}),{})}function E(e){try{if(/\{.*\}/.test(e)){var n=JSON.parse(e);return n=j(n),JSON.stringify(n)}return e}catch(n){return e}}function T(e){return e.replace(/[?#].*$/,"").replace(/\/(\d+)\//g,"/{param}/$1").replace(/\/\d+([/]*$)/g,"/{param}$1")}function k(e){return e.replace(/(\S+)(\/Documents\/)(\S*)/,"$3")}function C(e){return e.replace(/(\S+)(\/#\/)(\S*)/,"$1")}function I(e){var n=0;if(0==e.length)return n;for(var t=0;t<e.length;t++){n=(n<<5)-n+e.charCodeAt(t),n&=n}return n}return e.Logger=g,e.Queue=N,e._global=f,e._support=p,e.createErrorId=function(e,n,t){var r;switch(e.type){case"HTTP":r=e.type+e.request.method+e.response.status+T(e.request.url)+n;break;case"JAVASCRIPT":case"VUE":case"REACT":r=e.type+e.name+e.message+n;break;case"LOG":r=e.customTag+e.type+e.name+n;break;case"PROMISE":r=function(e,n){var t=T(e.url);if("unhandledrejection"===e.name)return e.type+E(e.message)+n;return e.type+e.name+E(e.message)+t}(e,n);break;default:r=e.type+e.message+n}return r=I(r),_[r]>=t?null:("number"==typeof _[r]?_[r]++:_[r]=1,r)},e.defaultFunctionName="<anonymous>",e.extractErrorStack=function(e,t){var r={time:v(),url:m(),name:e.name,level:t,message:e.message};if(void 0===e.stack||!e.stack)return r;for(var o,i,a,c=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,s=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,l=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,f=/\((\S*)(?::(\d+))(?::(\d+))\)/,p=e.stack.split("\n"),d=[],g=0,h=p.length;g<h;++g){if(i=c.exec(p[g])){var y=i[2]&&0===i[2].indexOf("native");i[2]&&0===i[2].indexOf("eval")&&(o=f.exec(i[2]))&&(i[2]=o[1],i[3]=o[2],i[4]=o[3]),a={url:y?null:i[2],func:i[1]||"UNKNOWN_FUNCTION",args:y?[i[2]]:[],line:i[3]?+i[3]:null,column:i[4]?+i[4]:null}}else if(i=u.exec(p[g]))a={url:i[2],func:i[1]||"UNKNOWN_FUNCTION",args:[],line:+i[3],column:i[4]?+i[4]:null};else{if(!(i=s.exec(p[g])))continue;i[3]&&i[3].indexOf(" > eval")>-1&&(o=l.exec(i[3]))?(i[3]=o[1],i[4]=o[2],i[5]=null):0!==g||i[5]||void 0===e.columnNumber||(d[0].column=e.columnNumber+1),a={url:i[3],func:i[1]||"UNKNOWN_FUNCTION",args:i[2]?i[2].split(","):[],line:i[4]?+i[4]:null,column:i[5]?+i[5]:null}}!a.func&&a.line&&(a.func="UNKNOWN_FUNCTION"),d.push(a)}return d.length?n(n({},r),{stack:d}):null},e.firstStrtoLowerCase=function(e){return e.replace(/\b(\w)(\w*)/g,(function(e,n,t){return""+n.toLowerCase()+t}))},e.firstStrtoUppercase=function(e){return e.replace(/\b(\w)(\w*)/g,(function(e,n,t){return""+n.toUpperCase()+t}))},e.fromHttpStatus=function(e){if(e<400)return"ok";if(e>=400&&e<500)switch(e){case 401:return"unauthenticated";case 403:return"permission_denied";case 404:return"not_found";case 409:return"already_exists";case 413:return"failed_precondition";case 429:return"resource_exhausted";default:return"invalid_argument"}if(e>=500&&e<600)switch(e){case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline_exceeded";default:return"internal_error"}return"unknown_error"},e.generateUUID=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(n){var t=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==n?t:3&t|8).toString(16)}))},e.getAppId=function(){return wx.getAccountInfoSync().miniProgram.appId},e.getBigVersion=function(e){return Number(e.split(".")[0])},e.getBreadcrumbCategoryInBrowser=function(e){switch(e){case"Xhr":case"Fetch":return"http";case"UI.Click":case"Route":return"user";case"Customer":case"Console":return"debug";case"Unhandledrejection":case"Code Error":case"Resource":default:return"exception"}},e.getBreadcrumbCategoryInWx=function(e){switch(e){case"Xhr":return"http";case"Route":case"UI.Tap":case"UI.Touchmove":return"user";case"Customer":case"Console":return"debug";case"App On Launch":case"App On Show":case"App On Hide":case"Page On Load":case"Page On Show":case"Page On Ready":case"Page On Hide":case"Page On Share App Message":case"Page On Share Timeline":case"Page On Tab Item Tap":return"lifecycle";case"Unhandledrejection":case"Code Error":case"Resource":case"Vue":case"React":default:return"exception"}},e.getCurrentRoute=S,e.getFlutterRealOrigin=function(e){return C(k(e))},e.getFlutterRealPath=k,e.getFunctionName=function(e){return e&&"function"==typeof e&&e.name||"<anonymous>"},e.getGlobal=l,e.getLocationHref=y,e.getObjectWithForIn=function(e){if(!i.isObject(e))return e;var n={};for(var t in e)n[t]=e[t];return n},e.getRealPath=T,e.getTimestamp=v,e.getUrlWithEnv=m,e.hashCode=I,e.htmlElementAsString=function(e){var n=e.tagName.toLowerCase();if("body"===n)return null;var t=e.classList.value;return t=""!==t?' class="'+t+'"':"","<"+n+(e.id?' id="'+e.id+'"':"")+(""!==t?t:"")+">"+e.innerText+"</"+n+">"},e.interceptStr=function(e,n){return i.isString(e)?e.slice(0,n)+(e.length>n?";slice the first "+n+" characters":""):""},e.isBrowserEnv=u,e.isEmpty=function(e){return i.isString(e)&&""===e.trim()||null==e},e.isEmptyObject=function(e){return i.isObject(e)&&0===Object.keys(e).length},e.isError=function(e){switch(r.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return a(e,Error)}},e.isExistProperty=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},e.isInclude=function(e,n){return!!~e.indexOf(n)},e.isInstanceOf=a,e.isNodeEnv=c,e.isType=o,e.isWxMiniEnv=s,e.logger=h,e.nativeToString=r,e.nativeTryCatch=function(e,n){try{e()}catch(e){console.error("err",e),n&&n(e)}},e.on=function(e,n,t,r){void 0===r&&(r=!1),e.addEventListener(n,t,r)},e.parseErrorString=function(e){var n=e.split("\n");if(n.length<2)return null;-1!==n[0].indexOf("MiniProgramError")&&n.splice(0,1);var t=n.splice(0,1)[0],r=n.splice(0,1)[0].split(":")[0],o=[];return n.forEach((function(e){var n=/at\s+([\S]+)\s+\(/.exec(e),t=/\(([^)]+)\)/.exec(e);t||(t=/\s+at\s+(\S+)/.exec(e));var r=Array.isArray(n)&&n.length>0?n[1].trim():"",i=(Array.isArray(t)&&t.length>0?t[1]:"").split(":");o.push({args:[],func:r||"UNKNOWN_FUNCTION",column:Number(i.pop()),line:Number(i.pop()),url:i.join(":")})})),{message:t,name:r,stack:o}},e.parseUrlToObj=function(e){if(!e)return{};var n=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!n)return{};var t=n[6]||"",r=n[8]||"";return{host:n[4],path:n[5],protocol:n[2],relative:n[5]+t+r}},e.removeHashPath=C,e.replaceOld=function(e,n,t,r){if(void 0===r&&(r=!1),void 0!==e&&(n in e||r)){var o=t(e[n]);"function"==typeof o&&(e[n]=o)}},e.safeStringify=function(e){var n=new Set,t=JSON.stringify(e,(function(e,t){return n.has(t)?"Circular":("object"==typeof t&&n.add(t),t)}));return n.clear(),t},e.setUrlQuery=x,e.silentConsoleScope=function(e){e()},e.sleepRun=function(e,n){void 0===n&&(n=200),setTimeout((function(){e()}),n)},e.sortObjByKey=j,e.stringToObjAndOrder=E,e.supportsHistory=function(){var e=f.chrome,n=e&&e.app&&e.app.runtime,t="history"in f&&!!f.history.pushState&&!!f.history.replaceState;return!n&&t},e.throttle=function(e,n){var t=!0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];t&&(e.apply(this,r),t=!1,setTimeout((function(){t=!0}),n))}},e.toStringAny=b,e.toStringValidateOption=O,e.unknownToString=function(e){return i.isString(e)?e:i.isUndefined(e)?"undefined":JSON.stringify(e)},e.validateOptionsAndSet=function(e){var n=this;e.forEach((function(e){var t=e[0],r=e[1];return O(t,r,e[2])&&(n[r]=t)}))},e.variableTypeDetection=i,Object.defineProperty(e,"__esModule",{value:!0}),e}({});