UNPKG

@apicart/vue-components

Version:

Apicart Vue.Js components for simple e-commerce platform development

1,172 lines (1,139 loc) 626 kB
/** * @apicart/vue-components 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'; function styleInject(css, ref) { if ( ref === void 0 ) ref = {}; var insertAt = ref.insertAt; if (!css || typeof document === 'undefined') { return; } var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (insertAt === 'top') { if (head.firstChild) { head.insertBefore(style, head.firstChild); } else { head.appendChild(style); } } else { head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } } var css_248z = "@font-face {\n font-family: 'apicart-icons';\n src: url('data:font/woff;base64,d09GRgABAAAAAArMAAsAAAAACoAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABCAAAAGAAAABgDxIF8WNtYXAAAAFoAAAAXAAAAFzpQ+m8Z2FzcAAAAcQAAAAIAAAACAAAABBnbHlmAAABzAAABlAAAAZQla7j+GhlYWQAAAgcAAAANgAAADYYnMfiaGhlYQAACFQAAAAkAAAAJAeXA8xobXR4AAAIeAAAACwAAAAsIgADOGxvY2EAAAikAAAAGAAAABgFQgbwbWF4cAAACLwAAAAgAAAAIAARAHVuYW1lAAAI3AAAAc4AAAHO8dCgtXBvc3QAAAqsAAAAIAAAACAAAwAAAAMDwAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA6QcDwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEA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AScmIgcGFBfi4uINDQwkDOLiDCQMDQ3i4g0NDCQM4uIMJAwNDQKN4uINIwwNDeHhDQ0MIw3i4gwjDQwM4uIMDA0jDAAAAAEAAAABAACvd1n1Xw889QALBAAAAAAA2tRByAAAAADa1EHIAAD/1QPVA4AAAAAIAAIAAAAAAAAAAQAAA8D/wAAABAAAAAAAA9UAAQAAAAAAAAAAAAAAAAAAAAsEAAAAAAAAAAAAAAACAAAABAAAqwQAAKsEAABVBAAAKwQAACsEAABVBAAA4gAAAAAACgAUAB4AOABqARQBvgJoAvIDKAABAAAACwBzAAUAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAADgCuAAEAAAAAAAEADQAAAAEAAAAAAAIABwCWAAEAAAAAAAMADQBIAAEAAAAAAAQADQCrAAEAAAAAAAUACwAnAAEAAAAAAAYADQBvAAEAAAAAAAoAGgDSAAMAAQQJAAEAGgANAAMAAQQJAAIADgCdAAMAAQQJAAMAGgBVAAMAAQQJAAQAGgC4AAMAAQQJAAUAFgAyAAMAAQQJAAYAGgB8AAMAAQQJAAoANADsYXBpY2FydC1pY29ucwBhAHAAaQBjAGEAcgB0AC0AaQBjAG8AbgBzVmVyc2lvbiAxLjAAVgBlAHIAcwBpAG8AbgAgADEALgAwYXBpY2FydC1pY29ucwBhAHAAaQBjAGEAcgB0AC0AaQBjAG8AbgBzYXBpY2FydC1pY29ucwBhAHAAaQBjAGEAcgB0AC0AaQBjAG8AbgBzUmVndWxhcgBSAGUAZwB1AGwAYQByYXBpY2FydC1pY29ucwBhAHAAaQBjAGEAcgB0AC0AaQBjAG8AbgBzRm9udCBnZW5lcmF0ZWQgYnkgSWNvTW9vbi4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==') format('woff');\n font-weight: normal;\n font-style: normal;\n font-display: block;\n}\n\n[class^=\"apicart-icon-\"], [class*=\" apicart-icon-\"] {\n /* use !important to prevent issues with browser extensions that change fonts */\n font-family: 'apicart-icons' !important;\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n\n /* Better Font Rendering =========== */\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.apicart-icon-image:before {\n content: \"\\e902\";\n}\n.apicart-icon-x:before {\n content: \"\\e907\";\n}\n.apicart-icon-minus:before {\n content: \"\\e900\";\n}\n.apicart-icon-plus:before {\n content: \"\\e901\";\n}\n.apicart-icon-arrow-left-circle:before {\n content: \"\\e903\";\n}\n.apicart-icon-arrow-right-circle:before {\n content: \"\\e904\";\n}\n.apicart-icon-shopping-bag:before {\n content: \"\\e905\";\n}\n"; styleInject(css_248z); /** * Utils.js v1.0.0-alpha7 * (c) 2018-2020 Apicart Company * Released under the MIT License. */ /** * 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(); /** * Utils.js v1.0.0-alpha7 * (c) 2018-2020 Apicart Company * Released under the MIT License. */ /*! ***************************************************************************** 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. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var PaymentGateway = (function () { function PaymentGateway(code, enabled, id, name) { this._code = code; this._enabled = enabled; this._id = id; this._name = name; } PaymentGateway.prototype.getCode = function () { return this._code; }; PaymentGateway.prototype.setCode = function (code) { this._code = code; }; PaymentGateway.prototype.isEnabled = function () { return this._enabled; }; PaymentGateway.prototype.setEnabled = function (enabled) { this._enabled