UNPKG

@singleton-i18n/angular-client

Version:

Singleton client code for Angular 10.

1,181 lines (1,168 loc) 357 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('rxjs/operators'), require('@angular/core'), require('@angular/common/http'), require('rxjs'), require('decimal.js-light')) : typeof define === 'function' && define.amd ? define('@singleton-i18n/angular-client', ['exports', 'rxjs/operators', '@angular/core', '@angular/common/http', 'rxjs', 'decimal.js-light'], factory) : (global = global || self, factory((global['singleton-i18n'] = global['singleton-i18n'] || {}, global['singleton-i18n']['angular-client'] = {}), global.rxjs.operators, global.ng.core, global.ng.common.http, global.rxjs, global.decimal)); }(this, (function (exports, operators, i0, http, rxjs, decimal_jsLight) { 'use strict'; /*! ***************************************************************************** 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. ***************************************************************************** */ /* 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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); 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 __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } 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 __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } 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; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from) { for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i]; return to; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } var VIPTimeOutError = /** @class */ (function (_super) { __extends(VIPTimeOutError, _super); function VIPTimeOutError(m) { var _this = _super.call(this, m) || this; _this.message = _this.message + '; Please check the network connection with VIP server and timeout settings.'; // Set the prototype explicitly. Object.setPrototypeOf(_this, VIPTimeOutError.prototype); return _this; } return VIPTimeOutError; }(Error)); function invalidPipeArgumentError(type, value) { return Error("InvalidPipeArgument: '" + value + "' for pipe '" + i0.ɵstringify(type) + "'"); } function invalidParamater(message) { return Error("InvalidParamater: '" + message + "'"); } var VIPServiceConstants = /** @class */ (function () { function VIPServiceConstants() { } return VIPServiceConstants; }()); VIPServiceConstants.L10N_COMPONENT_API_ENDPOINT = 'i18n/api/v2/translation'; VIPServiceConstants.L10N_STRING_API_ENDPOINT = 'i18n/api/v2/translation'; VIPServiceConstants.I18N_API_ENDPOINT = 'i18n/api/v2/formatting/patterns'; VIPServiceConstants.L10N_LOCAL_API_ENDPOINT = 'i18n/api/v2/locale'; VIPServiceConstants.TRANSLATION_PATTERN = 'i18n/api/v2/combination/translationsAndPattern'; VIPServiceConstants.PseudoTag = '#@'; VIPServiceConstants.ASSETS_SUFFIX = '.json'; VIPServiceConstants.I18N_ASSETS_PREFIX = 'locale_'; VIPServiceConstants.L10N_ASSETS_PREFIX = 'translation_'; VIPServiceConstants.NAME_SPACE_SEPARATOR = ':'; VIPServiceConstants.ENGLISH = { languageCode: 'en', languageName: 'English', regionCode: 'US', regionName: 'United States' }; /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ /** * verify value if undefined or null */ function isDefined(value) { return value !== undefined && value !== null && value !== ''; } /** * Format translation string, e.g. 'No custom buckets specified for {0}' */ function format(message, args) { var templateMatcher = /{\s?([\d]*)\s?}/g; var _loop_1 = function (i) { message = message.replace(templateMatcher, function (substring, b) { return (b.trim() === i.toString() && isDefined(args[i])) ? args[i] : substring; }); }; for (var i = 0; i < args.length; i += 1) { _loop_1(i); } return message; } function mergeObject(a, b) { a = a instanceof Object ? a : {}; b = b instanceof Object ? b : {}; // Merge the sub objects with the same key. Object.keys(a).forEach(function (key) { if (b[key]) { if ((b[key] instanceof Object) && (a[key] instanceof Object)) { Object.assign(b[key], a[key]); } } }); return Object.assign(a, b); } function equals(o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2; var length, key, keySet; if (t1 === t2 && t1 === 'object') { if (Array.isArray(o1)) { if (!Array.isArray(o2)) { return false; } if ((length = o1.length) === o2.length) { for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else { if (Array.isArray(o2)) { return false; } // Dealing with the Date object without any key, but the actual value is different. if (o1 instanceof Date && o2 instanceof Date) { return o1.getTime() === o2.getTime(); } keySet = Object.create(null); for (key in o1) { if (!equals(o1[key], o2[key])) { return false; } else { keySet[key] = true; } } for (key in o2) { if (!(key in keySet) && typeof o2[key] !== 'undefined') { return false; } } return true; } } return false; } /* * Mixin class decorator * * Based on * https://medium.com/@dmyl/mixins-as-class-decorators-in-typescript-angular2-8e09f1bc1f02 * * with minor modifications to support an opaque data object * stored in the object prototype as `mixinData` */ function Mixin(baseCtors, data) { return function (derivedCtor) { derivedCtor.prototype.mixinData = data; baseCtors.forEach(function (baseCtor) { Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) { var descriptor = Object.getOwnPropertyDescriptor(baseCtor.prototype, name); if (name === 'constructor') { return; } if (descriptor && (!descriptor.writable || !descriptor.configurable || !descriptor.enumerable || descriptor.get || descriptor.set)) { Object.defineProperty(derivedCtor.prototype, name, descriptor); } else { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }); }); }; } /** * Returns the culture language code name from the browser, e.g. "de-DE" * @returns string */ function getBrowserCultureLang() { if (window === undefined || window.navigator === undefined) { return undefined; } var browserCultureLang = window.navigator.languages ? window.navigator.languages[0] : null; browserCultureLang = browserCultureLang || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage; return browserCultureLang; } function deprecatedWarn(name, version, substitute) { console.warn(name + " is deprecated, will be removed in " + version + ", Please use " + substitute + " instead."); } /** * Merge the key-value pair which defined in each object and * check whether the key is globally unique * TODO: Support object directly * @param target Target object contains all strings * @param source A set of source objects */ function assign(target, source) { var s; var i; var props; var isObject = function (obj) { return obj && typeof obj === 'object'; }; if (!isObject(target)) { throw new TypeError('Target must be an object'); } for (s = 0; s < source.length; ++s) { var sub = void 0; sub = source[s]; if (!isObject(sub)) { throw new TypeError('Source must be an object'); } props = Object.keys(Object(sub)); for (i = 0; i < props.length; ++i) { if (target.hasOwnProperty(props[i])) { console.warn('Duplicate message key:', props[i]); } target[props[i]] = sub[props[i]]; } } return target; } function isEmptyObject(obj) { if (!isDefined(obj)) { return true; } return Object.keys(obj).length === 0; } function parseOption(name, range, a) { var res = parseInt(a); if (isNaN(res)) { throw Error(name + " is not a number"); } if (res < range[0] || res > range[1]) { throw Error(name + " value is out of range."); } return res; } /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ var VIP_CONFIG = new i0.InjectionToken('VIP_CONFIG'); (function (PatternCategories) { PatternCategories["DATE"] = "dates"; PatternCategories["NUMBER"] = "numbers"; PatternCategories["PLURAL"] = "plurals"; PatternCategories["CURRENCIES"] = "currencies"; PatternCategories["DATEFIELDS"] = "dateFields"; })(exports.PatternCategories || (exports.PatternCategories = {})); function getNameSpace(config) { if (!config) { return undefined; } return [config.productID, config.component, config.version] .join('-').toString().toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, ''); } /** * Check and set default value. i18n context will override some environmental parameters. * @param vipConfig */ function VIPConfigFactory(vipConfig, i18nContext) { // The isPseudo default value is false, // isPseudo config in i18nContext has the highest priority, // and will override other configurations. var isPseudo = isDefined(i18nContext.pseudoEnabled) ? i18nContext.pseudoEnabled : vipConfig.isPseudo || false; return { productID: vipConfig.productID || undefined, component: vipConfig.component || undefined, version: vipConfig.version || undefined, host: vipConfig.host || undefined, isPseudo: isPseudo, locale: vipConfig.locale || undefined, region: vipConfig.region || undefined, language: vipConfig.language || 'en', i18nScope: vipConfig.i18nScope || [], sourceBundle: vipConfig.sourceBundle || undefined, sourceBundles: vipConfig.sourceBundles || undefined, translationBundles: vipConfig.translationBundles || undefined, i18nAssets: vipConfig.i18nAssets || undefined, collectSource: vipConfig.collectSource || false, timeout: vipConfig.timeout || 3000 }; } /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ var ResponseParser = /** @class */ (function () { function ResponseParser() { } return ResponseParser; }()); var VIPResponseParser = /** @class */ (function () { function VIPResponseParser() { } VIPResponseParser.prototype.validateResponse = function (res) { if (!res || !res.response) { return null; } var response = res.response; // response code is bussiness code from VIP backend. if (response.code && response.code !== 200) { throw Error(response.message); } if (res.data && res.data.pattern && !res.data.pattern.isExistPattern) { res.data.pattern = null; } return res.data; }; VIPResponseParser.prototype.ParseLocaleData = function (res, config) { var translations = {}; var data = this.validateResponse(res); var nameSpace = getNameSpace(config); var pattern = this.ParsePatternsData(data); translations[nameSpace] = this.ParseTranslationsData(data); return { categories: pattern, messages: translations }; }; VIPResponseParser.prototype.ParsePatternsData = function (data) { var pattern = data && data.pattern && data.pattern.categories ? data.pattern.categories : undefined; return pattern; }; VIPResponseParser.prototype.ParseTranslationsData = function (data) { if (data.messages) { return data.messages; } var translations = data && data.components && data.components[0].messages ? data.components[0].messages : undefined; return translations; }; VIPResponseParser.prototype.ParseSupportedLanguagesData = function (res) { var data = this.validateResponse(res); var languages = data && data.languages ? data.languages : null; return languages; }; VIPResponseParser.prototype.ParseSupportedRegionsData = function (res) { var data = this.validateResponse(res); var regions = data && data[0] ? data[0] : null; return regions; }; return VIPResponseParser; }()); VIPResponseParser.decorators = [ { type: i0.Injectable } ]; VIPResponseParser.ctorParameters = function () { return []; }; /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ var I18nLoader = /** @class */ (function () { function I18nLoader() { } return I18nLoader; }()); var VIPLoader = /** @class */ (function () { function VIPLoader(responseParser, http) { this.responseParser = responseParser; this.http = http; } /** * Get the i18n resource through VIP service. * i18nAssets will be removed in future release. * And for i18nAsset only support loading translation * from web server, can't support loading patterns. * @param url * @returns Promise<any> * @memberof VIPRestLoader */ VIPLoader.prototype.getLocaleData = function (config, language, region) { this.validateConfig(config); var scope = config.i18nScope ? config.i18nScope.join(',') : ''; // For now, just only support downloading translation to local assets folder // but it is also supposed to support formatting pattern data. // Firstly, identify which mode is using. if (isDefined(config.i18nAssets)) { return scope === '' ? this.getTranslationByComponent(language, config) : this.getCombineDataFromAssets(language, config); } // Secondly, which API should be used to communicate with VIP service. return scope === '' ? this.getTranslationByComponent(language, config) : this.getCombineLocaleData(config, language, region); }; /** * Get the combine locale data(translations and pattern) through assets folder. * @param language language code in use * @param config */ VIPLoader.prototype.getCombineDataFromAssets = function (language, config) { var _this = this; var url = this.getI18nResourceUrl(config, language); return this.getRequest(url, config.timeout, function (res) { return _this.responseParser.ParseLocaleData(res, config); }); }; /** * Only get translations through VIP service. * @param language language tag for translation. * @param config without i18nScope */ VIPLoader.prototype.getTranslationByComponent = function (language, config) { var _this = this; var url = this.getComponentTranslationUrl(language, config); return this.getRequest(url, config.timeout, function (res) { return _this.responseParser.ParseLocaleData(res, config); }); }; /** * Get combine locale data(translations and pattern) through VIP service. * @param conf with i18nScope * @param language language tag for translation. * @param region region code for formatting pattern. */ VIPLoader.prototype.getCombineLocaleData = function (conf, language, region) { var _this = this; var scope = conf.i18nScope.join(','); var url = this.getI18nResourceUrl(conf); var combine = region ? 1 : 2; return this.postRequest(url, { language: language, region: region, productName: conf.productID, version: conf.version, components: [conf.component], scope: scope, pseudo: conf.isPseudo, combine: combine, machineTranslation: false }, conf.timeout, function (res) { return _this.responseParser.ParseLocaleData(res, conf); }); }; VIPLoader.prototype.getSupportedLanguages = function (conf) { var _this = this; var url = this.getSupportedLanguagesUrl(conf); return this.getRequest(url, conf.timeout, function (res) { return _this.responseParser.ParseSupportedLanguagesData(res); }); }; VIPLoader.prototype.getSupportedRegions = function (language, conf) { var _this = this; var url = this.getSupportedRegionsUrl(language, conf.host); return this.getRequest(url, conf.timeout, function (res) { return _this.responseParser.ParseSupportedRegionsData(res); }); }; VIPLoader.prototype.getLocalizedCities = function (language, region, conf) { var _this = this; var url = this.getLocalizedCitiesUrl(language, region, conf.host); return this.getRequest(url, conf.timeout, function (res) { return _this.responseParser.ParseSupportedRegionsData(res); }); }; /** * Fetch I18N resource from backend service through get request. * @param url request url. * @param timeout default value is 3000ms, timeoutWith default value is 0ms. * @param fn a callback function that is executed after the request is completed. */ VIPLoader.prototype.getRequest = function (url, timeout, fn) { return this.http.get(url) .pipe(operators.timeoutWith(timeout, rxjs.defer(function () { return rxjs.throwError(new VIPTimeOutError('Timeout error')); })), operators.map(function (res) { return fn && typeof fn === 'function' ? fn(res) : res; }), operators.catchError(function (err) { return rxjs.throwError(err); })); }; /** * Fetch I18N resource from backend service through post request. * @param url request url. * @param vipRequestBody parameters * @param timeout default value is 3000ms, timeoutWith default value is 0ms. * @param fn a callback function that is executed after the request is completed. */ VIPLoader.prototype.postRequest = function (url, vipRequestBody, timeout, fn) { return this.http.post(url, vipRequestBody) .pipe(operators.timeoutWith(timeout, rxjs.defer(function () { return rxjs.throwError(new VIPTimeOutError('Timeout error')); })), operators.map(function (res) { return fn && typeof fn === 'function' ? fn(res) : res; }), operators.catchError(function (err) { return rxjs.throwError(err); })); }; VIPLoader.prototype.getI18nResourceUrl = function (conf, language) { if (conf.i18nAssets) { var path = "" + conf.i18nAssets + language + VIPServiceConstants.ASSETS_SUFFIX; return path; } return conf.host .concat(VIPServiceConstants.TRANSLATION_PATTERN); }; VIPLoader.prototype.getComponentTranslationUrl = function (language, config) { if (isDefined(config.i18nAssets)) { var path = "" + config.i18nAssets + VIPServiceConstants.L10N_ASSETS_PREFIX + language + VIPServiceConstants.ASSETS_SUFFIX; return path; } return config.host .concat(VIPServiceConstants.L10N_COMPONENT_API_ENDPOINT) .concat('/products/' + config.productID) .concat('/versions/' + config.version) .concat('/locales/' + language) .concat('/components/' + config.component) .concat('?pseudo=' + config.isPseudo); }; VIPLoader.prototype.getSupportedLanguagesUrl = function (config) { return config.host .concat(VIPServiceConstants.L10N_LOCAL_API_ENDPOINT) .concat('/supportedLanguageList?') .concat('productName=' + config.productID) .concat('&version=' + config.version); }; VIPLoader.prototype.getSupportedRegionsUrl = function (language, host) { return host .concat(VIPServiceConstants.L10N_LOCAL_API_ENDPOINT) .concat('/regionList?') .concat('supportedLanguageList=' + language); }; VIPLoader.prototype.getLocalizedCitiesUrl = function (language, region, host) { return host .concat(VIPServiceConstants.L10N_LOCAL_API_ENDPOINT) .concat('/regionList?') .concat('supportedLanguageList=' + language) .concat('&displayCity=true&regions=' + region); }; VIPLoader.prototype.validateConfig = function (initConfig) { var message = ' in VIPLoader'; if (!isDefined(initConfig.productID) || !initConfig.productID.length) { throw invalidParamater('productID' + message); } if (!isDefined(initConfig.version) || !initConfig.version.length) { throw invalidParamater('version' + message); } // in i18nAssets mode, the host is not required if (!isDefined(initConfig.host) && !isDefined(initConfig.i18nAssets)) { throw invalidParamater('host' + message); } if (!isDefined(initConfig.language)) { throw invalidParamater('language' + message); } return true; }; return VIPLoader; }()); VIPLoader.decorators = [ { type: i0.Injectable } ]; VIPLoader.ctorParameters = function () { return [ { type: ResponseParser }, { type: http.HttpClient } ]; }; /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ var LanguageMap = { 'en': ['en'], 'en-gb': ['en-GB'], 'en-us': ['en'], 'fr': ['fr'], 'fr-fr': ['fr'], 'de': ['de'], 'de-de': ['de'], 'es': ['es'], 'es-es': ['es'], 'ja': ['ja'], 'ja-jp': ['ja'], 'ko': ['ko'], 'ko-kr': ['ko'], 'pt-br': ['pt'], 'pt-pt': ['pt-PT'], 'zh-hans': ['zh-Hans'], 'zh-hant': ['zh-Hant'], 'zh-cn': ['zh-Hans'], 'zh-hk': ['zh-Hant-HK'], 'zh-tw': ['zh-Hant'] }; var I18N_ENABLED = 'vip.i18nEnabled'; var PSEUDO_ENABLED = 'vip.pseudoEnabled'; var PREFERRED_LANGUAGE = 'vip.preferredLanguage'; var PREFERRED_REGION = 'vip.preferredRegion'; var I18nContext = /** @class */ (function () { function I18nContext() { } return I18nContext; }()); function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } var DefaultI18nContext = /** @class */ (function (_super) { __extends(DefaultI18nContext, _super); function DefaultI18nContext() { var _this = _super.call(this) || this; _this.localstore = {}; if (supports_html5_storage) { _this.store = window.localStorage; } return _this; } DefaultI18nContext.prototype.toBoolean = function (value) { if (value === undefined || value === 'undefined') { return undefined; } return value === 'true' ? true : false; }; DefaultI18nContext.prototype.setItem = function (item, value) { this.localstore[item] = value; if (this.store) { this.store.setItem(item, value); } }; DefaultI18nContext.prototype.getItem = function (name) { if (this.store && isDefined(this.store.getItem(name))) { return this.store.getItem(name); } if (isDefined(this.localstore[name])) { return this.localstore[name]; } }; Object.defineProperty(DefaultI18nContext.prototype, "pseudoEnabled", { get: function () { return this.toBoolean(this.getItem(PSEUDO_ENABLED)); }, enumerable: false, configurable: true }); Object.defineProperty(DefaultI18nContext.prototype, "i18nEnabled", { get: function () { return this.toBoolean(this.getItem(I18N_ENABLED)); }, set: function (i18nEnabled) { this.setItem(I18N_ENABLED, String(i18nEnabled)); }, enumerable: false, configurable: true }); Object.defineProperty(DefaultI18nContext.prototype, "preferredLanguage", { get: function () { return this.getItem(PREFERRED_LANGUAGE); }, set: function (languageCode) { this.setItem(PREFERRED_LANGUAGE, languageCode); }, enumerable: false, configurable: true }); Object.defineProperty(DefaultI18nContext.prototype, "preferredRegion", { get: function () { return this.getItem(PREFERRED_REGION); }, set: function (regionCode) { this.setItem(PREFERRED_REGION, regionCode); }, enumerable: false, configurable: true }); return DefaultI18nContext; }(I18nContext)); DefaultI18nContext.decorators = [ { type: i0.Injectable } ]; DefaultI18nContext.ctorParameters = function () { return []; }; /* * Copyright 2019-2021 VMware, Inc. * SPDX-License-Identifier: EPL-2.0 */ var LocaleService = /** @class */ (function () { /** * by default, the initial locale is en-US. */ function LocaleService(i18nContext) { this.i18nContext = i18nContext; /** * Fired when user changed current locale. * Return the combination of language and region. */ this.userLocaleChanged = new rxjs.Subject(); this.defaultLocale = VIPServiceConstants.ENGLISH; this.setLocale(this.defaultLocale.languageCode, this.defaultLocale.regionCode); } /** * initialize language and region combination at app bootstrap. * @param language language code for translation and plural rule. * @param region region code for the l2 formatting patterns. */ LocaleService.prototype.init = function (language, region) { if (isDefined(language)) { this.setLocale(language, region); this.i18nContext.preferredLanguage = language; } if (isDefined(region)) { this.i18nContext.preferredRegion = region; } }; /** * set default locale and initialize current language and current region. * this should be executed when the application start. * @param defaultLocale will be used as fallback locale. */ LocaleService.prototype.setDefaultLocale = function (defaultLocale) { this.defaultLocale = defaultLocale || this.defaultLocale; this.setLocale(this.defaultLocale.languageCode, this.defaultLocale.regionCode); }; LocaleService.prototype.setLocale = function (language, region) { if (language !== this.currentLanguage || region !== this.currentRegion) { this.currentLanguage = language; this.currentRegion = region; } }; LocaleService.prototype.getCurrentLanguage = function () { return this.currentLanguage; }; LocaleService.prototype.setCurrentLanguage = function (currentLang) { if (currentLang !== this.currentLanguage) { this.currentLanguage = currentLang; this.sendUserLocaleEvent(); } }; LocaleService.prototype.getCurrentRegion = function () { return this.currentRegion; }; LocaleService.prototype.setCurrentRegion = function (currentRegion) { if (currentRegion !== this.currentRegion) { this.currentRegion = currentRegion; this.sendUserLocaleEvent(); } }; LocaleService.prototype.getCurrentLocale = function () { return this.composeLocale(this.currentLanguage, this.currentRegion); }; /** * set current language and region combination at runtime. * and notify VIP service to load corresponding i18n resource. * @param language language code for translation and plural rule. * @param region region code for the l2 formatting patterns. */ LocaleService.prototype.setCurrentLocale = function (language, region) { this.setLocale(language, region); this.sendUserLocaleEvent(); }; /** * compose the sample locale structure based on the current usage scenarios. * @param language language code for translation and plural rule. * @param region region code for the l2 formatting patterns. */ LocaleService.prototype.composeLocale = function (language, region) { return language && region ? language + "-" + region : language; }; LocaleService.prototype.sendUserLocaleEvent = function () { this.userLocaleChanged.next(this.getCurrentLocale()); }; Object.defineProperty(LocaleService.prototype, "isSourceLocale", { get: function () { return this.shouldSourceLocale(this.currentLanguage, this.currentRegion); }, enumerable: false, configurable: true }); LocaleService.prototype.shouldSourceLocale = function (language, region) { return this.shouldSourceLanguage(language) && isDefined(region) && region.toUpperCase() === this.defaultLocale.regionCode ? true : this.shouldSourceLanguage(language) && !isDefined(region) ? true : false; }; LocaleService.prototype.resolveLanguageTag = function (language) { if (!isDefined(language)) { return language; } return language.split('_').join('-').toLocaleLowerCase(); }; Object.defineProperty(LocaleService.prototype, "isSourceLanguage", { get: function () { return this.shouldSourceLanguage(this.currentLanguage); }, enumerable: false, configurable: true }); LocaleService.prototype.shouldSourceLanguage = function (language) { return language.toLowerCase() === this.defaultLocale.languageName ? true : this.defaultLocale.languageCode.toLowerCase() === this.resolveLanguageTag(language) ? true : (this.defaultLocale.languageCode + "-" + this.defaultLocale.regionCode).toLowerCase() === this.resolveLanguageTag(language) ? true : false; }; /** * Reserve interface for language tag normalization in bundle mode. * @param language language code for translation and plural rule. */ LocaleService.prototype.normalizeLanguageCode = function (language) { var lang = language.replace('_', '-').toLowerCase(); if (LanguageMap[lang]) { return LanguageMap[lang][0]; } return language; }; return LocaleService; }()); LocaleService.ɵprov = i0.ɵɵdefineInjectable({ factory: function LocaleService_Factory() { return new LocaleService(i0.ɵɵinject(I18nContext)); }, token: LocaleService, providedIn: "root" }); LocaleService.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'root', },] } ]; LocaleService.ctorParameters = function () { return [ { type: I18nContext } ]; }; var VIPService = /** @class */ (function () { function VIPService(localeService, i18nContext, currentLoader) { this.localeService = localeService; this.i18nContext = i18nContext; this.currentLoader = currentLoader; this.pending = false; this.configs = []; this.availableLocales = []; this._onLocaleChange = new i0.EventEmitter(); this._i18nScope = []; this._localeData = {}; } Object.defineProperty(VIPService.prototype, "onLocaleChange", { get: function () { return this._onLocaleChange; }, enumerable: false, configurable: true }); Object.defineProperty(VIPService.prototype, "localeData", { get: function () { return this._localeData; }, enumerable: false, configurable: true }); Object.defineProperty(VIPService.prototype, "i18nScope", { get: function () { return this._i18nScope; }, enumerable: false, configurable: true }); /** * Loading the i18n data at app module or root of lazy module. * @param config For root module or lazy load mdule. */ VIPService.prototype.initData = function (config) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.subscribeLocaleSubject(); this.registerComponent(config, true); this.initLocale(config); return [4 /*yield