UNPKG

@ema/js-base-library

Version:

This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.2.0.

1,731 lines (1,718 loc) 84.6 kB
import { __awaiter } from 'tslib'; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class BaseApi { constructor() { 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 {?} */ init(settings) { 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 {?} */ const self = this; this.settings.headers.forEach((/** * @param {?} obj * @return {?} */ (obj) => { for (const k in obj) { self.headers[k] = obj[k]; } })); } if (this['httpHeaders']) { // AngularJs only Object.keys(this.headers).forEach((/** * @param {?} k * @return {?} */ (k) => { this['httpHeaders'].set(k, this.headers[k]); })); } // if ('withCredentials' in new XMLHttpRequest) { // this.cors = true; // } } ; /** * @param {?} url * @return {?} */ route(url) { /** @type {?} */ let mappedUrl; Object.keys(this.routes).forEach((/** * @param {?} k * @return {?} */ (k) => { if (k === url) { mappedUrl = this.routes[k]; } })); if (mappedUrl) { return mappedUrl; } else { return url; } } // CRUD /** * @param {?} path * @param {?} data * @return {?} */ post(path, data) { return __awaiter(this, void 0, void 0, function* () { /** @type {?} */ const result = 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 {?} */ (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 {?} */ (data) => { return data; })); return result; }); } /** * @param {?} path * @param {?=} params * @return {?} */ get(path, params = undefined) { return __awaiter(this, void 0, void 0, function* () { if (params) { path += '?'; Object.keys(params).forEach((/** * @param {?} key * @return {?} */ key => path += key + '=' + params[key] + '&')); } /** @type {?} */ const result = yield fetch(`${this.baseUrl}${path}`, { cache: this.cachePolicy, credentials: this.requestCredentials, headers: this.headers, mode: this.corsMode, method: 'GET', }).then((/** * @param {?} response * @return {?} */ (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 {?} */ (data) => { return data; })); return result; }); } // todo: patch /** * @param {?} path * @param {?} id * @param {?} data * @return {?} */ patch(path, id, data) { return __awaiter(this, void 0, void 0, function* () { yield fetch(`${this.baseUrl}${path}/` + id, { headers: this.headers, // method: 'PATCH', method: 'patch', body: JSON.stringify(data) }); }); } // fixme: causes php server error on drupal content page /** * @param {?} path * @param {?} id * @return {?} */ delete(path, id) { return __awaiter(this, void 0, void 0, function* () { console.log(path, id); // await fetch(`${this.baseUrl}${path}/` + id, { //     headers: this.headers, // //  method: 'DELETE' //     method: 'delete' // }); }); } /** * @param {?} username * @param {?} password * @return {?} */ login(username, password) { console.log(username, password.length); } /** * @param {?=} namespace * @param {?=} refresh * @return {?} */ logout(namespace = 'app:authData', refresh = false) { this.clearCredentials(namespace); this.settings.authenticated = false; if (refresh) { // location.href = location.origin; location.href = location.href; } } // todo: use btoa + atob /** * @param {?} credentials * @param {?=} namespace * @return {?} */ setCredentials(credentials, 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 {?} */ getCredentials(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 {?} */ clearCredentials(namespace = 'app:authData') { if (typeof window !== 'undefined' && window.localStorage.getItem(namespace)) { window.localStorage.removeItem(namespace); } } /** * @param {?} routes * @return {?} */ initApiRoutes(routes) { /** @type {?} */ const self = this; routes.forEach((/** * @param {?} obj * @return {?} */ (obj) => { for (let k in obj) { self.routes[k] = obj[k]; } })); if (self.settings.dev && self.settings.routes_dev) { self.settings.routes_dev.forEach((/** * @param {?} obj * @return {?} */ (obj) => { for (let k in obj) { self.routes[k] = obj[k]; } })); } } // todo /** * @param {?} error * @return {?} */ errorHandler(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 /** * @param {?} resource * @return {?} */ saveLocalResource(resource) { localStorage.setItem(resource[this.idField], resource); } /** * @param {?} ID * @return {?} */ loadLocalResource(ID) { if (localStorage.getItem(ID)) { localStorage.getItem(ID); } } /** * @param {?} ID * @return {?} */ flushLocalResource(ID) { if (localStorage.getItem(ID)) { localStorage.removeItem(ID); } } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /* base class for vanilla-js webcomponents */ class BaseWebComponent extends HTMLElement { constructor() { super(); this.data = {}; } /** * @return {?} */ init() { return __awaiter(this, void 0, void 0, function* () { }); } /** * @return {?} */ render() { } /** * @return {?} */ definePublicMethods() { } /** * @return {?} */ remove() { } /** * @param {?} name * @param {?} oldVal * @param {?} newVal * @return {?} */ attributeChangedCallback(name, oldVal, newVal) { } /** * @return {?} */ connectedCallback() { /** @type {?} */ let 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 {?} */ () => { this.preRender(); })); } else { this.preRender(); } } /** * @return {?} */ get template() { if (this._template) { return this._template; } this._template = document.createElement('template'); /** @type {?} */ let styles = document.createElement('style'); /** @type {?} */ let content = document.createElement('div'); /** @type {?} */ let 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; } /** * @param {?} propName * @param {?} getFn * @param {?} setFn * @return {?} */ declareProp(propName, getFn, setFn) { /** @type {?} */ let 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 {?} */ (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 {?} */ (value) => { /** @type {?} */ let data = JSON.parse(value); Object.keys(data).forEach((/** * @param {?} k * @return {?} */ (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 {?} */ dispatch(eventName, detail) { this.dispatchEvent(new CustomEvent(eventName, { bubbles: true, detail: detail })); } // state management /** * @param {?} state * @return {?} */ setState(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 = Object.assign({}, this.state, state); } /** * @param {?} key * @return {?} */ getState(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 {?} */ removeState(key) { if (!key) { this.state = {}; this.currentState = '{}'; this.preRender(); } else { delete this.state[key]; } } // data management /** * @param {?} object * @param {?} extend * @return {?} */ setData(object, extend) { if (extend) { Object.keys(object).forEach((/** * @param {?} k * @param {?} i * @return {?} */ (k, i) => { this.data[k] = object[k]; })); } else { this.data = object; } this.preRender(); } /** * @return {?} */ getData() { return this.data; } /** * @return {?} */ preRender() { if (this.root) { this.root.querySelector('.content')['innerHTML'] = this.render(); } } // utils /** * @param {?} jsonString * @return {?} */ isJson(jsonString) { try { /** @type {?} */ let o = JSON.parse(jsonString); if (o && typeof o === "object") { return o; } } catch (e) { } return false; } ; /** * @param {?} str * @return {?} */ kebabToLowerCamelCase(str) { /** @type {?} */ let string = str.charAt(0).toLowerCase() + str.slice(1); return string.replace(/(\-\w)/g, (/** * @param {?} m * @return {?} */ function (m) { return m[1].toUpperCase(); })); } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class Util { /** * @param {?} arr * @param {?} value * @return {?} */ static arrayRemoveValue(arr, value) { // todo: implement for complex objects /** @type {?} */ let arr2 = arr.filter((/** * @param {?} ele * @return {?} */ function (ele) { return ele != value; })); return arr2; // ex: var result = arrayRemove(array, 'myRemoveString'); } /** * @param {?} arr * @return {?} */ static arraySetUnique(arr) { /** @type {?} */ let obj = {}; for (let a = 0; a < arr.length; a++) obj[arr[a]] = true; /** @type {?} */ let resultarr = []; for (let o in obj) resultarr.push(o); return resultarr; } /** * @param {?} o * @return {?} */ static castToType(o) { /** @type {?} */ let 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 {?} */ static copy(obj) { return JSON.parse(JSON.stringify(obj)); } /** * @param {?} url * @return {?} */ static fetchJson(url) { return __awaiter(this, void 0, void 0, function* () { /** @type {?} */ const response = yield fetch(url).catch((/** * @param {?} error * @return {?} */ (error) => { console.error(error); })); /** @type {?} */ const json = yield response.json(); return json; }); } /** * @param {?} jsonString * @return {?} */ static tryParseJSON(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) * @return {?} */ static getGlobal() { // 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. * @param {?=} date * @return {?} */ static getTimeStamp(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. * @param {?=} date * @return {?} */ static getUnixTimeStamp(date = null) { return Math.floor(Util.getTimeStamp(date) / 1000); } /** * Returns a UUID. * @return {?} */ static getUUID() { /** @type {?} */ let d = new Date().getTime(); /** @type {?} */ const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (/** * @param {?} c * @return {?} */ function (c) { /** @type {?} */ const 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. * @return {?} */ static isBrowser() { return typeof window !== 'undefined'; } /** * Checks if the application is running in a browser and online. * @return {?} */ static isOnline() { if (typeof window !== 'undefined' && window.navigator.onLine) { return true; } else { return false; } } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class ObjectUtil { /** * @param {?} target * @param {...?} sources * @return {?} */ static deepAssign(target, ...sources) { if (!sources.length) { return target; } /** @type {?} */ const 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(target, ...sources); } /** * @param {?} item * @return {?} */ static isMergebleObject(item) { return ObjectUtil.isObject(item) && !Array.isArray(item); } /** * @param {?} item * @return {?} */ static isObject(item) { return item !== null && typeof item === 'object'; } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class Storage { /** * @param {?} model * @param {?=} modelName * @return {?} */ static saveLocalModel(model, 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 {?} */ static restoreLocalModel(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 {?} */ static flushLocalModel(modelName = 'model') { if (typeof window !== 'undefined' && window.localStorage) { if (localStorage.getItem(modelName)) { localStorage.removeItem(modelName); } if (localStorage.getItem(modelName + '-changed')) { localStorage.removeItem(modelName + '-changed'); } } else { console.error('localStorage not available: not running in a browser'); } } ; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class Config { constructor() { this._config = {}; this._locked = ['_config', '_defaults']; } /** * @param {?} key * @return {?} */ get(key) { return this._config[key]; } /** * @param {?} key * @param {?} value * @param {?=} castToType * @return {?} */ set(key, value, castToType = false) { if (!this.islocked(key)) { if (castToType) { value = Util.castToType(value); } return this._config[key] = value; } else { console.error('Config: property "' + key + '" can not be changed.'); } } /** * @param {?} object * @param {?=} extend * @param {?=} castToType * @return {?} */ add(object, extend = false, castToType = false) { /** @type {?} */ const self = this; if (!extend) { Object.keys(object).forEach((/** * @param {?} key * @return {?} */ (key) => { self.set(key, object[key], castToType); })); } else { this.extend(object); } } /** * @param {?} url * @param {?=} extend * @return {?} */ fetch(url, extend = false) { return __awaiter(this, void 0, void 0, function* () { /** @type {?} */ const self = this; // if(self.getVar('api_headers')){ // // } // let config = await fetch(url, {headers: self.getVar('api_headers')}) /** @type {?} */ let config = yield fetch(url) .then((/** * @param {?} response * @return {?} */ function (response) { return response.json(); })) .catch((/** * @param {?} error * @return {?} */ function (error) { console.log('config fetch error:', error.message); })); if (extend) { this.extend(config); } else { Object.keys(config).forEach((/** * @param {?} k * @param {?} i * @return {?} */ (k, i) => { self.set(k, config[k]); })); } return config; }); } /** * @param {?} object * @param {?=} target * @return {?} */ extend(object, target = this._config) { ObjectUtil.deepAssign(target, object); } /** * @return {?} */ all() { return this._config; } /** * @param {?} id * @return {?} */ getLocalSettings(id) { if (typeof window !== 'undefined') { if (window.localStorage && window.localStorage.getItem(id)) { this.add(Storage.restoreLocalModel(id)); } } } /** * @param {?} id * @param {?=} settings * @return {?} */ setLocalSettings(id, settings = this._config) { if (typeof window !== 'undefined') { if (window.localStorage) { Storage.saveLocalModel(settings, id); } } } /** * @param {?} configDefaults * @return {?} */ setDefaults(configDefaults) { /** @type {?} */ const self = this; self._defaults = configDefaults; Object.keys(configDefaults).forEach((/** * @param {?} k * @return {?} */ (k) => { self.set(k, Util.copy(configDefaults[k])); })); } /** * @return {?} */ restoreDefaults() { /** @type {?} */ const self = this; Object.keys(self._defaults).forEach((/** * @param {?} k * @return {?} */ (k) => { self.set(k, self._defaults[k]); })); } /** * @param {?} key * @return {?} */ islocked(key) { /** @type {?} */ let boolean = false; this._locked.forEach((/** * @param {?} k * @return {?} */ (k) => { if (k === key) { boolean = true; } })); return boolean; } // todo /** * @param {?} key * @return {?} */ lock(key) { // todo: return false; // this._locked.forEach((k) => { // // }) } /** * @param {?} key * @return {?} */ unLock(key) { // todo: // this._locked.forEach((k) => { // // }) } /** * @param {?} object * @return {?} */ initXdomain(object) { if (typeof window !== 'undefined' && window['xdomain']) { window['xdomain'].masters(object.masters); window['xdomain'].slaves(object.slaves); } } ; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const singleton = Symbol(); /** @type {?} */ const singletonEnforcer = Symbol(); class ConfigService extends Config { /** * @param {?} enforcer */ constructor(enforcer) { super(); if (enforcer !== singletonEnforcer) { throw new Error('Cannot construct singleton'); } this._type = 'ConfigService'; } /** * @return {?} */ static get instance() { if (!this[singleton]) { this[singleton] = new ConfigService(singletonEnforcer); } return this[singleton]; } /** * @return {?} */ get type() { return this._type; } /** * @param {?} value * @return {?} */ set type(value) { this._type = value; } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const configDefaults = { id: 'ema-js-base', name: 'ema-js-base', authenticated: false, version: '0.1.1', domain: 'ema-js-base.firebaseapp.com', baseUrl: 'https://ema-js-base.firebaseapp.com/', baseRoot: 'https://ema-js-base.firebaseapp.com', api_headers: [ { 'Content-Type': 'application/json;charset=utf-8' } ], language: 'en', languages: [ { key: 'nl', value: 'Nederlands' }, { key: 'en', value: 'English' }, ], roles: { ANONYMOUS: [ { "actions": ["read"], "subject": ["all"] }, { "actions": ["login"], "subject": ["user"] } ], AUTHENTICATED: [ { "actions": ["logout"], "subject": ["user"] } ], EDITOR: [ { "actions": ["create", "read", "update", "delete"], "subject": ["all"] } ], DEVELOPER: [ { "actions": ["create", "read", "update", "delete", "debug"], "subject": ["all"] } ], ADMINISTRATOR: [ { "actions": ["create", "read", "update", "delete", "administrate"], "subject": ["all"] }, { "actions": ["create", "read", "update", "delete"], "subject": ["user"] } ], OWNER: [ { "actions": ["create", "read", "update", "delete", "administrate", "debug", "autoLogin", "fetchCredentials"], "subject": ["all"] }, { "actions": ["create", "read", "update", "delete"], "subject": ["user"] } ] }, firebaseApps: { 'ema-js-base': { apiKey: "AIzaSyDQuSusOA5HNwIUoyViVOPwEWbGXWt91p4", authDomain: "ema-js-base.firebaseapp.com", databaseURL: "https://ema-js-base.firebaseio.com", projectId: "ema-js-base", storageBucket: "ema-js-base.appspot.com", messagingSenderId: "419979785648" }, 'app-base': { apiKey: "AIzaSyDds578OH_xcxGw7QiTDOCdweLRSBEyxng", authDomain: "app-base.firebaseapp.com", databaseURL: "https://app-base.firebaseio.com", projectId: "app-base-dce3f", storageBucket: "app-base-dce3f.appspot.com", messagingSenderId: "271464035830" } }, drupal: { domain: 'local.streamer.nl:8888', protocol: 'http:', app_uuid: '319e0e50-5f1b-4b76-8798-3f89da31dd12', }, wordpress: { host: 'wordpress-dev:8888', protocol: 'http:', base_path: '/', }, }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const en = { "ADD": "Add", "ADDRESS": "Address", "ADMIN": "Administration", "CANCEL": "Cancel", "CHANGE LANGUAGE": "Change language", "CLOSE": "Close", "CONFIRM": "Confirm", "CONFIRM WARNING": "This action cannot be undone", "CONTACT": "Contact", "COUNTRY": "Country", "CREATE": "Create", "CURRENT": "Current", "DATA": "Data", "DATE": "Date", "DATE_NTH": { "1": "{day} January {year}", "2": "{day} February {year}", "3": "{day} March {year}", "4": "{day} April {year}", "5": "{day} May {year}", "6": "{day} June {year}", "7": "{day} July {year}", "8": "{day} August {year}", "9": "{day} September {year}", "10": "{day} October {year}", "11": "{day} November {year}", "12": "{day} December {year}" }, "DATE_MONTH_NTH": { "1": "January", "2": "February", "3": "March", "4": "April", "5": "May", "6": "June", "7": "July", "8": "August", "9": "September", "10": "October", "11": "November", "12": "December" }, "DELETE": "Delete", "DELETE CONFIRM": "Are you sure you want to delete this item", "DELETE CONFIRM MULTIPLE": "Are you sure you want to delete these items", "DETAIL": "Detail", "DETAILS": "Details", "EDIT": "Edit", "EMAIL": "E-mail", "EMAIL ADDRESS": "E-mail address", "EMAIL ERROR": "This is not a valid email address", "ERROR": "Error", "FIELD": "Field", "FIELD REQUIRED": "This field is required", "FORM INVALID": "The form can not be submitted yet. Please fill in the required fields", "FORM SUCCESS": "The data have been stored", "LANGUAGE": "Language", "LOGIN": "Login", "LOGIN ERROR": "The credentials you provided are not valid", "LOGIN EXPIRED": "Your authorization has expired. Please login again", "LOGOUT": "Log out", "NAME": "Name", "NETWORK ERROR": "There is no internet connection", "PASSWORD": "Password", "PASSWORD ERROR": "Password is required", "PASSWORD MATCH ERROR": "The passwords don't match", "REMARKS": "Remarks", "REMEMBER": "Remember", "REQUIRED": "Required", "RESET": "Wissen", "RESULT": "Result", "RESULTS": "Results", "RESULTS_NTH": { "0": "No results", "1": "{n} result", "2": "{n} results", "n": "{n} results", "gt99": "99+ results" }, "SAVE": "Save", "SEARCH": "Search", "SUBMIT": "Submit", "TITLE": "Title", "USER": "User", "USERS": "Users", "USERNAME": "Username", "counter": 'The count is {n}' }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const nl = { "ADD": "Toevoegen", "ADDRESS": "Adres", "ADMIN": "Beheer", "CANCEL": "Annuleren", "CHANGE LANGUAGE": "Taal wijzigen", "CLOSE": "Sluiten", "CONFIRM": "Bevestigen", "CONFIRM WARNING": "Deze handeling kan niet ongedaan worden gemaakt", "CONTACT": "Contact", "COUNTRY": "Land", "CREATE": "Aanmaken", "CURRENT": "Huidige", "DATA": "Gegevens", "DATE": "Datum", "DATE_NTH": { "1": "{day} Januari {year}", "2": "{day} Februari {year}", "3": "{day} Maart {year}", "4": "{day} April {year}", "5": "{day} Mei {year}", "6": "{day} Juni {year}", "7": "{day} Juli {year}", "8": "{day} Augustus {year}", "9": "{day} September {year}", "10": "{day} Oktober {year}", "11": "{day} November {year}", "12": "{day} December {year}" }, "DATE_MONTH_NTH": { "1": "Januari", "2": "Februari", "3": "Maart", "4": "April", "5": "Mei", "6": "Juni", "7": "Juli", "8": "Augustus", "9": "September", "10": "Oktober", "11": "November", "12": "December" }, "DELETE": "Verwijderen", "DELETE CONFIRM": "Weet u zeker dat u dit onderdeel wilt verwijderen", "DELETE CONFIRM MULTIPLE": "Weet u zeker dat u deze onderdelen wilt verwijderen", "DETAIL": "Detail", "DETAILS": "Details", "EDIT": "Bewerken", "EMAIL": "E-mail", "EMAIL ADDRESS": "E-mailadres", "EMAIL ERROR": "Er is geen geldige e-mail ingevoerd", "ERROR": "Fout", "FIELD": "Veld", "FIELD REQUIRED": "Dit veld is verplicht", "FORM INVALID": "Het formulier kan niet worden verstuurd. Vul eerst de ontbrekende velden in", "FORM SUCCESS": "De gegevens zijn opgeslagen", "LANGUAGE": "Taal", "LOGIN": "Inloggen", "LOGIN ERROR": "De ingevoerde login combinatie is niet geldig", "LOGIN EXPIRED": "Uw autorisatie is verlopen. Log opnieuw in a.u.b", "LOGOUT": "Uitloggen", "NAME": "Naam", "NETWORK ERROR": "De internetverbinding is verbroken", "PASSWORD": "Wachtwoord", "PASSWORD ERROR": "Er is geen geldig wachtwoord ingevoerd", "PASSWORD MATCH ERROR": "De ingevoerde wachtwoorden komen niet overeen", "REMARKS": "Opmerkingen", "REMEMBER": "Onthouden", "REQUIRED": "Verplicht", "RESET": "Reset", "RESULT": "Resultaat", "RESULTS": "Resultaten", "RESULTS_NTH": { "0": "Geen resultaten", "1": "{n} resultaat", "2": "{n} resultaten", "n": "{n} resultaten", "gt99": "99+ resultaten" }, "SAVE": "Opslaan", "SEARCH": "Zoeken", "SUBMIT": "Indienen", "TITLE": "Titel", "USER": "Gebruiker", "USERS": "Gebruikers", "USERNAME": "Gebruikersnaam", "counter": 'Het aantal is {n}' }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const i18n = { en: en, nl: nl }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class Translate { constructor() { this.i18n = i18n; this.defaultLanguage = 'en-US'; this.supportedLanguages = [ 'en-US', 'nl-NL' ]; this.translations = {}; this.translationsLocation = 'assets/translations'; this.options = { debug: false, //[Boolean]: Logs missing translations to console and adds @@-markers around output. namespaceSplitter: '::' //[String|RegExp]: You can customize the part which splits namespace and translationKeys. }; this.initTranslateJs(); this.libTranslate = Util.getGlobal()['libTranslate']; // fixme: does not work in node.js Object.keys(i18n).forEach((/** * @param {?} k * @return {?} */ (k) => { this.supportedLanguages.push(k); })); this.translations = Util.copy(i18n); this.translations['nl-NL'] = Util.copy(this.translations['nl']); this.translations['en-US'] = Util.copy(this.translations['en']); this.translations['en-BE'] = Util.copy(this.translations['en']); this.use(this.defaultLanguage); } /** * Translates a string to the current language of the TranslateService. * @param {?} translationKey - The string to translate. * @param {...?} params - The parameters to send to the translate function. * @return {?} */ get(translationKey, ...params) { return this.t(translationKey, ...params); } /** * Adds a translated string to the current language object. * @param {?} translationKey - The identifier of the translation. * @param {?} value - The value of the translation in the current selected language. * @return {?} */ set(translationKey, value) { this.translations[this.language][translationKey] = value; } /** * @param {?} translationsObject * @return {?} */ add(translationsObject) { Object.keys(translationsObject).forEach((/** * @param {?} k * @return {?} */ (k) => { this.set(k, translationsObject[k]); })); } /** * Switch the current language of the translateService. * If the supplied language parameter is not yet present in the translations object, * the service will try to load a json file in the location specified in translationsLocation property. * example: use('fr'), will load 'assets/translations/fr.json' by default * @param {?} language - The language identifier. * @param {?=} reloadRemote - Set this to true to reload the json translation file. * @return {?} */ use(language, reloadRemote = false) { return __awaiter(this, void 0, void 0, function* () { this.language = language; if (!this.translations[language] || reloadRemote) { yield this.loadTranslation(language); } this.t = this.libTranslate.getTranslationFunction(this.translations[language], [this.options]); return; }); } /** * @param {?} language * @return {?} */ loadTranslation(language) { return __awaiter(this, void 0, void 0, function* () { if (!this.translations[language]) this.translations[language] = {}; /** @type {?} */ let loadedTranslation = yield Util.fetchJson(this.translationsLocation + '/' + language + '.json'); Object.keys(loadedTranslation).forEach((/** * @param {?} k * @return {?} */ (k) => { this.translations[language][k] = loadedTranslation[k]; })); return; }); } /** * @return {?} */ updateTranslateComponents() { /** @type {?} */ let components = Array.from(document.getElementsByTagName('ema-translate')); components.forEach((/** * @param {?} el * @return {?} */ (el) => { el['update'](); })); } /** * @return {?} */ initTranslateJs() { /*! translate.js - v1.1.0 - 2015-06-16 * https://github.com/musterknabe/translate.js * Copyright (c) 2015 Jonas Girnatis * Licensed under MIT license */ // @ts-ignore !(/** * @return {?} */ function () { /** @type {?} */ var a = (/** * @param {?} a * @return {?} */ function (a) { return !isNaN(parseFloat(a)) && isFinite(a); }); /** @type {?} */ var b = (/** * @param {?} a * @return {?} */ function (a) { return "object" == typeof a && null !== a; }); /** @type {?} */ var c = (/** * @param {?} a * @return {?} */ function (a) { return "[object String]" === Object.prototype.toString.call(a); }); Util.getGlobal()['libTranslate'] = { getTranslationFunction: (/** * @param {?} d * @param {?} e * @return {?} */ function (d, e) { /** * @param {?} a * @return {?} */ function f(a) { if (d[a]) return d[a]; /** @type {?} */ var b = a.split(j); /** @type {?} */ var c = b[0]; /** @type {?} */ var e = b[1]; return d[c] && d[c][e] ? d[c][e] : null; } /** * @param {?} a * @param {?} c * @return {?} */ function g(a, c) { if (b(a)) { /** @type {?} */ var d; /** @type {?} */ var e = Object.keys(a); if (0 === e.length) return i && console.log("[Translation] No plural forms found."), null; for (var f = 0; f < e.length; f++) 0 === e[f].indexOf("gt") && (d = parseInt(e[f].replace("gt", ""), 10)); a[c] ? a = a[c] : c > d ? a = a["gt" + d] : a.n ? a = a.n : (i && console.log('[Translation] No plural forms found for count:"' + c + '" in', a), a = a[Object.keys(a).reverse()[0]]); } return a; } /** * @param {?} a * @param {?} b * @return {?} */ function h(a, b) { return c(a) ? a.replace(/\{(\w*)\}/g, (/** * @param {?} a * @param {?} c * @return {?} */ function (a, c) { return b.hasOwnProperty(c) ? b.hasOwnProperty(c) ? b[c] : c : (i && console.log('Could not find replacement "' + c + '" in provided replacements object:', b), "{" + c + "}"); })) : a; } e = b(e) ? e : {}; /** @type {?} */ var i = e.debug; /** @type {?} */ var j = e.namespaceSplitter || "::"; return (/** * @param {?} c * @return {?} */ function (c) { /** @type {?} */ var d = b(arguments[1]) ? arguments[1] : b(arguments[2]) ? arguments[2] : {}; /** @type {?} */ var e = a(arguments[1]) ? arguments[1] : a(arguments[2]) ? arguments[2] : null; /** @type {?} */ var j = f(c); return null !== e && (d.n = d.n ? d.n : e, j = g(j, e)), j = h(j, d), null === j && (j = i ? "@@" + c + "@@" : c, i && console.log('Translation for "' + c + '" not found.')), j; }); }) }; })(); } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const singleton$1 = Symbol(); /** @type {?} */ const singletonEnforcer$1 = Symbol(); class TranslateService extends Translate { /** * @param {?} enforcer */ constructor(enforcer) { super(); if (enforcer !== singletonEnforcer$1) { throw new Error('Cannot construct singleton'); } this._type = '