@ema/js-base-library
Version:
This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.2.0.
1,414 lines (1,406 loc) • 143 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define('@ema/js-base-library', ['exports'], factory) :
(factory((global.ema = global.ema || {}, global.ema['js-base-library'] = {})));
}(this, (function (exports) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(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 };
}
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var BaseApi = /** @class */ (function () {
function BaseApi() {
this.headers = {};
this.routes = {};
this.baseUrl = '/api';
this.idField = 'id';
this.requestCredentials = 'same-origin'; // include, same-origin, *omit (default)
// include, same-origin, *omit (default)
this.corsMode = 'same-origin'; // no-cors, cors, *same-origin (default)
// no-cors, cors, *same-origin (default)
this.cachePolicy = 'no-cache'; // *default, no-cache, reload, force-cache, only-if-cached
this.entities = {};
this.hasDebugger = false;
}
/**
* @param {?} settings
* @return {?}
*/
BaseApi.prototype.init = /**
* @param {?} settings
* @return {?}
*/
function (settings) {
var _this = this;
this.settings = settings;
if (this.settings.host) {
this.baseUrl = settings.host;
}
if (this.settings.routes) {
this.initApiRoutes(this.settings.routes);
}
if (this.settings.headers) {
/** @type {?} */
var self_1 = this;
this.settings.headers.forEach(( /**
* @param {?} obj
* @return {?}
*/function (obj) {
for (var k in obj) {
self_1.headers[k] = obj[k];
}
}));
}
if (this['httpHeaders']) {
// AngularJs only
Object.keys(this.headers).forEach(( /**
* @param {?} k
* @return {?}
*/function (k) {
_this['httpHeaders'].set(k, _this.headers[k]);
}));
}
// if ('withCredentials' in new XMLHttpRequest) {
// this.cors = true;
// }
};
/**
* @param {?} url
* @return {?}
*/
BaseApi.prototype.route = /**
* @param {?} url
* @return {?}
*/
function (url) {
var _this = this;
/** @type {?} */
var mappedUrl;
Object.keys(this.routes).forEach(( /**
* @param {?} k
* @return {?}
*/function (k) {
if (k === url) {
mappedUrl = _this.routes[k];
}
}));
if (mappedUrl) {
return mappedUrl;
}
else {
return url;
}
};
// CRUD
// CRUD
/**
* @param {?} path
* @param {?} data
* @return {?}
*/
BaseApi.prototype.post =
// CRUD
/**
* @param {?} path
* @param {?} data
* @return {?}
*/
function (path, data) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch("" + this.baseUrl + path, {
body: JSON.stringify(data),
// must match 'Content-Type' header
cache: this.cachePolicy,
credentials: this.requestCredentials,
headers: this.headers,
mode: this.corsMode,
method: 'POST',
})
.then(( /**
* @param {?} response
* @return {?}
*/function (response) {
if (response.status >= 400) {
console.log(response);
console.error('Bad response from server');
return response;
}
return response.json();
}))
.catch(this.errorHandler)
.then(( /**
* @param {?} data
* @return {?}
*/function (data) {
return data;
}))];
case 1:
result = _a.sent();
return [2 /*return*/, result];
}
});
});
};
/**
* @param {?} path
* @param {?=} params
* @return {?}
*/
BaseApi.prototype.get = /**
* @param {?} path
* @param {?=} params
* @return {?}
*/
function (path, params) {
if (params === void 0) {
params = undefined;
}
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (params) {
path += '?';
Object.keys(params).forEach(( /**
* @param {?} key
* @return {?}
*/function (key) { return path += key + '=' + params[key] + '&'; }));
}
return [4 /*yield*/, fetch("" + this.baseUrl + path, {
cache: this.cachePolicy,
credentials: this.requestCredentials,
headers: this.headers,
mode: this.corsMode,
method: 'GET',
}).then(( /**
* @param {?} response
* @return {?}
*/function (response) {
if (response.status >= 400) {
console.log(response);
console.log('Bad response from server');
return response;
}
return response.json();
}))
.catch(this.errorHandler)
.then(( /**
* @param {?} data
* @return {?}
*/function (data) {
return data;
}))];
case 1:
result = _a.sent();
return [2 /*return*/, result];
}
});
});
};
// todo: patch
// todo: patch
/**
* @param {?} path
* @param {?} id
* @param {?} data
* @return {?}
*/
BaseApi.prototype.patch =
// todo: patch
/**
* @param {?} path
* @param {?} id
* @param {?} data
* @return {?}
*/
function (path, id, data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch("" + this.baseUrl + path + "/" + id, {
headers: this.headers,
// method: 'PATCH',
method: 'patch',
body: JSON.stringify(data)
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
// fixme: causes php server error on drupal content page
// fixme: causes php server error on drupal content page
/**
* @param {?} path
* @param {?} id
* @return {?}
*/
BaseApi.prototype.delete =
// fixme: causes php server error on drupal content page
/**
* @param {?} path
* @param {?} id
* @return {?}
*/
function (path, id) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
console.log(path, id);
return [2 /*return*/];
});
});
};
/**
* @param {?} username
* @param {?} password
* @return {?}
*/
BaseApi.prototype.login = /**
* @param {?} username
* @param {?} password
* @return {?}
*/
function (username, password) {
console.log(username, password.length);
};
/**
* @param {?=} namespace
* @param {?=} refresh
* @return {?}
*/
BaseApi.prototype.logout = /**
* @param {?=} namespace
* @param {?=} refresh
* @return {?}
*/
function (namespace, refresh) {
if (namespace === void 0) {
namespace = 'app:authData';
}
if (refresh === void 0) {
refresh = false;
}
this.clearCredentials(namespace);
this.settings.authenticated = false;
if (refresh) {
// location.href = location.origin;
location.href = location.href;
}
};
// todo: use btoa + atob
// todo: use btoa + atob
/**
* @param {?} credentials
* @param {?=} namespace
* @return {?}
*/
BaseApi.prototype.setCredentials =
// todo: use btoa + atob
/**
* @param {?} credentials
* @param {?=} namespace
* @return {?}
*/
function (credentials, namespace) {
if (namespace === void 0) {
namespace = 'app-auth';
}
this.credentials = credentials;
// window.localStorage.setItem(namespace, btoa(JSON.stringify(credentials)));
if (typeof window !== 'undefined' && window.localStorage) {
window.localStorage.setItem(namespace, JSON.stringify(credentials));
}
};
/**
* @param {?=} namespace
* @return {?}
*/
BaseApi.prototype.getCredentials = /**
* @param {?=} namespace
* @return {?}
*/
function (namespace) {
if (namespace === void 0) {
namespace = 'app:authData';
}
if (typeof window !== 'undefined' && window.localStorage && window.localStorage.getItem(namespace)) {
// return JSON.parse(atob(window.localStorage.getItem(namespace)));
return JSON.parse(window.localStorage.getItem(namespace));
}
};
/**
* @param {?=} namespace
* @return {?}
*/
BaseApi.prototype.clearCredentials = /**
* @param {?=} namespace
* @return {?}
*/
function (namespace) {
if (namespace === void 0) {
namespace = 'app:authData';
}
if (typeof window !== 'undefined' && window.localStorage.getItem(namespace)) {
window.localStorage.removeItem(namespace);
}
};
/**
* @param {?} routes
* @return {?}
*/
BaseApi.prototype.initApiRoutes = /**
* @param {?} routes
* @return {?}
*/
function (routes) {
/** @type {?} */
var self = this;
routes.forEach(( /**
* @param {?} obj
* @return {?}
*/function (obj) {
for (var k in obj) {
self.routes[k] = obj[k];
}
}));
if (self.settings.dev && self.settings.routes_dev) {
self.settings.routes_dev.forEach(( /**
* @param {?} obj
* @return {?}
*/function (obj) {
for (var k in obj) {
self.routes[k] = obj[k];
}
}));
}
};
// todo
// todo
/**
* @param {?} error
* @return {?}
*/
BaseApi.prototype.errorHandler =
// todo
/**
* @param {?} error
* @return {?}
*/
function (error) {
// AppService.scope.$broadcast('formError', error);
console.error(error);
if (!error) {
return;
}
// if(error.data === "token expired"){
// toastr.warning($filter('translate')('LOGIN EXPIRED')+'.');
// service.logOut();
// return;
// }
// if (error.statusText === 'Bad Request' || error.status == 400) {
// if (error.data.message) {
// toastr.warning($filter('translate')(error.data.message));
// } else {
// toastr.warning($filter('translate')('ERROR BAD REQUEST') + '.');
// }
// }
// if(error.statusText === 'Unauthorized' || error.status == 401){
// toastr.warning($filter('translate')('UNAUTHORIZED ERROR')+'.');
// service.logOut();
// return;
// }
// if(error.statusText === 'Not found' || error.status == 404){
// toastr.warning($filter('translate')('ERROR NOT FOUND')+'.');
// }
};
// entities local storage todo: move to storage.js
// entities local storage todo: move to storage.js
/**
* @param {?} resource
* @return {?}
*/
BaseApi.prototype.saveLocalResource =
// entities local storage todo: move to storage.js
/**
* @param {?} resource
* @return {?}
*/
function (resource) {
localStorage.setItem(resource[this.idField], resource);
};
/**
* @param {?} ID
* @return {?}
*/
BaseApi.prototype.loadLocalResource = /**
* @param {?} ID
* @return {?}
*/
function (ID) {
if (localStorage.getItem(ID)) {
localStorage.getItem(ID);
}
};
/**
* @param {?} ID
* @return {?}
*/
BaseApi.prototype.flushLocalResource = /**
* @param {?} ID
* @return {?}
*/
function (ID) {
if (localStorage.getItem(ID)) {
localStorage.removeItem(ID);
}
};
return BaseApi;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/*
base class for vanilla-js webcomponents
*/
var /*
base class for vanilla-js webcomponents
*/ BaseWebComponent = /** @class */ (function (_super) {
__extends(BaseWebComponent, _super);
function BaseWebComponent() {
var _this = _super.call(this) || this;
_this.data = {};
return _this;
}
/**
* @return {?}
*/
BaseWebComponent.prototype.init = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/];
});
});
};
/**
* @return {?}
*/
BaseWebComponent.prototype.render = /**
* @return {?}
*/
function () { };
/**
* @return {?}
*/
BaseWebComponent.prototype.definePublicMethods = /**
* @return {?}
*/
function () { };
/**
* @return {?}
*/
BaseWebComponent.prototype.remove = /**
* @return {?}
*/
function () { };
/**
* @param {?} name
* @param {?} oldVal
* @param {?} newVal
* @return {?}
*/
BaseWebComponent.prototype.attributeChangedCallback = /**
* @param {?} name
* @param {?} oldVal
* @param {?} newVal
* @return {?}
*/
function (name, oldVal, newVal) { };
/**
* @return {?}
*/
BaseWebComponent.prototype.connectedCallback = /**
* @return {?}
*/
function () {
var _this = this;
/** @type {?} */
var shadowRoot;
this.data = {};
if (!this.shadowRoot) {
shadowRoot = this.root = this.attachShadow({
mode: 'open'
});
}
else {
shadowRoot = this.root = this.shadowRoot;
}
this.el = shadowRoot.appendChild(this.template.content.cloneNode(true));
this.setState = this.setState.bind(this);
this.getState = this.getState.bind(this);
this.removeState = this.removeState.bind(this);
this.getData = this.getData.bind(this);
this.setData = this.setData.bind(this);
if (this.definePublicMethods) {
this.definePublicMethods();
}
if (this.init) {
this.init = this.init.bind(this);
}
if (this.dataJson) {
this.data = JSON.parse(this.dataJson);
}
if (this.init) {
this.init().then(( /**
* @return {?}
*/function () {
_this.preRender();
}));
}
else {
this.preRender();
}
};
Object.defineProperty(BaseWebComponent.prototype, "template", {
get: /**
* @return {?}
*/ function () {
if (this._template) {
return this._template;
}
this._template = document.createElement('template');
/** @type {?} */
var styles = document.createElement('style');
/** @type {?} */
var content = document.createElement('div');
/** @type {?} */
var imports = document.createElement('head');
imports.innerHTML = this.imports || "";
styles.innerHTML = this.styles || "";
content.innerHTML = this.htmlTemplate || "";
content.className = 'content';
this._template.content.appendChild(styles);
this._template.content.appendChild(imports);
this._template.content.appendChild(content);
return this._template;
},
enumerable: true,
configurable: true
});
/**
* @param {?} propName
* @param {?} getFn
* @param {?} setFn
* @return {?}
*/
BaseWebComponent.prototype.declareProp = /**
* @param {?} propName
* @param {?} getFn
* @param {?} setFn
* @return {?}
*/
function (propName, getFn, setFn) {
var _this = this;
/** @type {?} */
var obj = {};
// default getters / setters
if (!getFn) {
getFn = ( /**
* @return {?}
*/function () {
if (this.getAttribute(propName) !== null) {
return this.getAttribute(propName);
}
else {
return '';
}
});
}
if (!setFn) {
setFn = ( /**
* @param {?} value
* @return {?}
*/function (value) {
this.setAttribute(propName, value);
});
}
// current-state: getter / setter
if (propName === 'current-state') {
// getFn = () => {
// return this.getAttribute(propName);
// };
setFn = ( /**
* @param {?} value
* @return {?}
*/function (value) {
if (_this.isJson(value)) {
_this.setState(JSON.parse(value));
}
else {
_this.setState({ value: value });
}
// 2 way state
if (_this.sharedState) {
_this.setAttribute(propName, JSON.stringify(_this.state));
}
else {
_this.setAttribute(propName, value);
}
});
}
// current-state: getter / setter
if (propName === 'data-json') {
// getFn = () => {
// return this.getAttribute(propName);
// };
setFn = ( /**
* @param {?} value
* @return {?}
*/function (value) {
/** @type {?} */
var data = JSON.parse(value);
Object.keys(data).forEach(( /**
* @param {?} k
* @return {?}
*/function (k) {
_this.data[k] = data[k];
}));
_this.setAttribute(propName, value);
});
}
// obj[propName] = {get: getFn, set: setFn};
obj[this.kebabToLowerCamelCase(propName)] = { get: getFn, set: setFn };
Object.defineProperties(this, obj);
};
/**
* @param {?} eventName
* @param {?} detail
* @return {?}
*/
BaseWebComponent.prototype.dispatch = /**
* @param {?} eventName
* @param {?} detail
* @return {?}
*/
function (eventName, detail) {
this.dispatchEvent(new CustomEvent(eventName, { bubbles: true, detail: detail }));
};
// state management
// state management
/**
* @param {?} state
* @return {?}
*/
BaseWebComponent.prototype.setState =
// state management
/**
* @param {?} state
* @return {?}
*/
function (state) {
if (typeof state === 'string' && !this.isJson(state)) {
console.error('setState only accepts an object as argument');
return;
}
if (typeof state === 'string' && this.isJson(state)) {
state = JSON.parse(state);
}
this.state = __assign({}, this.state, state);
};
/**
* @param {?} key
* @return {?}
*/
BaseWebComponent.prototype.getState = /**
* @param {?} key
* @return {?}
*/
function (key) {
if (key && this.state[key]) {
return JSON.parse(JSON.stringify(this.state[key]));
}
else {
return JSON.parse(JSON.stringify(this.state));
}
};
/**
* @param {?} key
* @return {?}
*/
BaseWebComponent.prototype.removeState = /**
* @param {?} key
* @return {?}
*/
function (key) {
if (!key) {
this.state = {};
this.currentState = '{}';
this.preRender();
}
else {
delete this.state[key];
}
};
// data management
// data management
/**
* @param {?} object
* @param {?} extend
* @return {?}
*/
BaseWebComponent.prototype.setData =
// data management
/**
* @param {?} object
* @param {?} extend
* @return {?}
*/
function (object, extend) {
var _this = this;
if (extend) {
Object.keys(object).forEach(( /**
* @param {?} k
* @param {?} i
* @return {?}
*/function (k, i) {
_this.data[k] = object[k];
}));
}
else {
this.data = object;
}
this.preRender();
};
/**
* @return {?}
*/
BaseWebComponent.prototype.getData = /**
* @return {?}
*/
function () {
return this.data;
};
/**
* @return {?}
*/
BaseWebComponent.prototype.preRender = /**
* @return {?}
*/
function () {
if (this.root) {
this.root.querySelector('.content')['innerHTML'] = this.render();
}
};
// utils
// utils
/**
* @param {?} jsonString
* @return {?}
*/
BaseWebComponent.prototype.isJson =
// utils
/**
* @param {?} jsonString
* @return {?}
*/
function (jsonString) {
try {
/** @type {?} */
var o = JSON.parse(jsonString);
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};
/**
* @param {?} str
* @return {?}
*/
BaseWebComponent.prototype.kebabToLowerCamelCase = /**
* @param {?} str
* @return {?}
*/
function (str) {
/** @type {?} */
var string = str.charAt(0).toLowerCase() + str.slice(1);
return string.replace(/(\-\w)/g, ( /**
* @param {?} m
* @return {?}
*/function (m) {
return m[1].toUpperCase();
}));
};
return BaseWebComponent;
}(HTMLElement));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var Util = /** @class */ (function () {
function Util() {
}
/**
* @param {?} arr
* @param {?} value
* @return {?}
*/
Util.arrayRemoveValue = /**
* @param {?} arr
* @param {?} value
* @return {?}
*/
function (arr, value) {
// todo: implement for complex objects
/** @type {?} */
var arr2 = arr.filter(( /**
* @param {?} ele
* @return {?}
*/function (ele) {
return ele != value;
}));
return arr2;
// ex: var result = arrayRemove(array, 'myRemoveString');
};
/**
* @param {?} arr
* @return {?}
*/
Util.arraySetUnique = /**
* @param {?} arr
* @return {?}
*/
function (arr) {
/** @type {?} */
var obj = {};
for (var a = 0; a < arr.length; a++)
obj[arr[a]] = true;
/** @type {?} */
var resultarr = [];
for (var o in obj)
resultarr.push(o);
return resultarr;
};
/**
* @param {?} o
* @return {?}
*/
Util.castToType = /**
* @param {?} o
* @return {?}
*/
function (o) {
/** @type {?} */
var value = o;
if (Number(value) && value !== "true" && value !== "false") {
value = Number(value);
}
if (value === "0") {
value = 0;
}
if (value === "true") {
value = true;
}
if (value === "false") {
value = false;
}
return value;
};
/**
* @param {?} obj
* @return {?}
*/
Util.copy = /**
* @param {?} obj
* @return {?}
*/
function (obj) {
return JSON.parse(JSON.stringify(obj));
};
/**
* @param {?} url
* @return {?}
*/
Util.fetchJson = /**
* @param {?} url
* @return {?}
*/
function (url) {
return __awaiter(this, void 0, void 0, function () {
var response, json;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch(url).catch(( /**
* @param {?} error
* @return {?}
*/function (error) {
console.error(error);
}))];
case 1:
response = _a.sent();
return [4 /*yield*/, response.json()];
case 2:
json = _a.sent();
return [2 /*return*/, json];
}
});
});
};
/**
* @param {?} jsonString
* @return {?}
*/
Util.tryParseJSON = /**
* @param {?} jsonString
* @return {?}
*/
function (jsonString) {
try {
/** @type {?} */
var o = JSON.parse(jsonString);
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};
/**
* Returns the global object of the environment the application is running in (browser, node, web worker, or frame)
*/
/**
* Returns the global object of the environment the application is running in (browser, node, web worker, or frame)
* @return {?}
*/
Util.getGlobal = /**
* Returns the global object of the environment the application is running in (browser, node, web worker, or frame)
* @return {?}
*/
function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
// @ts-ignore
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
};
/**
* Returns the current date as milliseconds since midnight Jan 1, 1970.
*/
/**
* Returns the current date as milliseconds since midnight Jan 1, 1970.
* @param {?=} date
* @return {?}
*/
Util.getTimeStamp = /**
* Returns the current date as milliseconds since midnight Jan 1, 1970.
* @param {?=} date
* @return {?}
*/
function (date) {
if (date === void 0) {
date = null;
}
if (date) {
if (typeof date === 'string') {
return Math.round(+new Date(date));
}
else {
return Math.round(+date);
}
}
else {
return Math.round(+new Date());
}
};
/**
* Returns the current date as seconds since midnight Jan 1, 1970.
*/
/**
* Returns the current date as seconds since midnight Jan 1, 1970.
* @param {?=} date
* @return {?}
*/
Util.getUnixTimeStamp = /**
* Returns the current date as seconds since midnight Jan 1, 1970.
* @param {?=} date
* @return {?}
*/
function (date) {
if (date === void 0) {
date = null;
}
return Math.floor(Util.getTimeStamp(date) / 1000);
};
/**
* Returns a UUID.
*/
/**
* Returns a UUID.
* @return {?}
*/
Util.getUUID = /**
* Returns a UUID.
* @return {?}
*/
function () {
/** @type {?} */
var d = new Date().getTime();
/** @type {?} */
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, ( /**
* @param {?} c
* @return {?}
*/function (c) {
/** @type {?} */
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
}));
return uuid;
};
/**
* Checks if the application is running in a browser.
*/
/**
* Checks if the application is running in a browser.
* @return {?}
*/
Util.isBrowser = /**
* Checks if the application is running in a browser.
* @return {?}
*/
function () {
return typeof window !== 'undefined';
};
/**
* Checks if the application is running in a browser and online.
*/
/**
* Checks if the application is running in a browser and online.
* @return {?}
*/
Util.isOnline = /**
* Checks if the application is running in a browser and online.
* @return {?}
*/
function () {
if (typeof window !== 'undefined' && window.navigator.onLine) {
return true;
}
else {
return false;
}
};
return Util;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var ObjectUtil = /** @class */ (function () {
function ObjectUtil() {
}
/**
* @param {?} target
* @param {...?} sources
* @return {?}
*/
ObjectUtil.deepAssign = /**
* @param {?} target
* @param {...?} sources
* @return {?}
*/
function (target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
if (!sources.length) {
return target;
}
/** @type {?} */
var source = sources.shift();
if (source === undefined) {
return target;
}
if (ObjectUtil.isMergebleObject(target) && ObjectUtil.isMergebleObject(source)) {
Object.keys(source).forEach(( /**
* @param {?} key
* @return {?}
*/function (key) {
if (ObjectUtil.isMergebleObject(source[key])) {
if (!target[key]) {
target[key] = {};
}
ObjectUtil.deepAssign(target[key], source[key]);
}
else {
target[key] = source[key];
}
}));
}
return ObjectUtil.deepAssign.apply(ObjectUtil, __spread([target], sources));
};
/**
* @param {?} item
* @return {?}
*/
ObjectUtil.isMergebleObject = /**
* @param {?} item
* @return {?}
*/
function (item) {
return ObjectUtil.isObject(item) && !Array.isArray(item);
};
/**
* @param {?} item
* @return {?}
*/
ObjectUtil.isObject = /**
* @param {?} item
* @return {?}
*/
function (item) {
return item !== null && typeof item === 'object';
};
return ObjectUtil;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var Storage = /** @class */ (function () {
function Storage() {
}
/**
* @param {?} model
* @param {?=} modelName
* @return {?}
*/
Storage.saveLocalModel = /**
* @param {?} model
* @param {?=} modelName
* @return {?}
*/
function (model, modelName) {
if (modelName === void 0) {
modelName = 'model';
}
if (typeof window !== 'undefined' && window.localStorage) {
// window.localStorage.setItem(modelName , btoa(JSON.stringify(model)));
window.localStorage.setItem(modelName, JSON.stringify(model));
window.localStorage.setItem(modelName + '-changed', String(Math.round(+new Date() / 1000)));
}
else {
console.error('localStorage not available: not running in a browser');
}
};
/**
* @param {?=} modelName
* @return {?}
*/
Storage.restoreLocalModel = /**
* @param {?=} modelName
* @return {?}
*/
function (modelName) {
if (modelName === void 0) {
modelName = 'model';
}
if (typeof window !== 'undefined' && window.localStorage) {
if (localStorage.getItem(modelName)) {
// return JSON.parse(atob(localStorage.getItem(modelName)));
return JSON.parse(localStorage.getItem(modelName));
}
}
else {
console.error('localStorage not available: not running in a browser');
}
};
/**
* @param {?=} modelName
* @return {?}
*/
Storage.flushLocalModel = /**
* @param {?=} modelName
* @return {?}
*/
function (modelName) {
if (modelName === void 0) {
modelName = 'model';
}
if (typeof window !== 'undefined' && window.localStorage) {
if (localStorage.getItem(modelName)) {
localStorage.removeItem(modelName);
}