UNPKG

@mobileaction/ui-modules

Version:

Mobile Action common modules for Vue projects

2 lines (1 loc) 14.9 kB
import e from"js-cookie";import t from"axios";const o={default:{style:{marginRight:"2px",padding:"1px 3px",borderRadius:"3px"},type:"log"},log:{type:"log"},error:{style:{color:"#ffffff",backgroundColor:"#ff0000"},type:"error"},info:{style:{color:"#ffffff",backgroundColor:"#00bfff"},type:"info"},warn:{style:{color:"#ffffff",backgroundColor:"#ffa500"},type:"warn"},debug:{style:{padding:"1px 3px 1px 0",borderRight:"2px solid #333333"},type:"verbose"}};Object.keys(o).forEach((e=>{o[e].style=Object.assign({},o.default.style,o[e].style)}));const n=["log","info","warn","error","debug"],s=e=>Object.keys(e).map((t=>t.replace(/[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g,(e=>"-"+e.toLowerCase()))+": "+e[t])).join(";"),r=(e,t)=>[`%c${t}`,s(e)];function a(e,{name:t,isDebug:s}){let a="string"==typeof e?e:t,i="boolean"==typeof s?()=>s:s;const c=(e&&e.$options&&e.$options.__file||a).replace(/^\/?client\/src\//,"").replace(/\.(js|vue)$/,""),l={};n.forEach((e=>{l[e]=i()?r(o[e].style,c):[c],this[e]=(...t)=>{if(("undefined"==typeof process||!process||!process.server)&&("debug"!==e||i())){(console[e]||console.trace||console.log)(...l[e],...t)}}}))}function i(e,t,o){return t.$log||(t.$log=new a(e,{name:o+"-logger",isDebug:()=>!1})),t.app===e?(t.$log.warn(`${o}: already added`),!1):(t.app=e,!0)}function c(e,t,o){e[o]=t,l(e)[o]=t}function l(e){return function(e){return 3===Number(e.version.split(".")[0])}(e)?e.config.globalProperties:e.prototype}function d(e){if(!i(e,d,"MaCommonErrorHandlers"))return;c(e,{failedRequest(...e){(this.$log||d.$log).error("Request failed:",...e)},suppressDuplicateNavigation(e){if(!e._isRouter)throw e}},"$error")}class u{constructor(e,{fsParams:t,domains:o}){if(!o||!o.length)throw Error("MaFullStory: domains must be an array of at least size 1");if(!t||!t.org)throw Error("MaFullStory: fsParams.org must be given");this.Vue=e,Object.defineProperties(this,{domains:{value:o,writable:!1,enumerable:!1},fsParams:{value:Object.assign({debug:!1,host:"fullstory.com",script:"edge.fullstory.com/s/fs.js",org:"",namespace:"FS"},t),writable:!1,enumerable:!1},loaded:{value:!1,enumerable:!1}})}initialize(e,t=""){if(!e||-643103943===function(e){if("string"!=typeof e)return 0;let t=0;for(let o=0;o<e.length;o+=1)t=(t<<5)-t+e.charCodeAt(o)|0;return t}(e.username))return;if(!this.domains.includes(window.origin))return;Object.keys(this.fsParams).forEach((e=>{window[`_fs_${e}`]=this.fsParams[e]}));const o=this;window._fs_debug=!1,window._fs_host="fullstory.com",window._fs_script="edge.fullstory.com/s/fs.js",window._fs_org="3TA9V",window._fs_namespace="FS",function(e){let t="script",n="user";if(e in window)return void(window.console&&window.console.log&&o.Vue.$log.error('FullStory namespace conflict. Please set window["_fs_namespace"].'));let s=window[e]=function(e,t,o){s.q?s.q.push([e,t,o]):s._api(e,t,o)};s.q=[];let r=document.createElement(t);r.async=1,r.crossOrigin="anonymous",r.onload=()=>{this.loaded=!0},r.src="https://"+window._fs_script;let a=document.getElementsByTagName(t)[0];a.parentNode.insertBefore(r,a),s.identify=function(e,t,o){s(n,{uid:e},o),t&&s(n,t,o)},s.setUserVars=function(e,t){s(n,e,t)},s.event=function(e,t,o){s("event",{n:e,p:t},o)},s.anonymize=function(){s.identify(!1)},s.shutdown=function(){s("rec",!1)},s.restart=function(){s("rec",!0)},s.log=function(e,t){s("log",[e,t])},s.consent=function(e){s("consent",!arguments.length||e)},s.identifyAccount=function(e,t){r="account",(t=t||{}).acctId=e,s(r,t)},s.clearUserCookie=function(){},s.setVars=function(e,t){s("setVars",[e,t])},s._w={},a="XMLHttpRequest",s._w[a]=window[a],a="fetch",s._w[a]=window[a],window[a]&&(window[a]=function(){return s._w[a].apply(this,arguments)}),s._v="1.3.0"}(window._fs_namespace);const n={displayName:`${t}${e.username}`,email:`${t}${e.username}`,numberOfApps_int:e.usage.apps,keywords_int:e.usage.keywords,pricingPlan_str:e.plan,createdAt_date:new Date(1e3*+e.createdAt)},s=`${t}${e.userId}`;window.FS.identify(s,n)}fs(){return this.loaded||g.$log.warn("MaFullStory: FS is not loaded"),window.FS}}function g(e,t){if(!i(e,g,"MaFullStory"))return;const o=Object.assign({domains:[],fsParams:{}},t);c(e,new u(e,o),"$maFullStory")}class p{constructor(e,{isProduction:t=!1}){this.Vue=e,this.pUserId=!1,this.imp=null,this.isProduction="boolean"==typeof t?()=>t:t}cantSend(){return!this.isProduction()||"1"===e.get("MA")||!window.dataLayer}initialize(e,t=null){this.imp=t,this.pUserId=e&&e.userId,this.cantSend()||window.dataLayer.push({userId:this.pUserId})}eventSend(e,t,o=!1,n=!1,s=!1){const r=!1===o?location.pathname:o;if(this.cantSend())return void p.$log.warn("Mocked GA event:",e,t,r,this.pUserId,s,n);const a={event:"customEvent",gaEventCategory:e,gaEventAction:t,gaEventLabel:r};this.pUserId&&(a.dimension2=`${this.pUserId}`),n&&(a.dimension3=n),!1!==s&&(a.gaEventValue=s),window.dataLayer.push(a)}transactionAdd(e,t,o,n,s){this.cantSend()?p.$log.warn("Mocked GA transaction event:",...arguments):window.dataLayer.push({event:"transactionEvent",transactionId:e,transactionAffiliation:t,transactionTotal:o,dimension2:n,transactionProducts:s})}}function h(e,t={}){i(e,p,"MaGA")&&c(e,new p(e,t||{}),"$ga")}function f(e,{siteKey:t,h:o}){if(!i(e,f,"MaGoogleRecaptcha"))return;const n=`https://www.google.com/recaptcha/enterprise.js?render=${t}`;e.component("ma-recaptcha",{name:"ma-recaptcha",emits:["response","status-updated"],render(){return o("div",[this.$slots.default()])},data:()=>({waitingResponse:!1}),methods:{submit(){this.waitingResponse=!0,window.grecaptcha.enterprise.ready((async()=>{window.grecaptcha.enterprise.execute(t,{action:"login"}).then((e=>this.$emit("response",e))).catch((e=>Promise.reject(e))).then((()=>{this.waitingResponse=!1}))}))}},mounted(){if(Array.from(document.querySelectorAll(`script[src="${encodeURI(n)}"`)).length)return;const e=document.createElement("script");e.async=!0,e.onerror=e=>this.$log.error("Failed to load recaptcha",e),e.onload=()=>this.$log.debug("ReCaptcha loaded"),e.src=n;document.body.appendChild(e)},watch:{waitingResponse(){this.$emit("status-updated",this.waitingResponse)}}})}class m{constructor(e,{appId:t,autoStart:o}){this.Vue=e,Object.defineProperties(this,{autoStart:{value:o||!1,writable:!1,enumerable:!1},appId:{value:t,writable:!1,enumerable:!1},loaded:{value:!1,writable:!0,enumerable:!1}}),!0===this.autoStart&&this.boot()}boot(e={}){w.$log.debug("[MaIntercom] booted",e);(t=>{const o=e.isProduction?"Production":"Staging";w.$log.info("[MaIntercom]",`Initializing Intercom in ${o} mode`);const n=window,s=document,r=n.Intercom;if("function"==typeof r)r("reattach_activator"),r("update",e);else{const e=function(){e.c(arguments)};e.q=[],e.c=function(t){e.q.push(t)},n.Intercom=e;const o=s.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://widget.intercom.io/widget/"+this.appId,o.onload=t;const r=s.getElementsByTagName("script")[0];r&&r.parentNode.insertBefore(o,r)}})((()=>{w.$log.info("[MaIntercom] Loaded!"),this.loaded=!0;const t=Object.assign({},e,{widget:{activator:"#IntercomDefaultWidget"},app_id:this.appId});this.callIntercom("boot",t)}))}callIntercom(...e){void 0!==window.Intercom?window.Intercom(...e):w.$log.warn("[MaIntercom] Intercom not loaded yet;",...e)}track(e,t={}){w.$log.debug("[MaIntercom] track event:",e,t),this.callIntercom("trackEvent",e,t)}showMessenger(){w.$log.debug("[MaIntercom] show messenger"),this.callIntercom("show")}showIntercomWithMessage(e){w.$log.debug("[MaIntercom] show intercom with special message"),this.callIntercom("showNewMessage",e)}hideMessenger(){w.$log.debug("[MaIntercom] hide messenger"),this.callIntercom("hide")}update(e){w.$log.debug("[MaIntercom] update:",e),this.callIntercom("update",e)}showIntercomButton(){w.$log.debug("[MaIntercom] show intercom button"),this.callIntercom("update",{hide_default_launcher:!1})}hideIntercomButton(){w.$log.debug("[MaIntercom] hide intercom button"),this.callIntercom("update",{hide_default_launcher:!0})}}function w(e,t={}){if(!t.appId)throw new Error("MaIntercom: Missing app id");i(e,w,"MaIntercom")&&c(e,new m(e,t),"$maIntercom")}const b="MA_LAST_CLEARED";const y=new class{constructor(){this.storage={}}getItem(e){return e in this.storage?this.storage[e]:null}setItem(e,t){this.storage[e]=t}};class ${constructor(e,{cacheTimeout:t,cachePrefix:o,keptKeys:n,keptRawKeys:s}){const r=[...(n||[]).map((e=>`${o}${e}`)),...s||[]];this.$log=new a(null,{name:"MaStorage",isDebug:!1}),Object.defineProperties(this,{storage:{get:()=>e()||y,enumerable:!1},cacheTimeout:{value:t,writable:!1,enumerable:!1},cachePrefix:{value:o,writable:!1,enumerable:!1},keptKeys:{value:r,writable:!1,enumerable:!1}})}set(e,t){try{const o=JSON.stringify(t);return this.storage.setItem(e,o),!0}catch(e){return this.$log.error("Error: cannot set value. Possible circular data"),!1}}clear(e=!1){if(e)return void this.storage.clear();const t={};this.keptKeys.forEach((e=>{t[e]=this.storage.getItem(e)})),this.storage.clear(),Object.keys(t).forEach((e=>{this.storage.setItem(e,t[e])})),this.set(b,(new Date).getTime())}get(e){if(this.cacheTimeout>0){const e=this.storage.getItem(b);null===e?this.set(b,(new Date).getTime()):(new Date).getTime()-e>this.cacheTimeout&&this.clear()}const t=this.storage.getItem(e);try{return JSON.parse(t)}catch(e){return null}}del(e){try{this.storage.removeItem(e)}catch(t){this.$log.error("Failed to delete key from storage: ",e)}}reduce(e,t){const o=`${this.cachePrefix}${e}`;return void 0!==t?(this.set(o,t),t):this.get(o)}}function I(e,t){t.forEach((t=>{let o=t;if("string"==typeof o&&(o={name:o}),"string"!=typeof o.name||0===o.name.length)throw new Error(`Invalid reducer name given: ${o.name}`);if(o.reducer||(o.reducer=o.name),o.default&&(o.getter&&this.$log.warn(`MaStorage: "default" property will overwrite "getter" method for ${o.name}`),o.getter=e=>e||o.default),"function"!=typeof o.getter&&(o.getter=e=>e),"function"!=typeof o.setter&&(o.setter=e=>e),"string"==typeof o.reducer){let t=o.reducer;o.reducer=n=>o.getter(e.reduce(t,void 0!==n?o.setter(n):n))}if("function"!=typeof o.reducer)throw new Error(`Invalid reducer function provided: ${o.reducer}`);Object.defineProperty(e,o.name,{get:o.reducer,set:o.reducer,enumerable:!0})}))}const v=-1;function E(e,t=[],o){if(!i(e,E,"MaLocalStorage"))return;const n=Object.assign({cacheTimeout:v,cachePrefix:"MA_",keptKeys:[],keptRawKeys:[],windowGlobal:!1},o),s="appVersion";n.keptKeys.push(s);const r=new $((()=>"undefined"!=typeof window&&window.localStorage),n);-1===t.findIndex((e=>e===s||e.name===s))&&t.push({name:s,default:"0.0.0"}),I(r,t),c(e,r,"$maLocalStorage"),"undefined"!=typeof window&&n.windowGlobal&&(window.$maLocalStorage=r)}const{validate:_}=require("schema-utils"),S={type:"object",properties:{name:{type:"string"},isDebug:{anyOf:[{type:"boolean"},{type:"object"}]}}},M={name:"ma-logger",isDebug:!1};function P(e,{name:t="ma-logger",isDebug:o=!1}={}){const n={...M,name:t,isDebug:o};if(_(S,n,{name:"MaLoggerPlugin",baseDataPath:"options"}),P.app===e)return console.warn(`${n.name}: already added`),!1;P.app=e,P.options=n,n.isDebug="boolean"==typeof n.isDebug?()=>n.isDebug:n.isDebug;c(e,new a(e,n),"$log")}const k=[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"],R=(e=8)=>[...new Array(e)].map((()=>k[Math.floor(Math.random()*k.length)])).join(""),j={cacheEnabled:!1,cacheDelay:10,disableLoginCheck:!1,preRequestCheck:()=>!0,alreadyRetried:!1};class O{constructor(e,o){this.pools={},this.axiosCfg=Object.assign({responseType:"json",withCredentials:!0,headers:{"Access-Control-Allow-Origin":"*","Content-Type":"application/json"}},e),this.poolerAxios=t.create(this.axiosCfg),this.app=o.app,this.$log=new a(o.app,{name:"MaRequestPooler",isDebug:o.isDebug||!1}),this.cfg=Object.assign({REQUEST_PREFIX:"MA_REQ_",notLoggedIn:(...e)=>this.$log.error("Login failed:",...e)},o)}clearPool(e){if(!e)return void this.$log.error("Invalid id given:",e);if(!(e in this.pools))return void this.$log.error("Tried to clean non existing pool with id:",e);const t=this.pools[e];Object.keys(t).forEach((e=>{t[e].cancel()})),this.pools[e]&&delete this.pools[e]}makeRequest(e,o,n){let s=o||{};this.$log.debug("Making a request to:",e);const r=Object.assign({id:window.location.href},j,n),a=R(16),i=t.CancelToken.source(),c=new Promise(((t,o)=>{if(r.cacheEnabled){if(!this.app.$maSessionStorage)throw Error("MaSessionStorage plugin not enabled");const o=this.app.$maSessionStorage.get(this.cfg.REQUEST_PREFIX+e);if(o)return this.$log.debug(`Using cached data(${o.ts}) for: ${e}`),void setTimeout((()=>{t(o.data)}),r.cacheDelay)}this.pools[r.id]=this.pools[r.id]||{},this.pools[r.id][a]={id:a,cancel:i.cancel,ts:Date.now()};const n=Object.assign({},s.headers);Object.assign(s,{url:e,headers:n,cancelToken:i.token});if(!1===r.preRequestCheck(e,s,r))return o({errors:["PRE_REQUEST_CHECK_FAILED"]});this.poolerAxios.request(s).then((({data:n,status:s,statusText:a})=>{this.$log.debug(`Data received: ${s}-${a} data:`,n);let i=null;if(/\.json$/.test(e.split("?")[0])&&!Object.hasOwnProperty.bind(n)("success")&&(i={success:!0,data:n}),i=i||n,i.success){if(r.cacheEnabled){const t=(new Date).getTime();this.app.$maSessionStorage.set(this.cfg.REQUEST_PREFIX+e,{data:i.data,ts:t}),this.$log.debug(`Caching data at ${t} for: ${e}`)}t(i.data)}else{const e=i.errors||[];!r.disableLoginCheck&&e.find((e=>"NOT_LOGGED_IN"===e))&&this.cfg.notLoggedIn(),o(i)}})).catch((e=>{this.$log.error("Failed request:",e);const t=e.response?e.response.status:e.message;!r.disableLoginCheck&&(401===t||e.response&&"AUTHENTICATION_FAILED"===e.response.data.errorCode)&&this.cfg.notLoggedIn();let n=e.response&&e.response.data||e.message;n=n&&([n.errorCode]||n.errors),o({errors:[...n,"FETCH_ERROR"]},t)}))}));return c.poolId=r.id,c.reqId=a,c.cancel=i.cancel,c}clear(e){e||e in this.pools?this.clearPool(e):Object.keys(this.pools).forEach((e=>{this.clearPool(e)}))}cancelRequest(e,t){e&&t?this.pools[e]&&this.pools[e][t]?this.pools[e][t].cancel():this.$log.error("Pool or request does not exists:",e,t):this.$log.error("Received invalid poolId-reqId pair: ",e,t)}}function D(e,t,o){i(e,D,"MaRequestPooler")&&(l(e).$req=new O(t,o))}const T=36e5;function A(e,t=[],o){if(!i(e,A,"MaSessionStorage"))return;const n=Object.assign({cacheTimeout:T,cachePrefix:"MA_",keptKeys:[],keptRawKeys:[],windowGlobal:!1},o),s="appVersion",r="appVersionInitTime";n.keptKeys.push(s,r);const a=new $((()=>"undefined"!=typeof window&&window.sessionStorage),n);C(t,s,"0.0.0"),C(t,r,0),I(a,t),c(e,a,"$maSessionStorage"),"undefined"!=typeof window&&n.windowGlobal&&(window.$maSessionStorage=a)}function C(e,t,o){-1===e.findIndex((e=>e===t||e.name===t))&&e.push({name:t,default:o})}export{k as ALPHANUMERIC_CHARS,j as DEFAULT_OPTIONS,y as FALLBACK_STORAGE,d as MaCommonErrorHandlers,g as MaFullStory,h as MaGa,f as MaGoogleRecaptcha,w as MaIntercom,E as MaLocalStorage,a as MaLogger,P as MaLoggerPlugin,D as MaRequestPooler,A as MaSessionStorage,$ as MaStorage,I as insertReducerProps,R as randomString};