@apicart/core-sdk
Version:
Apicart Core dependency for all SDKs
1,063 lines (1,041 loc) • 42.4 kB
JavaScript
/**
* Utils.js v1.0.0-alpha7
* (c) 2018-2020 Apicart Company
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('https'), require('http')) :
typeof define === 'function' && define.amd ? define(['https', 'http'], factory) :
(global = global || self, global.Apicart = factory(global.httpsProcessor, global.httpProcessor));
}(this, (function (httpsProcessor, httpProcessor) { 'use strict';
/**
* Utils.js v1.0.0-alpha7
* (c) 2018-2020 Apicart Company
* Released under the MIT License.
*/
var Ajax = (function () {
function Ajax() {
}
Ajax.prototype.get = function (url, parameters) {
if (parameters === void 0) { parameters = {}; }
parameters.method = 'get';
parameters.url = url;
return this.sendRequest(parameters);
};
Ajax.prototype.post = function (url, parameters) {
if (parameters === void 0) { parameters = {}; }
parameters.method = 'post';
parameters.url = url;
return this.sendRequest(parameters);
};
Ajax.prototype.request = function (parameters) {
return this.sendRequest(parameters);
};
Ajax.prototype.createResponseObject = function (processedRequestConfig) {
var headers = {};
var data = {};
var status;
var statusText;
if (processedRequestConfig.type === 'xhr') {
Loops$1.forEach(processedRequestConfig.request.getAllResponseHeaders().trim().split(/[\r\n]+/), function (line) {
var parts = line.split(': ');
headers[parts.shift()] = parts.join(': ');
});
data = processedRequestConfig.responseData;
status = processedRequestConfig.request.status;
statusText = processedRequestConfig.request.statusText;
}
else if (processedRequestConfig.type === 'nodeHttp') {
data = processedRequestConfig.responseData;
headers = processedRequestConfig.response ? processedRequestConfig.response.headers : null;
status = processedRequestConfig.response ? processedRequestConfig.response.statusCode : null;
statusText = processedRequestConfig.response ? processedRequestConfig.response.statusMessage : null;
}
return {
config: processedRequestConfig.requestConfig,
data: Json$1.isJson(data) ? Json$1.parse(data) : data,
headers: headers,
request: processedRequestConfig.request,
status: status,
statusText: statusText
};
};
Ajax.prototype.sendRequest = function (requestConfiguration) {
if (Validators$1.isEmpty(requestConfiguration.url)) {
throw '@apicart/js-utils: No url provided for ajax request';
}
var config = Objects$1.merge({
adapter: null,
data: {},
eventListeners: Object,
headers: {},
method: 'get',
timeout: 5000,
url: '',
withCredentials: false,
isGet: function () {
return this.method === 'get';
},
isPost: function () {
return this.method === 'post';
}
}, requestConfiguration);
config.url = new URL(config.url);
if (config.isGet()) {
Loops$1.forEach(config.data, function (value, key) {
config.url.searchParams.append(key, encodeURIComponent(value));
});
}
else if (typeof config.data !== 'string') {
config.data = Json$1.stringify(config.data);
}
if (Validators$1.isEmpty(config.data)) {
config.data = null;
}
var requestAdapter = config.adapter || null;
var response = null;
if (requestAdapter === 'function') {
response = requestAdapter.call(this, config);
}
else if (typeof XMLHttpRequest !== 'undefined') {
response = this.xhrAdapter(config);
}
else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
response = this.httpAdapter(config);
}
else {
throw '@apicart/js-utils: Request cannot be processed because no Adapter was configured'
+ 'or is not a callable function.';
}
return response;
};
Ajax.prototype.xhrAdapter = function (requestConfiguration) {
var _this = this;
var createXHResponseObject = function (request, requestConfiguration) {
return _this.createResponseObject({
type: 'xhr',
request: request,
responseData: request.responseText,
requestConfig: requestConfiguration
});
};
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
Loops$1.forEach(requestConfiguration.eventListeners, function (eventName, eventCallback) {
request.addEventListener(eventName, function (event) { return eventCallback.call(request, event); });
});
request.addEventListener('load', function () {
resolve(createXHResponseObject(request, requestConfiguration));
});
request.addEventListener('error', function () {
reject(createXHResponseObject(request, requestConfiguration));
});
request.open(requestConfiguration.method, requestConfiguration.url.toString());
request.withCredentials = requestConfiguration.withCredentials;
if (requestConfiguration.timeout > 0) {
request.timeout = requestConfiguration.timeout;
request.addEventListener('timeout', function () {
reject(createXHResponseObject(request, requestConfiguration));
});
}
if (!Validators$1.isEmpty(requestConfiguration.headers)) {
Loops$1.forEach(requestConfiguration.headers, function (header, headerKey) {
request.setRequestHeader(headerKey, header);
});
}
request.send(requestConfiguration.data);
});
};
Ajax.prototype.httpAdapter = function (requestConfiguration) {
var _this = this;
var options = {
hostname: requestConfiguration.url.hostname,
port: null,
path: requestConfiguration.url.pathname,
method: requestConfiguration.method,
headers: requestConfiguration.headers,
timeout: requestConfiguration.timeout
};
if (requestConfiguration.isPost()) {
options.headers['Content-Type'] = 'application/json';
options.headers['Content-Length'] = requestConfiguration.data ? requestConfiguration.data.length : 0;
}
var processor = null;
var requestConfigurationProtocol = requestConfiguration.url.protocol;
if (requestConfigurationProtocol === 'http:') {
options.port = 80;
processor = httpProcessor;
}
else if (requestConfigurationProtocol === 'https:') {
options.port = 443;
processor = httpsProcessor;
}
else {
throw '@apicart/js-utils: No processor was found for URL protocol "' + requestConfigurationProtocol + '"';
}
var createNodeHttpResponseObject = function (request, response, responseData) {
return _this.createResponseObject({
type: 'nodeHttp',
request: request,
response: response,
responseData: responseData,
requestConfig: requestConfiguration
});
};
return new Promise(function (resolve) {
var request = processor.request(options, function (response) {
var responseData = '';
response.on('data', function (data) {
responseData += data;
});
response.on('end', function () {
resolve(createNodeHttpResponseObject(request, response, responseData));
});
});
request.on('error', function (error) {
resolve(createNodeHttpResponseObject(request, null, error));
});
request.on('timeout', function () {
request.abort();
});
if (requestConfiguration.isPost()) {
request.write(requestConfiguration.data);
}
request.end();
});
};
return Ajax;
}());
var Ajax$1 = new Ajax();
var Console = (function () {
function Console() {
}
Console.prototype.error = function () {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
if (typeof console.error !== 'undefined') {
console.error.apply(console, data);
}
return this;
};
Console.prototype.log = function () {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
if (typeof console.log !== 'undefined') {
console.log.apply(console, data);
}
return this;
};
Console.prototype.warn = function () {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
if (typeof console.warn !== 'undefined') {
console.warn.apply(console, data);
}
return this;
};
return Console;
}());
var Console$1 = new Console();
var Dom = (function () {
function Dom() {
}
Dom.prototype.addClass = function (element, classes) {
if (typeof classes === 'string') {
classes = classes.split(' ');
}
Loops$1.forEach(classes, function (newClass) {
if (!element.classList.contains(newClass)) {
element.className += ' ' + newClass;
}
});
element.className = element.className.trim();
return this;
};
Dom.prototype.findParent = function (element, selector) {
var parent = null;
while (element = element.parentElement) {
if (this.matches(element, selector)) {
parent = element;
break;
}
}
return parent;
};
Dom.prototype.matches = function (element, selector) {
var elementPrototype = Element.prototype;
if (elementPrototype.matches) {
return element.matches(selector);
}
else if (elementPrototype.msMatchesSelector) {
return element.msMatchesSelector(selector);
}
return false;
};
Dom.prototype.on = function (eventTypes, selectors, callback) {
var self = this;
if (typeof eventTypes === 'string') {
eventTypes = eventTypes.split(' ');
}
if (typeof selectors === 'string') {
selectors = selectors.split(',');
}
Loops$1.forEach(selectors, function (selector) {
Loops$1.forEach(eventTypes, function (eventType) {
(function (selector, eventType) {
document.addEventListener(eventType, function (event) {
var target = event.target;
if (target === this) {
return;
}
if (!self.matches(target, selector)) {
target = self.findParent(target, selector);
}
if (target && target !== this) {
event.preventDefault();
var newEvent_1 = {
currentTarget: target,
originalEvent: event
};
Loops$1.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 (keyToCopy) {
if (!Objects$1.keyExists(event, keyToCopy)) {
return;
}
var isFunction = event[keyToCopy] instanceof Function;
if (isFunction) {
newEvent_1[keyToCopy] = function () {
return event[keyToCopy]();
};
}
else {
Object.defineProperty(newEvent_1, keyToCopy, {
get: function () {
return event[keyToCopy];
}
});
}
});
callback.call(target, newEvent_1);
}
});
})(selector, eventType);
});
});
return this;
};
Dom.prototype.removeClass = function (element, classes) {
element.className = element.className
.replace(new RegExp(classes.trim().replace(' ', '|'), 'g'), '')
.trim()
.replace(/\s+/, ' ');
return this;
};
Dom.prototype.toggleClass = function (element, classes) {
var classesForCheck = classes.split(' ');
var classesToRemove = '';
var classesToAdd = '';
Loops$1.forEach(classesForCheck, function (value) {
if (element.classList.contains(value)) {
classesToRemove += ' ' + value;
}
else {
classesToAdd += ' ' + value;
}
});
this.removeClass(element, classesToRemove);
this.addClass(element, classesToAdd);
return this;
};
Dom.prototype.trigger = function (element, event) {
if (element instanceof Element) {
element = [element];
}
Loops$1.forEach(element, function (elementItem) {
elementItem.dispatchEvent(new Event(event, {
bubbles: true,
cancelable: true
}));
});
return this;
};
return Dom;
}());
var Dom$1 = new Dom();
var EventDispatcher = (function () {
function EventDispatcher() {
this.eventsRegister = {};
}
EventDispatcher.prototype.addListener = function (listenerKey, event, callback, singleAction) {
var _this = this;
if (singleAction === void 0) { singleAction = false; }
if (typeof event === 'string') {
event = event.split(' ');
}
Loops$1.forEach(event, function (eventName) {
if (!(eventName in _this.eventsRegister)) {
_this.eventsRegister[eventName] = {};
}
_this.eventsRegister[eventName][listenerKey] = {
callback: callback,
singleAction: singleAction
};
});
return this;
};
EventDispatcher.prototype.dispatchEvent = function (event, parameters) {
var _this = this;
if (parameters === void 0) { parameters = []; }
if (!Array.isArray(parameters)) {
parameters = [parameters];
}
if (typeof event === 'string') {
event = event.split(' ');
}
Loops$1.forEach(event, function (eventName) {
if (!(eventName in _this.eventsRegister)) {
return;
}
Loops$1.forEach(_this.eventsRegister[eventName], function (eventListener, eventListenerKey) {
if (eventListener.singleAction) {
_this.removeListener(eventListenerKey, eventName);
}
eventListener.callback.apply(null, parameters);
});
});
return this;
};
EventDispatcher.prototype.removeListener = function (listenerKey, event) {
var _this = this;
if (typeof event === 'string') {
event = event.split(' ');
}
Loops$1.forEach(event, function (eventName) {
delete _this.eventsRegister[eventName][listenerKey];
});
return this;
};
return EventDispatcher;
}());
var EventDispatcher$1 = new EventDispatcher();
var FlashMessages = (function () {
function FlashMessages() {
this.STORAGE_KEY = 'utils_flash_messages';
}
FlashMessages.prototype.addMessage = function (content, type) {
if (type === void 0) { type = null; }
type = type || 'info';
var flashMessagesItems = this.getMessages();
if (!(type in flashMessagesItems)) {
flashMessagesItems[type] = [];
}
flashMessagesItems[type].push(content);
LocalStorage$1.setItem(this.STORAGE_KEY, flashMessagesItems);
return this;
};
FlashMessages.prototype.getMessages = function () {
return LocalStorage$1.getItem(this.STORAGE_KEY);
};
FlashMessages.prototype.hasMessages = function (type) {
if (type === void 0) { type = null; }
var messages = this.getMessages();
var messagesByType = type ? Objects$1.find(messages, type) : messages;
return Validators$1.isEmpty(messagesByType);
};
FlashMessages.prototype.processMessages = function (callback, type) {
if (type === void 0) { type = null; }
var messages = this.getMessages();
if (type && Objects$1.keyExists(messages, type)) {
Loops$1.forEach(messages[type], function (message) {
callback(message, type);
});
}
else if (Validators$1.isEmpty(messages)) {
Loops$1.forEach(messages, function (messagesQueue, messagesType) {
if (Validators$1.isEmpty(messagesQueue)) {
return;
}
Loops$1.forEach(messagesQueue, function (message) {
callback(message, messagesType);
});
});
}
localStorage.setItem(this.STORAGE_KEY, Json$1.stringify({}));
return this;
};
return FlashMessages;
}());
var FlashMessages$1 = new FlashMessages();
var Json = (function () {
function Json() {
}
Json.prototype.isJson = function (content) {
if (typeof content !== 'string') {
return false;
}
try {
JSON.parse(content);
}
catch (e) {
return false;
}
return true;
};
Json.prototype.parse = function (content) {
return this.isJson(content) ? JSON.parse(content) : {};
};
Json.prototype.stringify = function (data) {
return typeof data === 'object' ? JSON.stringify(data) : '';
};
return Json;
}());
var Json$1 = new Json();
var LocalStorage = (function () {
function LocalStorage() {
this._localStorageManager = {
_data: {},
getItem: function (key) {
return typeof this._data[key] === 'undefined' ? null : this._data[key];
},
setItem: function (key, value) {
this._data[key] = value;
},
removeItem: function (key) {
delete this._data[key];
},
clear: function () {
this._data = {};
},
key: function (key) {
return typeof Object.keys(this._data)[key] === 'undefined' ? null : Object.keys(this._data)[key];
}
};
if (typeof localStorage !== 'undefined') {
this._localStorageManager = localStorage;
}
}
LocalStorage.prototype.clear = function () {
this._localStorageManager.clear();
return this;
};
LocalStorage.prototype.getItem = function (key) {
var itemString = this._localStorageManager.getItem(key);
var item = null;
if (itemString) {
item = Json$1.parse(itemString);
if (item.expiration !== null && item.expiration < this.getActualTimestamp()) {
item = null;
this.removeItem(key);
}
}
return item === null ? item : item.value;
};
LocalStorage.prototype.setItem = function (key, value, expiration) {
if (expiration === void 0) { expiration = null; }
var item = {
expiration: expiration ? this.getActualTimestamp() + expiration : null,
value: value
};
try {
this._localStorageManager.setItem(key, Json$1.stringify(item));
}
catch (error) {
Console$1.error(error);
}
return this;
};
LocalStorage.prototype.updateItem = function (key, value, expiration) {
if (expiration === void 0) { expiration = null; }
var item = this.getItem(key) || {};
Objects$1.merge(item, value);
this.setItem(key, item, expiration);
return this;
};
LocalStorage.prototype.removeItem = function (key) {
this._localStorageManager.removeItem(key);
return this;
};
LocalStorage.prototype.hasItem = function (key) {
return this.getItem(key) !== null;
};
LocalStorage.prototype.getActualTimestamp = function () {
return new Date().getTime();
};
return LocalStorage;
}());
var LocalStorage$1 = new LocalStorage();
var Loops = (function () {
function Loops() {
}
Loops.prototype.forEach = function (iterable, callback) {
var iterator;
var iteratorObject = {
iterableLength: 0,
counter: 0,
isEven: function () {
return this.counter % 2 === 0;
},
isOdd: function () {
return Math.abs(this.counter % 2) === 1;
},
isFirst: function () {
return this.counter === 1;
},
isLast: function () {
return this.counter === this.iterableLength;
}
};
var iterableLength;
var statement;
var keys;
var keysLength;
var key;
if (iterable === null || ['undefined', 'number'].includes(typeof iterable)) {
return;
}
if (Array.isArray(iterable)) {
iterableLength = Object.keys(iterable).length;
if (!iterableLength) {
return;
}
iteratorObject.iterableLength = iterableLength;
for (iterator = 0; iterator < iterableLength; iterator++) {
iteratorObject.counter++;
statement = callback.apply(iteratorObject, [iterable[iterator], iterator]);
if (statement === false) {
break;
}
}
}
else {
keys = Object.keys(iterable);
keysLength = keys.length;
if (!keys.length) {
return;
}
iteratorObject.iterableLength = keysLength;
for (iterator = 0; iterator < keysLength; iterator++) {
iteratorObject.counter++;
key = keys[iterator];
statement = callback.apply(iteratorObject, [iterable[key], key]);
if (statement === false) {
break;
}
}
}
return this;
};
return Loops;
}());
var Loops$1 = new Loops();
var Numbers = (function () {
function Numbers() {
}
Numbers.prototype.randomNumber = function (min, max) {
return Math.random() * (max - min) + min;
};
Numbers.prototype.randomInt = function (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
return Numbers;
}());
var Numbers$1 = new Numbers();
var Objects = (function () {
function Objects() {
}
Objects.prototype.assign = function (object, keyPath, value) {
if (typeof keyPath === 'string') {
keyPath = keyPath.split('.');
}
var key;
var lastKeyIndex = keyPath.length - 1;
for (var i = 0; i < lastKeyIndex; ++i) {
key = keyPath[i];
if (!(key in object)) {
object[key] = {};
}
object = object[key];
}
object[keyPath[lastKeyIndex]] = value;
};
Objects.prototype.copy = function (object) {
var _this = this;
var newObject = {};
Loops$1.forEach(object, function (value, key) {
newObject[key] = _this.isObject(value) ? _this.copy(value) : value;
});
return newObject;
};
Objects.prototype.delete = function (object, keyPath) {
if (typeof keyPath === 'string') {
keyPath = keyPath.split('.');
}
if (keyPath.length) {
Loops$1.forEach(keyPath, function (key) {
if (this.isLast() || typeof object[key] !== 'object') {
return false;
}
object = object[key];
});
}
delete object[keyPath.pop()];
};
Objects.prototype.find = function (object, keyPath) {
if (!keyPath || !object || typeof object !== 'object') {
return null;
}
if (typeof keyPath === 'string') {
keyPath = keyPath.split('.');
}
var wrongKeyPath = false;
if (keyPath.length) {
Loops$1.forEach(keyPath, function (keyPathPart) {
if (object === null || typeof object !== 'object' || !(keyPathPart in object)) {
wrongKeyPath = true;
return false;
}
object = object[keyPathPart];
});
}
return wrongKeyPath ? null : object;
};
Objects.prototype.keyExists = function (object, keyPath) {
if (!keyPath || !object || typeof object !== 'object') {
return false;
}
if (typeof keyPath === 'string') {
keyPath = keyPath.split('.');
}
var keyExists = true;
if (keyPath.length) {
Loops$1.forEach(keyPath, function (keyPathPart) {
if (object === null || typeof object !== 'object' || !(keyPathPart in object)) {
keyExists = false;
return false;
}
object = object[keyPathPart];
});
}
else {
keyExists = false;
}
return keyExists;
};
Objects.prototype.isObject = function (data) {
if (typeof data === 'undefined' || data === null || Array.isArray(data)) {
return false;
}
return typeof data === 'object';
};
Objects.prototype.merge = function () {
var _this = this;
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
var newObject = {};
Loops$1.forEach(objects, function (object) {
Loops$1.forEach(object, function (value, key) {
newObject[key] = !(key in newObject) || !_this.isObject(value)
? value
: _this.merge(newObject[key], value);
});
});
return newObject;
};
Objects.prototype.values = function (object) {
var values = [];
Loops$1.forEach(object, function (value) {
values.push(value);
});
return values;
};
return Objects;
}());
var Objects$1 = new Objects();
var Strings = (function () {
function Strings() {
}
Strings.prototype.firstToUpper = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
Strings.prototype.generateHash = function (length, characters) {
if (characters === void 0) { characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; }
var hash = '';
while (length--) {
hash += characters.charAt(Math.floor(Math.random() * characters.length));
}
return hash;
};
Strings.prototype.sprintf = function (content, parameters) {
Loops$1.forEach(parameters, function (value, key) {
if (!['number', 'string'].includes(typeof value)) {
return;
}
content = content.replace(new RegExp('%' + key + '%', 'g'), value);
});
return content;
};
Strings.prototype.stripHtml = function (content) {
var el = document.createElement('div');
el.innerHTML = content;
return el.textContent || el.innerText || '';
};
Strings.prototype.truncate = function (content, length, separator, ending) {
if (separator === void 0) { separator = ' '; }
if (ending === void 0) { ending = '...'; }
if (content.length <= length) {
return content;
}
return content.substr(0, content.lastIndexOf(separator, length - 3)) + ending;
};
return Strings;
}());
var Strings$1 = new Strings();
var Validators = (function () {
function Validators() {
}
Validators.prototype.isEmpty = function (data) {
var dataType = typeof data;
if (dataType === 'undefined' || data === null) {
return true;
}
if (dataType === 'number') {
return false;
}
else if (dataType === 'string') {
return data.length === 0;
}
else if (dataType === 'object' || Array.isArray(data)) {
return Object.keys(data).length < 1;
}
};
return Validators;
}());
var Validators$1 = new Validators();
var Utils = {
Ajax: Ajax$1,
Console: Console$1,
Dom: Dom$1,
EventDispatcher: EventDispatcher$1,
FlashMessages: FlashMessages$1,
Json: Json$1,
LocalStorage: LocalStorage$1,
Loops: Loops$1,
Numbers: Numbers$1,
Objects: Objects$1,
Strings: Strings$1,
Validators: Validators$1
};
var Configurator = (function () {
function Configurator() {
this.ENV_DEV = 'dev';
this.ENV_PROD = 'prod';
this._parameters = {
env: this.ENV_PROD
};
if (typeof ApicartConfig !== 'undefined') {
this._parameters = Utils.Objects.merge(this._parameters, ApicartConfig);
}
}
Configurator.prototype.configure = function (parameters) {
this._parameters = Utils.Objects.merge(this._parameters, parameters);
Utils.EventDispatcher.dispatchEvent('apicart:configure');
};
Configurator.prototype.setEnvironment = function (environment) {
if (![this.ENV_PROD, this.ENV_DEV].includes(environment)) {
throw new Error('Unknown environment "' + environment + '".');
}
this._parameters.env = environment;
Utils.EventDispatcher.dispatchEvent('apicart:environment:changed');
};
Configurator.prototype.isDevEnv = function () {
return this._parameters.env === this.ENV_DEV;
};
Configurator.prototype.isProdEnv = function () {
return this._parameters.env === this.ENV_PROD;
};
Configurator.prototype.getEnvironment = function () {
return this._parameters.env;
};
Configurator.prototype.getParameter = function (keyPath) {
return Utils.Objects.find(this._parameters, keyPath);
};
return Configurator;
}());
var Configurator$1 = new Configurator();
var Storage = (function () {
function Storage() {
var _this = this;
this.STORAGE_KEY = 'apicart-1.0.0-alpha7';
this._cacheKey = null;
this._storage = {};
this.init();
Utils.EventDispatcher.addListener('apicart-storage', 'apicart:configure', function () {
_this.init();
});
}
Storage.prototype.init = function () {
this._cacheKey = Configurator$1.getParameter('storage.cacheKey');
var storage = Utils.LocalStorage.getItem(this.STORAGE_KEY);
if (storage && (!this._cacheKey || this._cacheKey === storage._cacheKey)) {
this._storage[this.STORAGE_KEY] = storage;
}
else {
this.clearStorage();
}
};
Storage.prototype.clearStorage = function () {
this._storage = {};
this._storage[this.STORAGE_KEY] = {
_cacheKey: Configurator$1.getParameter('storage.cacheKey') || null
};
this.saveStorage();
};
Storage.prototype.saveStorage = function () {
Utils.LocalStorage.setItem(this.STORAGE_KEY, this.getStorage());
};
Storage.prototype.find = function (keyPath) {
return Utils.Objects.find(this.getStorage(), keyPath);
};
Storage.prototype.getStorage = function () {
return this._storage[this.STORAGE_KEY];
};
Storage.prototype.getItem = function (keyPath) {
var storage = Utils.LocalStorage.getItem(this.STORAGE_KEY);
return Utils.Objects.find(storage, keyPath);
};
Storage.prototype.setItem = function (keyPath, value) {
Utils.Objects.assign(this.getStorage(), keyPath, value);
this.saveStorage();
};
Storage.prototype.updateItem = function (keyPath, value) {
var item = this.getItem(keyPath);
if (!item) {
this.setItem(keyPath, value);
return;
}
Utils.Objects.merge(item, value);
this.setItem(keyPath, item);
};
Storage.prototype.hasItem = function (keyPath) {
return this.getItem(keyPath) !== null;
};
Storage.prototype.removeItem = function (keyPath) {
Utils.Objects.delete(this._storage[this.STORAGE_KEY], keyPath);
this.saveStorage();
};
return Storage;
}());
var Storage$1 = new Storage();
var ApiCommunicator = (function () {
function ApiCommunicator() {
}
ApiCommunicator.prototype.call = function (url, query, variables, connectTimeout, withCredentials) {
return Utils.Ajax
.post(url, {
data: Utils.Json.stringify({
query: query,
variables: variables
}),
headers: {
'Content-Type': 'application/json'
},
withCredentials: withCredentials,
timeout: connectTimeout
})
.then(function (response) {
if (response.status === 401) {
throw '401 Unauthorized - check provided Payments API token';
}
else if (response.status === 404) {
throw '404 Not Found - data source was not found';
}
else if (response.status === 429) {
throw '429 Too Many Requests - read rate limit docs section';
}
else if (response.status !== 200) {
throw response.status + ' - please contact Apicart support';
}
return response;
})
.catch(function (error) {
Utils.Console.error(error);
});
};
ApiCommunicator.prototype.isSuccessResult = function (response, key, throwOnFailed) {
if (response === void 0) { response = null; }
if (throwOnFailed === void 0) { throwOnFailed = true; }
if (response === null) {
throw 'An error occurred, please try again in a few minutes.';
}
if (Utils.Validators.isEmpty(response)) {
throw 'Response is empty.';
}
var responseData = response.data;
if (!Utils.Objects.keyExists(responseData, 'data.' + key + '.result')) {
throw 'Response doesn\'t contains valid result.';
}
if (throwOnFailed && responseData.data[key].result !== 'SUCCESS') {
throw Utils.Strings.sprintf('Response returned result "%0%" with message "%1%".', [responseData.data[key].result, responseData.data[key]['message'] || '']);
}
return true;
};
return ApiCommunicator;
}());
var ApiCommunicator$1 = new ApiCommunicator();
var Core = (function () {
function Core() {
this.ApiCommunicator = ApiCommunicator$1;
this.Configurator = Configurator$1;
this.Storage = Storage$1;
this.Utils = Utils;
}
Core.prototype.setDevEnv = function () {
this.Configurator.setEnvironment(this.Configurator.ENV_DEV);
return this;
};
Core.prototype.setProdEnv = function () {
this.Configurator.setEnvironment(this.Configurator.ENV_PROD);
return this;
};
Core.prototype.configure = function (config) {
this.Configurator.configure(config);
return this;
};
Core.prototype.isDevEnv = function () {
return this.Configurator.isDevEnv();
};
Core.prototype.isProdEnv = function () {
return this.Configurator.isProdEnv();
};
Core.prototype.getConfigParameter = function (keyPath) {
return this.Configurator.getParameter(keyPath);
};
return Core;
}());
var Core$1 = new Core();
return Core$1;
})));