jinbi-utils
Version:
这是一个实用工具库,包含了多个常用的功能模块。以下是各个模块的详细说明:
16 lines (13 loc) • 18.2 kB
JavaScript
import e from"axios";var t={isWxWork:"wecom",isWeixin:"wechat",isMobile:"mobile",isMobileAny:"mobile"};function r(e){return null===e||""===e||void 0===e}var n=function(){localStorage.removeItem("wecom_userinfo"),localStorage.removeItem("wecom_token"),localStorage.removeItem("projectActive"),localStorage.removeItem("loginTime"),localStorage.removeItem("projectInfo")},o=function(e,t){var r=new RegExp("&{1}"+t+"\\=[a-zA-Z0-9_-]+","g"),n=e.replace(/\?/g,"&").match(r)[0];return n.substr(n.indexOf("=")+1)},i=function(e){for(var t=window.location.search.substring(1).split("&"),r=0;r<t.length;r++){var n=t[r].split("=");if(n[0]===e)return n[1]}return!1},a=function(){return localStorage.getItem("wecom_token")},u=function(){var e=navigator.userAgent.toLowerCase(),t=/wxwork/.test(e),r=/micromessenger/.test(e)&&!t,n=window.innerWidth<=768;return{isWxWork:t,isWeixin:r,isMobileScreen:n,isMobileAny:t||r||n}},c=function(e){var r="wecom";for(var n in e){if(e[n]){r=t[n];break}}return r};function s(e){e=e||32;for(var t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",r=t.length,n="",o=0;o<e;o++)n+=t.charAt(Math.floor(Math.random()*r));return n}var l=function(e){for(var t="",r=document.cookie.split("; "),n=0;n<r.length;n++){var o=r[n].split("=");if(o[0]===e){t=o[1];break}}return t},f=function(){for(var e=[],t=0;t<=15;t++)e[t]=t.toString(16);var r="";for(t=1;t<=36;t++)r+=9===t||14===t||19===t||24===t?"-":15===t?4:20===t?e[4*Math.random()|8]:e[16*Math.random()|0];return r.replace(/-/g,"")},d=function(){return localStorage.getItem("jsapiTicket")},g=function(e){return localStorage.setItem("jsapiTicket",e)},p=function(){return localStorage.removeItem("jsapiTicket")},h=function(e,t){if(void 0===t&&(t="YYYY年MM月DD日 hh:mm:ss"),!e)return"-";var r=new Date(e),n=r.getFullYear()+"",o=r.getMonth()+1,i=r.getDate(),a=r.getHours()>9?r.getHours():"0"+r.getHours(),u=r.getMinutes()>9?r.getMinutes():"0"+r.getMinutes(),c=r.getSeconds()>9?r.getSeconds():"0"+r.getSeconds();return t.replace("YYYY",n+"").replace("MM",o+"").replace("DD",i+"").replace("hh",a+"").replace("mm",u+"").replace("ss",c+"")},v=function(e){for(var t=window.atob(e.split(",")[1]),r=new ArrayBuffer(t.length),n=new Uint8Array(r),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return new Blob([r],{type:"image/png"})},m=function(){var e=window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i),t=/micromessenger/i.test(navigator.userAgent),r=/wxwork/i.test(navigator.userAgent);return r&&e?"com-wx-mobile":r&&!e?"com-wx-pc":t&&e?"wx-mobile":t&&!e?"wx-pc":"other"},w=function(){return/wxwork/i.test(navigator.userAgent)},y=function(){var e=!1;return"uat2-h5-wecom.hengdayun.com"!==location.origin&&"127.0.0.1:8081"!==location.origin&&"localhost:8081"!==location.origin||(e=!0),e},b=function(e,t){var r=new Set;return e.filter((function(e){var n=e[t];return!r.has(n)&&(r.add(n),!0)}))},S=function(e){for(var t=e.split(","),r=t[0].match(/:(.\*?);/)[1],n=atob(t[1]),o=n.length,i=new Uint8Array(o);o--;)i[o]=n.charCodeAt(o);return new Blob([i],{type:r})},M=function(e,t){for(var r=e.split(","),n=r[0].match(/:(.*);/)[1],o=atob(r[1]),i=o.length,a=new Uint8Array(i);i--;)a[i]=o.charCodeAt(i);return new File([a],t,{type:n})},A=function(e){return/^image\//i.test(e)},C=function(e){var t=e.split(","),r=t[0],n=void 0===r?"":r,o=t[1],i=void 0===o?"":o;return{name:decodeURIComponent(n),url:decodeURIComponent(i)}},R=function(e){return!e||""===e||/^(\d+)(\.\d{1,2})?$/.test(e.toString())},k=function(e,t){var r,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),o=[];if(t=t||n.length,e)for(r=0;r<e;r++)o[r]=n[0|Math.random()*t];else{var i=void 0;for(o[8]=o[13]=o[18]=o[23]="-",o[14]="4",r=0;r<36;r++)o[r]||(i=0|16*Math.random(),o[r]=n[19==r?3&i|8:i])}return o.join("")},x=function(e,t){var r=e.toLowerCase();return"localstorage"===r?localStorage.getItem("token")||"":"sessionstorage"===r?sessionStorage.getItem("token")||"":localStorage.getItem("token")||sessionStorage.getItem("token")||""},I=function(e,t){var r=e.toLowerCase();"localstorage"===r?localStorage.removeItem("token"):"sessionstorage"===r?sessionStorage.removeItem("token"):(localStorage.removeItem("token"),sessionStorage.getItem("token"))};function E(e){return"string"==typeof e?e.replace(/-/g,"/"):e}function N(e){return e?new Date(E(e)):new Date}function D(e,t){void 0===e&&(e=Date.now()),void 0===t&&(t="yyyy-MM-dd HH:mm:ss"),e=E(e);var r={"M+":(e=new Date(e)).getMonth()+1,"d+":e.getDate(),"h+":e.getHours()%12==0?12:e.getHours()%12,"H+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};return/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(""+e.getFullYear()).substr(4-RegExp.$1.length))),Object.keys(r).forEach((function(e){new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?r[e]:("00"+r[e]).substr((""+r[e]).length)))})),t}function T(e,t,n){if(void 0===t&&(t="yyyy年MM月dd日 HH时mm分ss秒"),void 0===n&&(n="-"),r(e))return n;e=E(e);var o=new Date(e),i=(Date.now()-o.getTime())/1e3;return i<0?e:i<30?"刚刚":i<3600?Math.ceil(i/60)+"分钟前":i<86400?Math.floor(i/3600)+"小时前":i<172800?"1天前":D(e,t)}function U(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n="yyyy-MM-dd"),r(e))return"-";e=E(e);var o=new Date(e);return o.setDate(o.getDate()+Number(t)),D(o,n)}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var O=function(){return(O=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function P(e,t,r,n){return new(r||(r=Promise))((function(o,i){function a(e){try{c(n.next(e))}catch(e){i(e)}}function u(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,u)}c((n=n.apply(e,t||[])).next())}))}function B(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}var j={operation:"divide",factor:100,precision:2,formatAsCurrency:!1,currencySymbol:"¥"};function F(e,t){if(void 0===t&&(t="-"),r(e))return t;var n=e.toString();return n.includes(".")||(n+="."),n.replace(/\d(?=(\d{3})+\.)/g,(function(e){return e+","})).replace(/\.$/,"")}function z(e){void 0===e&&(e="");if(r(e))return"";if(Number(e)>=1e15)return e;var t,n,o,i=["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"],a=["","拾","佰","仟"],u=["","万","亿","兆"],c=["角","分","毫","厘"],s="";if("0"===(e=parseFloat(e).toString()))return s=i[0]+"元整";if(-1===(e=e.toString()).indexOf(".")?(t=e,n=""):(t=(o=e.split("."))[0],n=o[1].substr(0,4)),parseInt(t,10)>0){for(var l=0,f=t.length,d=0;d<f;d+=1){var g=t.substr(d,1),p=f-d-1,h=p/4,v=p%4;"0"===g?l+=1:(l>0&&(s+=i[0]),l=0,s+=i[parseInt(g,10)]+a[v]),0===v&&l<4&&(s+=u[h])}s+="元"}if(""!==n){var m=n.length;for(d=0;d<m;d+=1){var w=n.substr(d,1);"0"!==w&&(s+=i[Number(w)]+c[d])}}return""===s?s+=i[0]+"元整":""===n&&(s+="整"),s}function H(e,t){void 0===t&&(t=2);var r=parseFloat(String(e));if(Number.isNaN(r))return"";var n=(r=Math.round(Number(e)*Math.pow(10,t))/Math.pow(10,t)).toString(),o=n.indexOf(".");for(o<0&&(o=n.length,n+=".");n.length<=o+t;)n+="0";return n}function W(e,t){if(void 0===t&&(t=0),r(e))return e;var n=Math.pow(10,t),o=Number(e)*n;return Math.ceil(o)/n}function Y(e,t){if(void 0===t&&(t=0),r(e))return e;var n=Math.pow(10,t),o=Number(e)*n;return Math.floor(o)/n}function $(e,t){var r=q(e,t),n=O(O({},j),t);if(n.formatter)return n.formatter(r);if(n.formatAsCurrency){var o=r.toFixed(n.precision),i=r>=1e3?F(o):o;return""+n.currencySymbol+i}return r.toFixed(n.precision)}function q(e,t){var r,n,o=O(O({},j),t);if(null==e||""===e)return 0;if("string"==typeof e){var i=e.replace(/[^\d.-]/g,"");r=i?parseFloat(i):0}else r=e;if(isNaN(r))return 0;if(n="multiply"===o.operation?r*o.factor:0!==o.factor?r/o.factor:0,void 0!==o.precision){var a=Math.pow(10,o.precision);n=Math.round(n*a)/a}return n}function _(e,t){return $(e,O({operation:"divide",factor:100,formatAsCurrency:!0},t))}function L(e,t){void 0===t&&(t="B");var r=["B","KB","MB","GB","TB"],n=r.indexOf(t.toUpperCase());for(n=-1===n?0:n;e>=1024&&n<r.length;)e/=1024,n+=1;return{size:e,unit:r[n]}}function G(e,t,n){if(void 0===t&&(t="B"),void 0===n&&(n="-"),r(e))return n;var o=L(parseFloat(e.toString()),t);return""+W(o.size,2)+o.unit}function J(e){for(var t=e.match(/:(.*?);/)[1],r=window.atob(e.split(",")[1]),n=new ArrayBuffer(r.length),o=new Uint8Array(n),i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return new Blob([n],{type:t})}function Z(e){return new Promise((function(t,r){var n=new FileReader;n.onload=function(e){e&&e.target?t(e.target.result):r(e)},n.onerror=function(e){r(e)},n.readAsDataURL(e)}))}function Q(e,t,r){return new Promise((function(n,o){var i=parseFloat((e.size/1024/1024).toString()),a=new FileReader;a.onload=function(a){var u=new Image;u.onload=function(){var o=u.width,a=u.height,c=document.createElement("canvas"),s=c.getContext("2d"),l=t?t(o,a):1;(Number.isNaN(l)||"number"!=typeof l)&&(l=1);var f=r?r(i,l,o,a):1;if((Number.isNaN(f)||"number"!=typeof f)&&(f=1),s){var d=parseInt((o*l).toString(),10),g=parseInt((a*l).toString(),10);c.setAttribute("width",d.toString()),c.setAttribute("height",g.toString()),s.drawImage(u,0,0,d,g)}var p=c.toDataURL(e.type,f);n(J(p))},u.onerror=function(e){o(e)},a.target&&(u.src=a.target.result)},a.onerror=function(e){o(e)},a.readAsDataURL(e)}))}function K(e){var t=e.axiosRequest,r=e.notWithCredentials,n=void 0===r?[]:r;return function(e){var r=this,o=e.filename,i=e.url,a=e.data,u=void 0===a?{}:a,c=e.params,s=void 0===c?{}:c,l=e.method,f=void 0===l?"post":l;return new Promise((function(e,a){t({method:f,url:i,data:u,params:s,responseType:"blob",config:{withCredentials:n.some((function(e){return!i.includes(e)}))}}).then((function(t){return P(r,void 0,void 0,(function(){var r,n,i,u,c,s,l,f,d,g;return B(this,(function(p){switch(p.label){case 0:return"application/json"!==(r=null==t?void 0:t.data).type?[3,1]:((n=new FileReader).readAsText(r,"utf-8"),n.onload=function(){var e={};try{e=JSON.parse(n.result)}catch(t){e=r}a(e)},[3,3]);case 1:try{i=t.headers,u=i["content-disposition"],c=decodeURIComponent(u.split(";")[1].split("filename=")[1]),o&&!o.includes(".")?(s=c.split("."),l=s[s.length-1],o+="."+l):o||(o=c)}catch(e){o||(o="download.xlsx")}return f=new Blob([t.data]),d=document.createElement("a"),[4,Z(f)];case 2:g=p.sent(),d.href=g,d.download=o,document.body.appendChild(d),d.click(),document.body.removeChild(d),e(t),p.label=3;case 3:return[2]}}))}))})).catch((function(e){a(e)}))}))}}function V(e,t){var r=Object.keys,n=typeof e;return e&&t&&"object"===n&&n===typeof t?r(e).length===r(t).length&&r(e).every((function(r){return V(e[r],t[r])})):e===t}function X(e,t,r,n,o){if(void 0===o&&(o=[]),o.push(e),e[r]===t)throw"GOT IT!";if(e[n]&&e[n].length>0)for(var i=0;i<e[n].length;i++)X(e[n][i],t,r,n,o);o.pop()}function ee(e,t,r,n){var o=[];try{for(var i=0;i<r.length;i++)X(r[i],e,t,n,o)}catch(e){return o}}function te(e){return/^(https?:|mailto:|tel:)/.test(e)}function re(e){if(!e)return e;return e.replace(/^\s+|\s+$/g,"")}function ne(e){return/^0?(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/.test(e.toString())}function oe(e){return e=e.toString(),/^1/.test(e)&&11===e.length}function ie(e){return/^0[1-9][0-9]{1,2}-[2-8][0-9]{6,7}$/.test(String(e))}function ae(e){return/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(e)}function ue(e){return/^[1-9][0-9]{4,9}$/gim.test(String(e))}function ce(e,t){return void 0===t&&(t="-"),r(e)?t:e}function se(e,t,n){if(void 0===t&&(t=" "),void 0===n&&(n="-"),r(e))return n;if(11!==e.toString().length)return e;var o=e.toString().replace(/[^\d]/g,"").split(""),i="";return o.forEach((function(e,r){3!==r&&7!==r||(i+=t),i+=e})),i}function le(e,t){if(void 0===t&&(t=""),r(e))return t;if(11!==e.toString().length)return e;var n=e.toString();return n.substr(0,3)+"****"+n.substr(7,11)}function fe(e,t){return void 0===t&&(t=""),r(e)?t:e.toString().replace(/\s/g,"").replace(/(.{4})/g,"$1 ")}function de(){for(var e=[],t=65;t<91;t+=1)e.push(String.fromCharCode(t));return e}function ge(e){void 0===e&&(e="");return e.replace(/\B([A-Z])/g,"-$1").toLowerCase()}var pe={HTTP_STATUS:{TEMP_RESPOND:{Continue:100,SwitchingProtocal:101},SUCCESS:{Ok:200,Created:201,Accepted:202,NoAuthoritativeInformation:203,NoContent:204,ResetContent:205,ParticalContent:206},REDIRECT:{MultipleChoice:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308},REQUEST_ERROR:{BadRequest:400,UnAuthorized:401,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAccepted:406,ProxyAuthorizationRequired:407,RequestTimeout:408,UpgradeRequired:426,TokenUnAuthorized:499},SERVER_ERROR:{InternalServerError:500,BadGateway:502,ServiceUnavailable:503,GateTimeout:504,HttpVersionNotSupported:505}},CODES:{Success:"00000",UnAuthorized:"00099",UnAuthorizedPhone:"11001",UnAuthorizedWecom:"11000",UnAuthorizedHavePhone:"11002"},ERR_CODE_WHITE_LIST:[]},he=e.create({timeout:15e3,headers:{"Content-Type":"application/json"}}),ve=function(e){var t=e.cacheType,r=e.currentMode,n=e.errorCb,o=e.getTokenCb;return e.tokenKey,he.interceptors.request.use((function(e){return P(void 0,void 0,void 0,(function(){var r,n;return B(this,(function(o){return r=x(t),n=u(),e.headers.Authorization=r,e.headers.token=r,e.headers.FrontType=c(n),[2,e]}))}))}),(function(e){return Promise.reject(e)})),he.interceptors.response.use((function(e){return P(void 0,void 0,void 0,(function(){var n,i,a;return B(this,(function(u){return n=e.data,i=n.code||e.status,n instanceof Blob||i===pe.CODES.Success?[2,n]:i===pe.CODES.UnAuthorized?("local"!==r&&"dev"!==r&&"development"!==r&&(I(t),o&&"function"==typeof o&&o()),[2,Promise.reject(new Error("token过期!"))]):(a=n.message||n.msg,[2,Promise.reject(new Error(a||"Error"))])}))}))}),(function(e){return P(void 0,void 0,void 0,(function(){return B(this,(function(t){return n&&"function"==typeof n&&n(e),[2,Promise.reject(e)]}))}))})),he},me=function(e){return function(t,r){return P(void 0,void 0,void 0,(function(){var n,o,i,a,u,c,s;return B(this,(function(l){switch(l.label){case 0:return n=t.ip||t.request.ip,o=t.path,i=t.method,a=we(),u={method:t.method,url:t.url,query:t.query,body:t.request.body},c=t.headers,[4,r()];case 1:return l.sent(),s={status:t.status,body:t.body,headers:t.response.headers},ye({system:e,ip:n,path:o,method:i,time:a,params:u,headers:c,result:s}),[2]}}))}))}},we=function(){var e=new Date;return e.getFullYear()+""+"年"+(e.getMonth()+1+"")+"月"+(e.getDate()+"")+"日"+(e.getHours()+"")+":"+(e.getMinutes()+"")},ye=function(t){console.log("logData---------",t);e.post("https://fe-log-producer.jinbizhihui.com/log/save",t)};var be=function(e,t){void 0===e&&(e="state");var r=function(e,t){void 0===t&&(t="state");for(var r,n=e;"string"==typeof n;)try{r=n,n=decodeURIComponent(n),n=JSON.parse(n)}catch(e){n=r;break}for(;n&&"object"==typeof n&&t in n&&("string"==typeof n[t]||"object"==typeof n[t]);)if("string"==typeof(n=n[t]))try{n=decodeURIComponent(n),n=JSON.parse(n)}catch(e){break}return n}(t,e);return"object"==typeof r?JSON.stringify(r):String(r)};export{U as addDays,S as base64ToBlob,M as base64ToFile,Z as blobToDataURL,f as buildUUID,L as calcFileSize,W as ceil,n as clearLoginData,E as compatibleDate,Q as compressImg,q as computeMoney,v as convertBase64UrlToBlob,z as convertCurrency,J as dataURLtoBlob,V as deepEqual,G as fileSizeFormat,b as filterRepeat,ee as findNodePath,Y as floor,fe as formatBank,_ as formatCentsToYuan,ce as formatEmptyValue,H as formatFloat,$ as formatMoney,se as formatPhone,le as formatPhoneHide,D as formatTime,h as formateTimestamp,T as fromNow,K as genExportByBlob,de as generateEnglishLetters,l as getCookie,u as getDeviceType,m as getEnvironment,C as getFileData,c as getFromType,w as getIsComWx,y as getIsDevelopment,o as getQueryString,i as getQueryVariable,d as getTicket,x as getToken,a as getWecomToken,be as handleFlatStr,ve as http,pe as httpEnum,ge as humpTurnDashed,ae as isEmail,r as isEmpty,te as isExternal,A as isImage,ne as isMobile,oe as isMobileSimple,ue as isQQ,ie as isTelephone,N as newDate,s as randomString,me as recordLogMiddleWare,p as removeTicket,I as removeToken,g as setTicket,F as toThousands,re as trimVal,k as uuid,R as validateTwoDecimal};