@apicart/core-sdk
Version:
Apicart Core dependency for all SDKs
8 lines (6 loc) • 16.5 kB
JavaScript
/**
* Utils.js v1.0.0-alpha7
* (c) 2018-2020 Apicart Company
* Released under the MIT License.
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("https"),require("http")):"function"==typeof define&&define.amd?define(["https","http"],e):(t=t||self).Apicart=e(t.httpsProcessor,t.httpProcessor)}(this,(function(t,e){"use strict";var n=new(function(){function n(){}return n.prototype.get=function(t,e){return void 0===e&&(e={}),e.method="get",e.url=t,this.sendRequest(e)},n.prototype.post=function(t,e){return void 0===e&&(e={}),e.method="post",e.url=t,this.sendRequest(e)},n.prototype.request=function(t){return this.sendRequest(t)},n.prototype.createResponseObject=function(t){var e,n,r={},o={};return"xhr"===t.type?(c.forEach(t.request.getAllResponseHeaders().trim().split(/[\r\n]+/),(function(t){var e=t.split(": ");r[e.shift()]=e.join(": ")})),o=t.responseData,e=t.request.status,n=t.request.statusText):"nodeHttp"===t.type&&(o=t.responseData,r=t.response?t.response.headers:null,e=t.response?t.response.statusCode:null,n=t.response?t.response.statusMessage:null),{config:t.requestConfig,data:a.isJson(o)?a.parse(o):o,headers:r,request:t.request,status:e,statusText:n}},n.prototype.sendRequest=function(t){if(l.isEmpty(t.url))throw"@apicart/js-utils: No url provided for ajax request";var e=f.merge({adapter:null,data:{},eventListeners:Object,headers:{},method:"get",timeout:5e3,url:"",withCredentials:!1,isGet:function(){return"get"===this.method},isPost:function(){return"post"===this.method}},t);e.url=new URL(e.url),e.isGet()?c.forEach(e.data,(function(t,n){e.url.searchParams.append(n,encodeURIComponent(t))})):"string"!=typeof e.data&&(e.data=a.stringify(e.data)),l.isEmpty(e.data)&&(e.data=null);var n=e.adapter||null,r=null;if("function"===n)r=n.call(this,e);else if("undefined"!=typeof XMLHttpRequest)r=this.xhrAdapter(e);else{if("undefined"==typeof process||"[object process]"!==Object.prototype.toString.call(process))throw"@apicart/js-utils: Request cannot be processed because no Adapter was configuredor is not a callable function.";r=this.httpAdapter(e)}return r},n.prototype.xhrAdapter=function(t){var e=this,n=function(t,n){return e.createResponseObject({type:"xhr",request:t,responseData:t.responseText,requestConfig:n})};return new Promise((function(e,r){var o=new XMLHttpRequest;c.forEach(t.eventListeners,(function(t,e){o.addEventListener(t,(function(t){return e.call(o,t)}))})),o.addEventListener("load",(function(){e(n(o,t))})),o.addEventListener("error",(function(){r(n(o,t))})),o.open(t.method,t.url.toString()),o.withCredentials=t.withCredentials,t.timeout>0&&(o.timeout=t.timeout,o.addEventListener("timeout",(function(){r(n(o,t))}))),l.isEmpty(t.headers)||c.forEach(t.headers,(function(t,e){o.setRequestHeader(e,t)})),o.send(t.data)}))},n.prototype.httpAdapter=function(n){var r=this,o={hostname:n.url.hostname,port:null,path:n.url.pathname,method:n.method,headers:n.headers,timeout:n.timeout};n.isPost()&&(o.headers["Content-Type"]="application/json",o.headers["Content-Length"]=n.data?n.data.length:0);var i=null,s=n.url.protocol;if("http:"===s)o.port=80,i=e;else{if("https:"!==s)throw'@apicart/js-utils: No processor was found for URL protocol "'+s+'"';o.port=443,i=t}var a=function(t,e,o){return r.createResponseObject({type:"nodeHttp",request:t,response:e,responseData:o,requestConfig:n})};return new Promise((function(t){var e=i.request(o,(function(n){var r="";n.on("data",(function(t){r+=t})),n.on("end",(function(){t(a(e,n,r))}))}));e.on("error",(function(n){t(a(e,null,n))})),e.on("timeout",(function(){e.abort()})),n.isPost()&&e.write(n.data),e.end()}))},n}()),r=new(function(){function t(){}return t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return void 0!==console.error&&console.error.apply(console,t),this},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return void 0!==console.log&&console.log.apply(console,t),this},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return void 0!==console.warn&&console.warn.apply(console,t),this},t}()),o=new(function(){function t(){}return t.prototype.addClass=function(t,e){return"string"==typeof e&&(e=e.split(" ")),c.forEach(e,(function(e){t.classList.contains(e)||(t.className+=" "+e)})),t.className=t.className.trim(),this},t.prototype.findParent=function(t,e){for(var n=null;t=t.parentElement;)if(this.matches(t,e)){n=t;break}return n},t.prototype.matches=function(t,e){var n=Element.prototype;return n.matches?t.matches(e):!!n.msMatchesSelector&&t.msMatchesSelector(e)},t.prototype.on=function(t,e,n){var r=this;return"string"==typeof t&&(t=t.split(" ")),"string"==typeof e&&(e=e.split(",")),c.forEach(e,(function(e){c.forEach(t,(function(t){!function(t,e){document.addEventListener(e,(function(e){var o=e.target;if(o!==this&&(r.matches(o,t)||(o=r.findParent(o,t)),o&&o!==this)){e.preventDefault();var i={currentTarget:o,originalEvent:e};c.forEach(["altKey","bubbles","button","buttons","cancelable","char","charCode","clientX","clientY","ctrlKey","data","detail","eventPhase","key","keyCode","metaKey","offsetX","offsetY","originalTarget","pageX","pageY","preventDefault","relatedTarget","screenX","screenY","shiftKey","stopImmediatePropagation","stopPropagation","target","toElement","type","view","which"],(function(t){f.keyExists(e,t)&&(e[t]instanceof Function?i[t]=function(){return e[t]()}:Object.defineProperty(i,t,{get:function(){return e[t]}}))})),n.call(o,i)}}))}(e,t)}))})),this},t.prototype.removeClass=function(t,e){return t.className=t.className.replace(new RegExp(e.trim().replace(" ","|"),"g"),"").trim().replace(/\s+/," "),this},t.prototype.toggleClass=function(t,e){var n=e.split(" "),r="",o="";return c.forEach(n,(function(e){t.classList.contains(e)?r+=" "+e:o+=" "+e})),this.removeClass(t,r),this.addClass(t,o),this},t.prototype.trigger=function(t,e){return t instanceof Element&&(t=[t]),c.forEach(t,(function(t){t.dispatchEvent(new Event(e,{bubbles:!0,cancelable:!0}))})),this},t}()),i=new(function(){function t(){this.eventsRegister={}}return t.prototype.addListener=function(t,e,n,r){var o=this;return void 0===r&&(r=!1),"string"==typeof e&&(e=e.split(" ")),c.forEach(e,(function(e){e in o.eventsRegister||(o.eventsRegister[e]={}),o.eventsRegister[e][t]={callback:n,singleAction:r}})),this},t.prototype.dispatchEvent=function(t,e){var n=this;return void 0===e&&(e=[]),Array.isArray(e)||(e=[e]),"string"==typeof t&&(t=t.split(" ")),c.forEach(t,(function(t){t in n.eventsRegister&&c.forEach(n.eventsRegister[t],(function(r,o){r.singleAction&&n.removeListener(o,t),r.callback.apply(null,e)}))})),this},t.prototype.removeListener=function(t,e){var n=this;return"string"==typeof e&&(e=e.split(" ")),c.forEach(e,(function(e){delete n.eventsRegister[e][t]})),this},t}()),s=new(function(){function t(){this.STORAGE_KEY="utils_flash_messages"}return t.prototype.addMessage=function(t,e){void 0===e&&(e=null),e=e||"info";var n=this.getMessages();return e in n||(n[e]=[]),n[e].push(t),u.setItem(this.STORAGE_KEY,n),this},t.prototype.getMessages=function(){return u.getItem(this.STORAGE_KEY)},t.prototype.hasMessages=function(t){void 0===t&&(t=null);var e=this.getMessages(),n=t?f.find(e,t):e;return l.isEmpty(n)},t.prototype.processMessages=function(t,e){void 0===e&&(e=null);var n=this.getMessages();return e&&f.keyExists(n,e)?c.forEach(n[e],(function(n){t(n,e)})):l.isEmpty(n)&&c.forEach(n,(function(e,n){l.isEmpty(e)||c.forEach(e,(function(e){t(e,n)}))})),localStorage.setItem(this.STORAGE_KEY,a.stringify({})),this},t}()),a=new(function(){function t(){}return t.prototype.isJson=function(t){if("string"!=typeof t)return!1;try{JSON.parse(t)}catch(t){return!1}return!0},t.prototype.parse=function(t){return this.isJson(t)?JSON.parse(t):{}},t.prototype.stringify=function(t){return"object"==typeof t?JSON.stringify(t):""},t}()),u=new(function(){function t(){this._localStorageManager={_data:{},getItem:function(t){return void 0===this._data[t]?null:this._data[t]},setItem:function(t,e){this._data[t]=e},removeItem:function(t){delete this._data[t]},clear:function(){this._data={}},key:function(t){return void 0===Object.keys(this._data)[t]?null:Object.keys(this._data)[t]}},"undefined"!=typeof localStorage&&(this._localStorageManager=localStorage)}return t.prototype.clear=function(){return this._localStorageManager.clear(),this},t.prototype.getItem=function(t){var e=this._localStorageManager.getItem(t),n=null;return e&&null!==(n=a.parse(e)).expiration&&n.expiration<this.getActualTimestamp()&&(n=null,this.removeItem(t)),null===n?n:n.value},t.prototype.setItem=function(t,e,n){void 0===n&&(n=null);var o={expiration:n?this.getActualTimestamp()+n:null,value:e};try{this._localStorageManager.setItem(t,a.stringify(o))}catch(t){r.error(t)}return this},t.prototype.updateItem=function(t,e,n){void 0===n&&(n=null);var r=this.getItem(t)||{};return f.merge(r,e),this.setItem(t,r,n),this},t.prototype.removeItem=function(t){return this._localStorageManager.removeItem(t),this},t.prototype.hasItem=function(t){return null!==this.getItem(t)},t.prototype.getActualTimestamp=function(){return(new Date).getTime()},t}()),c=new(function(){function t(){}return t.prototype.forEach=function(t,e){var n,r,o,i,s,a={iterableLength:0,counter:0,isEven:function(){return this.counter%2==0},isOdd:function(){return 1===Math.abs(this.counter%2)},isFirst:function(){return 1===this.counter},isLast:function(){return this.counter===this.iterableLength}};if(null!==t&&!["undefined","number"].includes(typeof t)){if(Array.isArray(t)){if(!(r=Object.keys(t).length))return;for(a.iterableLength=r,n=0;n<r&&(a.counter++,!1!==e.apply(a,[t[n],n]));n++);}else{if(i=(o=Object.keys(t)).length,!o.length)return;for(a.iterableLength=i,n=0;n<i&&(a.counter++,s=o[n],!1!==e.apply(a,[t[s],s]));n++);}return this}},t}()),p=new(function(){function t(){}return t.prototype.randomNumber=function(t,e){return Math.random()*(e-t)+t},t.prototype.randomInt=function(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t},t}()),f=new(function(){function t(){}return t.prototype.assign=function(t,e,n){var r;"string"==typeof e&&(e=e.split("."));for(var o=e.length-1,i=0;i<o;++i)(r=e[i])in t||(t[r]={}),t=t[r];t[e[o]]=n},t.prototype.copy=function(t){var e=this,n={};return c.forEach(t,(function(t,r){n[r]=e.isObject(t)?e.copy(t):t})),n},t.prototype.delete=function(t,e){"string"==typeof e&&(e=e.split(".")),e.length&&c.forEach(e,(function(e){if(this.isLast()||"object"!=typeof t[e])return!1;t=t[e]})),delete t[e.pop()]},t.prototype.find=function(t,e){if(!e||!t||"object"!=typeof t)return null;"string"==typeof e&&(e=e.split("."));var n=!1;return e.length&&c.forEach(e,(function(e){if(null===t||"object"!=typeof t||!(e in t))return n=!0,!1;t=t[e]})),n?null:t},t.prototype.keyExists=function(t,e){if(!e||!t||"object"!=typeof t)return!1;"string"==typeof e&&(e=e.split("."));var n=!0;return e.length?c.forEach(e,(function(e){if(null===t||"object"!=typeof t||!(e in t))return n=!1,!1;t=t[e]})):n=!1,n},t.prototype.isObject=function(t){return null!=t&&!Array.isArray(t)&&"object"==typeof t},t.prototype.merge=function(){for(var t=this,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];var r={};return c.forEach(e,(function(e){c.forEach(e,(function(e,n){r[n]=n in r&&t.isObject(e)?t.merge(r[n],e):e}))})),r},t.prototype.values=function(t){var e=[];return c.forEach(t,(function(t){e.push(t)})),e},t}()),h=new(function(){function t(){}return t.prototype.firstToUpper=function(t){return t.charAt(0).toUpperCase()+t.slice(1)},t.prototype.generateHash=function(t,e){void 0===e&&(e="abcdefghijklmnopqrstuvwxyz0123456789");for(var n="";t--;)n+=e.charAt(Math.floor(Math.random()*e.length));return n},t.prototype.sprintf=function(t,e){return c.forEach(e,(function(e,n){["number","string"].includes(typeof e)&&(t=t.replace(new RegExp("%"+n+"%","g"),e))})),t},t.prototype.stripHtml=function(t){var e=document.createElement("div");return e.innerHTML=t,e.textContent||e.innerText||""},t.prototype.truncate=function(t,e,n,r){return void 0===n&&(n=" "),void 0===r&&(r="..."),t.length<=e?t:t.substr(0,t.lastIndexOf(n,e-3))+r},t}()),l=new(function(){function t(){}return t.prototype.isEmpty=function(t){var e=typeof t;return"undefined"===e||null===t||"number"!==e&&("string"===e?0===t.length:"object"===e||Array.isArray(t)?Object.keys(t).length<1:void 0)},t}()),d={Ajax:n,Console:r,Dom:o,EventDispatcher:i,FlashMessages:s,Json:a,LocalStorage:u,Loops:c,Numbers:p,Objects:f,Strings:h,Validators:l},g=new(function(){function t(){this.ENV_DEV="dev",this.ENV_PROD="prod",this._parameters={env:this.ENV_PROD},"undefined"!=typeof ApicartConfig&&(this._parameters=d.Objects.merge(this._parameters,ApicartConfig))}return t.prototype.configure=function(t){this._parameters=d.Objects.merge(this._parameters,t),d.EventDispatcher.dispatchEvent("apicart:configure")},t.prototype.setEnvironment=function(t){if(![this.ENV_PROD,this.ENV_DEV].includes(t))throw new Error('Unknown environment "'+t+'".');this._parameters.env=t,d.EventDispatcher.dispatchEvent("apicart:environment:changed")},t.prototype.isDevEnv=function(){return this._parameters.env===this.ENV_DEV},t.prototype.isProdEnv=function(){return this._parameters.env===this.ENV_PROD},t.prototype.getEnvironment=function(){return this._parameters.env},t.prototype.getParameter=function(t){return d.Objects.find(this._parameters,t)},t}()),y=new(function(){function t(){var t=this;this.STORAGE_KEY="apicart-1.0.0-alpha7",this._cacheKey=null,this._storage={},this.init(),d.EventDispatcher.addListener("apicart-storage","apicart:configure",(function(){t.init()}))}return t.prototype.init=function(){this._cacheKey=g.getParameter("storage.cacheKey");var t=d.LocalStorage.getItem(this.STORAGE_KEY);!t||this._cacheKey&&this._cacheKey!==t._cacheKey?this.clearStorage():this._storage[this.STORAGE_KEY]=t},t.prototype.clearStorage=function(){this._storage={},this._storage[this.STORAGE_KEY]={_cacheKey:g.getParameter("storage.cacheKey")||null},this.saveStorage()},t.prototype.saveStorage=function(){d.LocalStorage.setItem(this.STORAGE_KEY,this.getStorage())},t.prototype.find=function(t){return d.Objects.find(this.getStorage(),t)},t.prototype.getStorage=function(){return this._storage[this.STORAGE_KEY]},t.prototype.getItem=function(t){var e=d.LocalStorage.getItem(this.STORAGE_KEY);return d.Objects.find(e,t)},t.prototype.setItem=function(t,e){d.Objects.assign(this.getStorage(),t,e),this.saveStorage()},t.prototype.updateItem=function(t,e){var n=this.getItem(t);n?(d.Objects.merge(n,e),this.setItem(t,n)):this.setItem(t,e)},t.prototype.hasItem=function(t){return null!==this.getItem(t)},t.prototype.removeItem=function(t){d.Objects.delete(this._storage[this.STORAGE_KEY],t),this.saveStorage()},t}()),m=new(function(){function t(){}return t.prototype.call=function(t,e,n,r,o){return d.Ajax.post(t,{data:d.Json.stringify({query:e,variables:n}),headers:{"Content-Type":"application/json"},withCredentials:o,timeout:r}).then((function(t){if(401===t.status)throw"401 Unauthorized - check provided Payments API token";if(404===t.status)throw"404 Not Found - data source was not found";if(429===t.status)throw"429 Too Many Requests - read rate limit docs section";if(200!==t.status)throw t.status+" - please contact Apicart support";return t})).catch((function(t){d.Console.error(t)}))},t.prototype.isSuccessResult=function(t,e,n){if(void 0===t&&(t=null),void 0===n&&(n=!0),null===t)throw"An error occurred, please try again in a few minutes.";if(d.Validators.isEmpty(t))throw"Response is empty.";var r=t.data;if(!d.Objects.keyExists(r,"data."+e+".result"))throw"Response doesn't contains valid result.";if(n&&"SUCCESS"!==r.data[e].result)throw d.Strings.sprintf('Response returned result "%0%" with message "%1%".',[r.data[e].result,r.data[e].message||""]);return!0},t}());return new(function(){function t(){this.ApiCommunicator=m,this.Configurator=g,this.Storage=y,this.Utils=d}return t.prototype.setDevEnv=function(){return this.Configurator.setEnvironment(this.Configurator.ENV_DEV),this},t.prototype.setProdEnv=function(){return this.Configurator.setEnvironment(this.Configurator.ENV_PROD),this},t.prototype.configure=function(t){return this.Configurator.configure(t),this},t.prototype.isDevEnv=function(){return this.Configurator.isDevEnv()},t.prototype.isProdEnv=function(){return this.Configurator.isProdEnv()},t.prototype.getConfigParameter=function(t){return this.Configurator.getParameter(t)},t}())}));