UNPKG

@petkoneo/phaser3-rex-plugins

Version:
1,134 lines (1,080 loc) 178 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.rextexttranslationplugin = factory()); })(this, (function () { 'use strict'; function _mergeNamespaces(n, m) { m.forEach(function (e) { e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); }); return Object.freeze(n); } var EventEmitterMethods = { setEventEmitter(eventEmitter, EventEmitterClass) { if (EventEmitterClass === undefined) { EventEmitterClass = Phaser.Events.EventEmitter; // Use built-in EventEmitter class by default } this._privateEE = (eventEmitter === true) || (eventEmitter === undefined); this._eventEmitter = (this._privateEE) ? (new EventEmitterClass()) : eventEmitter; return this; }, destroyEventEmitter() { if (this._eventEmitter && this._privateEE) { this._eventEmitter.shutdown(); } return this; }, getEventEmitter() { return this._eventEmitter; }, on() { if (this._eventEmitter) { this._eventEmitter.on.apply(this._eventEmitter, arguments); } return this; }, once() { if (this._eventEmitter) { this._eventEmitter.once.apply(this._eventEmitter, arguments); } return this; }, off() { if (this._eventEmitter) { this._eventEmitter.off.apply(this._eventEmitter, arguments); } return this; }, emit(event) { if (this._eventEmitter && event) { this._eventEmitter.emit.apply(this._eventEmitter, arguments); } return this; }, addListener() { if (this._eventEmitter) { this._eventEmitter.addListener.apply(this._eventEmitter, arguments); } return this; }, removeListener() { if (this._eventEmitter) { this._eventEmitter.removeListener.apply(this._eventEmitter, arguments); } return this; }, removeAllListeners() { if (this._eventEmitter) { this._eventEmitter.removeAllListeners.apply(this._eventEmitter, arguments); } return this; }, listenerCount() { if (this._eventEmitter) { return this._eventEmitter.listenerCount.apply(this._eventEmitter, arguments); } return 0; }, listeners() { if (this._eventEmitter) { return this._eventEmitter.listeners.apply(this._eventEmitter, arguments); } return []; }, eventNames() { if (this._eventEmitter) { return this._eventEmitter.eventNames.apply(this._eventEmitter, arguments); } return []; }, }; const FILE_POPULATED = Phaser.Loader.FILE_POPULATED; const UUID = Phaser.Utils.String.UUID; class AwaitFile extends Phaser.Loader.File { constructor(loader, fileConfig) { if (!fileConfig.hasOwnProperty('type')) { fileConfig.type = 'await'; } if (!fileConfig.hasOwnProperty('url')) { fileConfig.url = ''; } if (!fileConfig.hasOwnProperty('key')) { fileConfig.key = UUID(); } super(loader, fileConfig); } load() { if (this.state === FILE_POPULATED) { // Can happen for example in a JSONFile if they've provided a JSON object instead of a URL this.loader.nextFile(this, true); } else { // start loading task var config = this.config; var callback = config.callback; var scope = config.scope; if (callback) { var self = this; var runOnce = false; var successCallback = function () { if (runOnce) { return; } // Invoke onLoad next tick setTimeout(function () { self.onLoad(); }, 0); runOnce = true; }; var failureCallback = function () { if (runOnce) { return; } // Invoke onError next tick setTimeout(function () { self.onError(); }, 0); runOnce = true; }; if (scope) { callback.call(scope, successCallback, failureCallback); } else { callback(successCallback, failureCallback); } } else { this.onLoad(); } } } onLoad() { this.loader.nextFile(this, true); } onError() { this.loader.nextFile(this, false); } } var IsFunction = function (obj) { return obj && (typeof(obj) === 'function'); }; const IsPlainObject = Phaser.Utils.Objects.IsPlainObject; const loaderCallback = function (key, config) { if (IsFunction(key)) { var callback = key; var scope = config; config = { config: { callback: callback, scope: scope, } }; } else if (IsPlainObject(key)) { config = key; if (!config.hasOwnProperty('config')) { config = { config: config }; } } else { config = { key: key, config: config }; } this.addFile(new AwaitFile(this, config)); return this; }; Phaser.Loader.FileTypesManager.register('rexAwait', loaderCallback); function _typeof$3(o) { "@babel/helpers - typeof"; return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof$3(o); } function _classCallCheck$1(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function toPrimitive(t, r) { if ("object" != _typeof$3(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof$3(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function toPropertyKey(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof$3(i) ? i : i + ""; } function _defineProperties$1(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o); } } function _createClass$1(e, r, t) { return r && _defineProperties$1(e.prototype, r), t && _defineProperties$1(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof$3(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _defineProperty$2(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6(Object(source), !0).forEach(function (key) { _defineProperty$2(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var consoleLogger = { type: 'logger', log: function log(args) { this.output('log', args); }, warn: function warn(args) { this.output('warn', args); }, error: function error(args) { this.output('error', args); }, output: function output(type, args) { if (console && console[type]) console[type].apply(console, args); } }; var Logger = function () { function Logger(concreteLogger) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck$1(this, Logger); this.init(concreteLogger, options); } _createClass$1(Logger, [{ key: "init", value: function init(concreteLogger) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.prefix = options.prefix || 'i18next:'; this.logger = concreteLogger || consoleLogger; this.options = options; this.debug = options.debug; } }, { key: "setDebug", value: function setDebug(bool) { this.debug = bool; } }, { key: "log", value: function log() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return this.forward(args, 'log', '', true); } }, { key: "warn", value: function warn() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return this.forward(args, 'warn', '', true); } }, { key: "error", value: function error() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return this.forward(args, 'error', ''); } }, { key: "deprecate", value: function deprecate() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true); } }, { key: "forward", value: function forward(args, lvl, prefix, debugOnly) { if (debugOnly && !this.debug) return null; if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]); return this.logger[lvl](args); } }, { key: "create", value: function create(moduleName) { return new Logger(this.logger, _objectSpread$6(_objectSpread$6({}, { prefix: "".concat(this.prefix, ":").concat(moduleName, ":") }), this.options)); } }, { key: "clone", value: function clone(options) { options = options || this.options; options.prefix = options.prefix || this.prefix; return new Logger(this.logger, options); } }]); return Logger; }(); var baseLogger = new Logger(); var EventEmitter = function () { function EventEmitter() { _classCallCheck$1(this, EventEmitter); this.observers = {}; } _createClass$1(EventEmitter, [{ key: "on", value: function on(events, listener) { var _this = this; events.split(' ').forEach(function (event) { _this.observers[event] = _this.observers[event] || []; _this.observers[event].push(listener); }); return this; } }, { key: "off", value: function off(event, listener) { if (!this.observers[event]) return; if (!listener) { delete this.observers[event]; return; } this.observers[event] = this.observers[event].filter(function (l) { return l !== listener; }); } }, { key: "emit", value: function emit(event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (this.observers[event]) { var cloned = [].concat(this.observers[event]); cloned.forEach(function (observer) { observer.apply(void 0, args); }); } if (this.observers['*']) { var _cloned = [].concat(this.observers['*']); _cloned.forEach(function (observer) { observer.apply(observer, [event].concat(args)); }); } } }]); return EventEmitter; }(); function defer() { var res; var rej; var promise = new Promise(function (resolve, reject) { res = resolve; rej = reject; }); promise.resolve = res; promise.reject = rej; return promise; } function makeString(object) { if (object == null) return ''; return '' + object; } function copy(a, s, t) { a.forEach(function (m) { if (s[m]) t[m] = s[m]; }); } function getLastOfPath(object, path, Empty) { function cleanKey(key) { return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key; } function canNotTraverseDeeper() { return !object || typeof object === 'string'; } var stack = typeof path !== 'string' ? [].concat(path) : path.split('.'); while (stack.length > 1) { if (canNotTraverseDeeper()) return {}; var key = cleanKey(stack.shift()); if (!object[key] && Empty) object[key] = new Empty(); if (Object.prototype.hasOwnProperty.call(object, key)) { object = object[key]; } else { object = {}; } } if (canNotTraverseDeeper()) return {}; return { obj: object, k: cleanKey(stack.shift()) }; } function setPath(object, path, newValue) { var _getLastOfPath = getLastOfPath(object, path, Object), obj = _getLastOfPath.obj, k = _getLastOfPath.k; obj[k] = newValue; } function pushPath(object, path, newValue, concat) { var _getLastOfPath2 = getLastOfPath(object, path, Object), obj = _getLastOfPath2.obj, k = _getLastOfPath2.k; obj[k] = obj[k] || []; if (concat) obj[k] = obj[k].concat(newValue); if (!concat) obj[k].push(newValue); } function getPath(object, path) { var _getLastOfPath3 = getLastOfPath(object, path), obj = _getLastOfPath3.obj, k = _getLastOfPath3.k; if (!obj) return undefined; return obj[k]; } function getPathWithDefaults(data, defaultData, key) { var value = getPath(data, key); if (value !== undefined) { return value; } return getPath(defaultData, key); } function deepExtend(target, source, overwrite) { for (var prop in source) { if (prop !== '__proto__' && prop !== 'constructor') { if (prop in target) { if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) { if (overwrite) target[prop] = source[prop]; } else { deepExtend(target[prop], source[prop], overwrite); } } else { target[prop] = source[prop]; } } } return target; } function regexEscape(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } var _entityMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;' }; function escape(data) { if (typeof data === 'string') { return data.replace(/[&<>"'\/]/g, function (s) { return _entityMap[s]; }); } return data; } var isIE10 = typeof window !== 'undefined' && window.navigator && typeof window.navigator.userAgentData === 'undefined' && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1; var chars = [' ', ',', '?', '!', ';']; function looksLikeObjectPath(key, nsSeparator, keySeparator) { nsSeparator = nsSeparator || ''; keySeparator = keySeparator || ''; var possibleChars = chars.filter(function (c) { return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0; }); if (possibleChars.length === 0) return true; var r = new RegExp("(".concat(possibleChars.map(function (c) { return c === '?' ? '\\?' : c; }).join('|'), ")")); var matched = !r.test(key); if (!matched) { var ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) { matched = true; } } return matched; } function deepFind(obj, path) { var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.'; if (!obj) return undefined; if (obj[path]) return obj[path]; var paths = path.split(keySeparator); var current = obj; for (var i = 0; i < paths.length; ++i) { if (!current) return undefined; if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) { return undefined; } if (current[paths[i]] === undefined) { var j = 2; var p = paths.slice(i, i + j).join(keySeparator); var mix = current[p]; while (mix === undefined && paths.length > i + j) { j++; p = paths.slice(i, i + j).join(keySeparator); mix = current[p]; } if (mix === undefined) return undefined; if (mix === null) return null; if (path.endsWith(p)) { if (typeof mix === 'string') return mix; if (p && typeof mix[p] === 'string') return mix[p]; } var joinedPath = paths.slice(i + j).join(keySeparator); if (joinedPath) return deepFind(mix, joinedPath, keySeparator); return undefined; } current = current[paths[i]]; } return current; } function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5(Object(source), !0).forEach(function (key) { _defineProperty$2(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ResourceStore = function (_EventEmitter) { _inherits(ResourceStore, _EventEmitter); var _super = _createSuper$3(ResourceStore); function ResourceStore(data) { var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { ns: ['translation'], defaultNS: 'translation' }; _classCallCheck$1(this, ResourceStore); _this = _super.call(this); if (isIE10) { EventEmitter.call(_assertThisInitialized(_this)); } _this.data = data || {}; _this.options = options; if (_this.options.keySeparator === undefined) { _this.options.keySeparator = '.'; } if (_this.options.ignoreJSONStructure === undefined) { _this.options.ignoreJSONStructure = true; } return _this; } _createClass$1(ResourceStore, [{ key: "addNamespaces", value: function addNamespaces(ns) { if (this.options.ns.indexOf(ns) < 0) { this.options.ns.push(ns); } } }, { key: "removeNamespaces", value: function removeNamespaces(ns) { var index = this.options.ns.indexOf(ns); if (index > -1) { this.options.ns.splice(index, 1); } } }, { key: "getResource", value: function getResource(lng, ns, key) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; var path = [lng, ns]; if (key && typeof key !== 'string') path = path.concat(key); if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.indexOf('.') > -1) { path = lng.split('.'); } var result = getPath(this.data, path); if (result || !ignoreJSONStructure || typeof key !== 'string') return result; return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator); } }, { key: "addResource", value: function addResource(lng, ns, key, value) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { silent: false }; var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; var path = [lng, ns]; if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.indexOf('.') > -1) { path = lng.split('.'); value = ns; ns = path[1]; } this.addNamespaces(ns); setPath(this.data, path, value); if (!options.silent) this.emit('added', lng, ns, key, value); } }, { key: "addResources", value: function addResources(lng, ns, resources) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { silent: false }; for (var m in resources) { if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], { silent: true }); } if (!options.silent) this.emit('added', lng, ns, resources); } }, { key: "addResourceBundle", value: function addResourceBundle(lng, ns, resources, deep, overwrite) { var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : { silent: false }; var path = [lng, ns]; if (lng.indexOf('.') > -1) { path = lng.split('.'); deep = resources; resources = ns; ns = path[1]; } this.addNamespaces(ns); var pack = getPath(this.data, path) || {}; if (deep) { deepExtend(pack, resources, overwrite); } else { pack = _objectSpread$5(_objectSpread$5({}, pack), resources); } setPath(this.data, path, pack); if (!options.silent) this.emit('added', lng, ns, resources); } }, { key: "removeResourceBundle", value: function removeResourceBundle(lng, ns) { if (this.hasResourceBundle(lng, ns)) { delete this.data[lng][ns]; } this.removeNamespaces(ns); this.emit('removed', lng, ns); } }, { key: "hasResourceBundle", value: function hasResourceBundle(lng, ns) { return this.getResource(lng, ns) !== undefined; } }, { key: "getResourceBundle", value: function getResourceBundle(lng, ns) { if (!ns) ns = this.options.defaultNS; if (this.options.compatibilityAPI === 'v1') return _objectSpread$5(_objectSpread$5({}, {}), this.getResource(lng, ns)); return this.getResource(lng, ns); } }, { key: "getDataByLanguage", value: function getDataByLanguage(lng) { return this.data[lng]; } }, { key: "hasLanguageSomeTranslations", value: function hasLanguageSomeTranslations(lng) { var data = this.getDataByLanguage(lng); var n = data && Object.keys(data) || []; return !!n.find(function (v) { return data[v] && Object.keys(data[v]).length > 0; }); } }, { key: "toJSON", value: function toJSON() { return this.data; } }]); return ResourceStore; }(EventEmitter); var postProcessor = { processors: {}, addPostProcessor: function addPostProcessor(module) { this.processors[module.name] = module; }, handle: function handle(processors, value, key, options, translator) { var _this = this; processors.forEach(function (processor) { if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator); }); return value; } }; function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty$2(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var checkedLoadedFor = {}; var Translator = function (_EventEmitter) { _inherits(Translator, _EventEmitter); var _super = _createSuper$2(Translator); function Translator(services) { var _this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck$1(this, Translator); _this = _super.call(this); if (isIE10) { EventEmitter.call(_assertThisInitialized(_this)); } copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this)); _this.options = options; if (_this.options.keySeparator === undefined) { _this.options.keySeparator = '.'; } _this.logger = baseLogger.create('translator'); return _this; } _createClass$1(Translator, [{ key: "changeLanguage", value: function changeLanguage(lng) { if (lng) this.language = lng; } }, { key: "exists", value: function exists(key) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { interpolation: {} }; if (key === undefined || key === null) { return false; } var resolved = this.resolve(key, options); return resolved && resolved.res !== undefined; } }, { key: "extractFromKey", value: function extractFromKey(key, options) { var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator; if (nsSeparator === undefined) nsSeparator = ':'; var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; var namespaces = options.ns || this.options.defaultNS || []; var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); if (wouldCheckForNsInKey && !seemsNaturalLanguage) { var m = key.match(this.interpolator.nestingRegexp); if (m && m.length > 0) { return { key: key, namespaces: namespaces }; } var parts = key.split(nsSeparator); if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift(); key = parts.join(keySeparator); } if (typeof namespaces === 'string') namespaces = [namespaces]; return { key: key, namespaces: namespaces }; } }, { key: "translate", value: function translate(keys, options, lastKey) { var _this2 = this; if (_typeof$3(options) !== 'object' && this.options.overloadTranslationOptionHandler) { options = this.options.overloadTranslationOptionHandler(arguments); } if (_typeof$3(options) === 'object') options = _objectSpread$4({}, options); if (!options) options = {}; if (keys === undefined || keys === null) return ''; if (!Array.isArray(keys)) keys = [String(keys)]; var returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails; var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options), key = _this$extractFromKey.key, namespaces = _this$extractFromKey.namespaces; var namespace = namespaces[namespaces.length - 1]; var lng = options.lng || this.language; var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; if (lng && lng.toLowerCase() === 'cimode') { if (appendNamespaceToCIMode) { var nsSeparator = options.nsSeparator || this.options.nsSeparator; if (returnDetails) { return { res: "".concat(namespace).concat(nsSeparator).concat(key), usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace }; } return "".concat(namespace).concat(nsSeparator).concat(key); } if (returnDetails) { return { res: key, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace }; } return key; } var resolved = this.resolve(keys, options); var res = resolved && resolved.res; var resUsedKey = resolved && resolved.usedKey || key; var resExactUsedKey = resolved && resolved.exactUsedKey || key; var resType = Object.prototype.toString.apply(res); var noObject = ['[object Number]', '[object Function]', '[object RegExp]']; var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays; var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number'; if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) { if (!options.returnObjects && !this.options.returnObjects) { if (!this.options.returnedObjectHandler) { this.logger.warn('accessing an object - but returnObjects options is not enabled!'); } var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$4(_objectSpread$4({}, options), {}, { ns: namespaces })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string."); if (returnDetails) { resolved.res = r; return resolved; } return r; } if (keySeparator) { var resTypeIsArray = resType === '[object Array]'; var copy = resTypeIsArray ? [] : {}; var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; for (var m in res) { if (Object.prototype.hasOwnProperty.call(res, m)) { var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m); copy[m] = this.translate(deepKey, _objectSpread$4(_objectSpread$4({}, options), { joinArrays: false, ns: namespaces })); if (copy[m] === deepKey) copy[m] = res[m]; } } res = copy; } } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') { res = res.join(joinArrays); if (res) res = this.extendTranslation(res, keys, options, lastKey); } else { var usedDefault = false; var usedKey = false; var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; var hasDefaultValue = Translator.hasDefaultValue(options); var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : ''; var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue; if (!this.isValidLookup(res) && hasDefaultValue) { usedDefault = true; res = defaultValue; } if (!this.isValidLookup(res)) { usedKey = true; res = key; } var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res; var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; if (usedKey || usedDefault || updateMissing) { this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res); if (keySeparator) { var fk = this.resolve(key, _objectSpread$4(_objectSpread$4({}, options), {}, { keySeparator: false })); if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.'); } var lngs = []; var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language); if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) { for (var i = 0; i < fallbackLngs.length; i++) { lngs.push(fallbackLngs[i]); } } else if (this.options.saveMissingTo === 'all') { lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language); } else { lngs.push(options.lng || this.language); } var send = function send(l, k, specificDefaultValue) { var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; if (_this2.options.missingKeyHandler) { _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options); } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) { _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options); } _this2.emit('missingKey', l, namespace, k, res); }; if (this.options.saveMissing) { if (this.options.saveMissingPlurals && needsPluralHandling) { lngs.forEach(function (language) { _this2.pluralResolver.getSuffixes(language, options).forEach(function (suffix) { send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue); }); }); } else { send(lngs, key, defaultValue); } } } res = this.extendTranslation(res, keys, options, resolved, lastKey); if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key); if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { if (this.options.compatibilityAPI !== 'v1') { res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : undefined); } else { res = this.options.parseMissingKeyHandler(res); } } } if (returnDetails) { resolved.res = res; return resolved; } return res; } }, { key: "extendTranslation", value: function extendTranslation(res, key, options, resolved, lastKey) { var _this3 = this; if (this.i18nFormat && this.i18nFormat.parse) { res = this.i18nFormat.parse(res, _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved: resolved }); } else if (!options.skipInterpolation) { if (options.interpolation) this.interpolator.init(_objectSpread$4(_objectSpread$4({}, options), { interpolation: _objectSpread$4(_objectSpread$4({}, this.options.interpolation), options.interpolation) })); var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); var nestBef; if (skipOnVariables) { var nb = res.match(this.interpolator.nestingRegexp); nestBef = nb && nb.length; } var data = options.replace && typeof options.replace !== 'string' ? options.replace : options; if (this.options.interpolation.defaultVariables) data = _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), data); res = this.interpolator.interpolate(res, data, options.lng || this.language, options); if (skipOnVariables) { var na = res.match(this.interpolator.nestingRegexp); var nestAft = na && na.length; if (nestBef < nestAft) options.nest = false; } if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng; if (options.nest !== false) res = this.interpolator.nest(res, function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (lastKey && lastKey[0] === args[0] && !options.context) { _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0])); return null; } return _this3.translate.apply(_this3, args.concat([key])); }, options); if (options.interpolation) this.interpolator.reset(); } var postProcess = options.postProcess || this.options.postProcess; var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess; if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) { res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$4({ i18nResolved: resolved }, options) : options, this); } return res; } }, { key: "resolve", value: function resolve(keys) { var _this4 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var found; var usedKey; var exactUsedKey; var usedLng; var usedNS; if (typeof keys === 'string') keys = [keys]; keys.forEach(function (k) { if (_this4.isValidLookup(found)) return; var extracted = _this4.extractFromKey(k, options); var key = extracted.key; usedKey = key; var namespaces = extracted.namespaces; if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS); var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string'; var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi(); var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== ''; var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng); namespaces.forEach(function (ns) { if (_this4.isValidLookup(found)) return; usedNS = ns; if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) { checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true; _this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(usedNS, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); } codes.forEach(function (code) { if (_this4.isValidLookup(found)) return; usedLng = code; var finalKeys = [key]; if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) { _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options); } else { var pluralSuffix; if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, op