@pie-lib/translator 2.19.1-next.0 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js ADDED
@@ -0,0 +1,2903 @@
1
+ function _defineProperty$1(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+
13
+ return obj;
14
+ }
15
+
16
+ function _typeof(obj) {
17
+ "@babel/helpers - typeof";
18
+
19
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
20
+ return typeof obj;
21
+ } : function (obj) {
22
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
23
+ }, _typeof(obj);
24
+ }
25
+
26
+ function _classCallCheck(instance, Constructor) {
27
+ if (!(instance instanceof Constructor)) {
28
+ throw new TypeError("Cannot call a class as a function");
29
+ }
30
+ }
31
+
32
+ function _toPrimitive(input, hint) {
33
+ if (_typeof(input) !== "object" || input === null) return input;
34
+ var prim = input[Symbol.toPrimitive];
35
+ if (prim !== undefined) {
36
+ var res = prim.call(input, hint);
37
+ if (_typeof(res) !== "object") return res;
38
+ throw new TypeError("@@toPrimitive must return a primitive value.");
39
+ }
40
+ return (hint === "string" ? String : Number)(input);
41
+ }
42
+
43
+ function _toPropertyKey(arg) {
44
+ var key = _toPrimitive(arg, "string");
45
+ return _typeof(key) === "symbol" ? key : String(key);
46
+ }
47
+
48
+ function _defineProperties(target, props) {
49
+ for (var i = 0; i < props.length; i++) {
50
+ var descriptor = props[i];
51
+ descriptor.enumerable = descriptor.enumerable || false;
52
+ descriptor.configurable = true;
53
+ if ("value" in descriptor) descriptor.writable = true;
54
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
55
+ }
56
+ }
57
+ function _createClass(Constructor, protoProps, staticProps) {
58
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
59
+ if (staticProps) _defineProperties(Constructor, staticProps);
60
+ Object.defineProperty(Constructor, "prototype", {
61
+ writable: false
62
+ });
63
+ return Constructor;
64
+ }
65
+
66
+ function _assertThisInitialized(self) {
67
+ if (self === void 0) {
68
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
69
+ }
70
+ return self;
71
+ }
72
+
73
+ function _setPrototypeOf(o, p) {
74
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
75
+ o.__proto__ = p;
76
+ return o;
77
+ };
78
+ return _setPrototypeOf(o, p);
79
+ }
80
+
81
+ function _inherits(subClass, superClass) {
82
+ if (typeof superClass !== "function" && superClass !== null) {
83
+ throw new TypeError("Super expression must either be null or a function");
84
+ }
85
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
86
+ constructor: {
87
+ value: subClass,
88
+ writable: true,
89
+ configurable: true
90
+ }
91
+ });
92
+ Object.defineProperty(subClass, "prototype", {
93
+ writable: false
94
+ });
95
+ if (superClass) _setPrototypeOf(subClass, superClass);
96
+ }
97
+
98
+ function _possibleConstructorReturn(self, call) {
99
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
100
+ return call;
101
+ } else if (call !== void 0) {
102
+ throw new TypeError("Derived constructors may only return object or undefined");
103
+ }
104
+ return _assertThisInitialized(self);
105
+ }
106
+
107
+ function _getPrototypeOf(o) {
108
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
109
+ return o.__proto__ || Object.getPrototypeOf(o);
110
+ };
111
+ return _getPrototypeOf(o);
112
+ }
113
+
114
+ function _defineProperty(obj, key, value) {
115
+ key = _toPropertyKey(key);
116
+ if (key in obj) {
117
+ Object.defineProperty(obj, key, {
118
+ value: value,
119
+ enumerable: true,
120
+ configurable: true,
121
+ writable: true
122
+ });
123
+ } else {
124
+ obj[key] = value;
125
+ }
126
+ return obj;
127
+ }
128
+
129
+ function _arrayWithHoles(arr) {
130
+ if (Array.isArray(arr)) return arr;
131
+ }
132
+
133
+ function _iterableToArray(iter) {
134
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
135
+ }
136
+
137
+ function _arrayLikeToArray(arr, len) {
138
+ if (len == null || len > arr.length) len = arr.length;
139
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
140
+ return arr2;
141
+ }
142
+
143
+ function _unsupportedIterableToArray(o, minLen) {
144
+ if (!o) return;
145
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
146
+ var n = Object.prototype.toString.call(o).slice(8, -1);
147
+ if (n === "Object" && o.constructor) n = o.constructor.name;
148
+ if (n === "Map" || n === "Set") return Array.from(o);
149
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
150
+ }
151
+
152
+ function _nonIterableRest() {
153
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
154
+ }
155
+
156
+ function _toArray(arr) {
157
+ return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
158
+ }
159
+
160
+ 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; }
161
+ 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), true).forEach(function (key) { _defineProperty(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; }
162
+ var consoleLogger = {
163
+ type: 'logger',
164
+ log: function log(args) {
165
+ this.output('log', args);
166
+ },
167
+ warn: function warn(args) {
168
+ this.output('warn', args);
169
+ },
170
+ error: function error(args) {
171
+ this.output('error', args);
172
+ },
173
+ output: function output(type, args) {
174
+ if (console && console[type]) console[type].apply(console, args);
175
+ }
176
+ };
177
+ var Logger = function () {
178
+ function Logger(concreteLogger) {
179
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
180
+ _classCallCheck(this, Logger);
181
+ this.init(concreteLogger, options);
182
+ }
183
+ _createClass(Logger, [{
184
+ key: "init",
185
+ value: function init(concreteLogger) {
186
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
187
+ this.prefix = options.prefix || 'i18next:';
188
+ this.logger = concreteLogger || consoleLogger;
189
+ this.options = options;
190
+ this.debug = options.debug;
191
+ }
192
+ }, {
193
+ key: "setDebug",
194
+ value: function setDebug(bool) {
195
+ this.debug = bool;
196
+ }
197
+ }, {
198
+ key: "log",
199
+ value: function log() {
200
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
201
+ args[_key] = arguments[_key];
202
+ }
203
+ return this.forward(args, 'log', '', true);
204
+ }
205
+ }, {
206
+ key: "warn",
207
+ value: function warn() {
208
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
209
+ args[_key2] = arguments[_key2];
210
+ }
211
+ return this.forward(args, 'warn', '', true);
212
+ }
213
+ }, {
214
+ key: "error",
215
+ value: function error() {
216
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
217
+ args[_key3] = arguments[_key3];
218
+ }
219
+ return this.forward(args, 'error', '');
220
+ }
221
+ }, {
222
+ key: "deprecate",
223
+ value: function deprecate() {
224
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
225
+ args[_key4] = arguments[_key4];
226
+ }
227
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
228
+ }
229
+ }, {
230
+ key: "forward",
231
+ value: function forward(args, lvl, prefix, debugOnly) {
232
+ if (debugOnly && !this.debug) return null;
233
+ if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
234
+ return this.logger[lvl](args);
235
+ }
236
+ }, {
237
+ key: "create",
238
+ value: function create(moduleName) {
239
+ return new Logger(this.logger, _objectSpread$6(_objectSpread$6({}, {
240
+ prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
241
+ }), this.options));
242
+ }
243
+ }, {
244
+ key: "clone",
245
+ value: function clone(options) {
246
+ options = options || this.options;
247
+ options.prefix = options.prefix || this.prefix;
248
+ return new Logger(this.logger, options);
249
+ }
250
+ }]);
251
+ return Logger;
252
+ }();
253
+ var baseLogger = new Logger();
254
+
255
+ var EventEmitter = function () {
256
+ function EventEmitter() {
257
+ _classCallCheck(this, EventEmitter);
258
+ this.observers = {};
259
+ }
260
+ _createClass(EventEmitter, [{
261
+ key: "on",
262
+ value: function on(events, listener) {
263
+ var _this = this;
264
+ events.split(' ').forEach(function (event) {
265
+ _this.observers[event] = _this.observers[event] || [];
266
+ _this.observers[event].push(listener);
267
+ });
268
+ return this;
269
+ }
270
+ }, {
271
+ key: "off",
272
+ value: function off(event, listener) {
273
+ if (!this.observers[event]) return;
274
+ if (!listener) {
275
+ delete this.observers[event];
276
+ return;
277
+ }
278
+ this.observers[event] = this.observers[event].filter(function (l) {
279
+ return l !== listener;
280
+ });
281
+ }
282
+ }, {
283
+ key: "emit",
284
+ value: function emit(event) {
285
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
286
+ args[_key - 1] = arguments[_key];
287
+ }
288
+ if (this.observers[event]) {
289
+ var cloned = [].concat(this.observers[event]);
290
+ cloned.forEach(function (observer) {
291
+ observer.apply(void 0, args);
292
+ });
293
+ }
294
+ if (this.observers['*']) {
295
+ var _cloned = [].concat(this.observers['*']);
296
+ _cloned.forEach(function (observer) {
297
+ observer.apply(observer, [event].concat(args));
298
+ });
299
+ }
300
+ }
301
+ }]);
302
+ return EventEmitter;
303
+ }();
304
+
305
+ function defer() {
306
+ var res;
307
+ var rej;
308
+ var promise = new Promise(function (resolve, reject) {
309
+ res = resolve;
310
+ rej = reject;
311
+ });
312
+ promise.resolve = res;
313
+ promise.reject = rej;
314
+ return promise;
315
+ }
316
+ function makeString(object) {
317
+ if (object == null) return '';
318
+ return '' + object;
319
+ }
320
+ function copy(a, s, t) {
321
+ a.forEach(function (m) {
322
+ if (s[m]) t[m] = s[m];
323
+ });
324
+ }
325
+ function getLastOfPath(object, path, Empty) {
326
+ function cleanKey(key) {
327
+ return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
328
+ }
329
+ function canNotTraverseDeeper() {
330
+ return !object || typeof object === 'string';
331
+ }
332
+ var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
333
+ while (stack.length > 1) {
334
+ if (canNotTraverseDeeper()) return {};
335
+ var key = cleanKey(stack.shift());
336
+ if (!object[key] && Empty) object[key] = new Empty();
337
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
338
+ object = object[key];
339
+ } else {
340
+ object = {};
341
+ }
342
+ }
343
+ if (canNotTraverseDeeper()) return {};
344
+ return {
345
+ obj: object,
346
+ k: cleanKey(stack.shift())
347
+ };
348
+ }
349
+ function setPath(object, path, newValue) {
350
+ var _getLastOfPath = getLastOfPath(object, path, Object),
351
+ obj = _getLastOfPath.obj,
352
+ k = _getLastOfPath.k;
353
+ obj[k] = newValue;
354
+ }
355
+ function pushPath(object, path, newValue, concat) {
356
+ var _getLastOfPath2 = getLastOfPath(object, path, Object),
357
+ obj = _getLastOfPath2.obj,
358
+ k = _getLastOfPath2.k;
359
+ obj[k] = obj[k] || [];
360
+ obj[k].push(newValue);
361
+ }
362
+ function getPath(object, path) {
363
+ var _getLastOfPath3 = getLastOfPath(object, path),
364
+ obj = _getLastOfPath3.obj,
365
+ k = _getLastOfPath3.k;
366
+ if (!obj) return undefined;
367
+ return obj[k];
368
+ }
369
+ function getPathWithDefaults(data, defaultData, key) {
370
+ var value = getPath(data, key);
371
+ if (value !== undefined) {
372
+ return value;
373
+ }
374
+ return getPath(defaultData, key);
375
+ }
376
+ function deepExtend(target, source, overwrite) {
377
+ for (var prop in source) {
378
+ if (prop !== '__proto__' && prop !== 'constructor') {
379
+ if (prop in target) {
380
+ if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
381
+ if (overwrite) target[prop] = source[prop];
382
+ } else {
383
+ deepExtend(target[prop], source[prop], overwrite);
384
+ }
385
+ } else {
386
+ target[prop] = source[prop];
387
+ }
388
+ }
389
+ }
390
+ return target;
391
+ }
392
+ function regexEscape(str) {
393
+ return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
394
+ }
395
+ var _entityMap = {
396
+ '&': '&amp;',
397
+ '<': '&lt;',
398
+ '>': '&gt;',
399
+ '"': '&quot;',
400
+ "'": '&#39;',
401
+ '/': '&#x2F;'
402
+ };
403
+ function escape(data) {
404
+ if (typeof data === 'string') {
405
+ return data.replace(/[&<>"'\/]/g, function (s) {
406
+ return _entityMap[s];
407
+ });
408
+ }
409
+ return data;
410
+ }
411
+ var isIE10 = typeof window !== 'undefined' && window.navigator && typeof window.navigator.userAgentData === 'undefined' && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
412
+ var chars = [' ', ',', '?', '!', ';'];
413
+ function looksLikeObjectPath(key, nsSeparator, keySeparator) {
414
+ nsSeparator = nsSeparator || '';
415
+ keySeparator = keySeparator || '';
416
+ var possibleChars = chars.filter(function (c) {
417
+ return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
418
+ });
419
+ if (possibleChars.length === 0) return true;
420
+ var r = new RegExp("(".concat(possibleChars.map(function (c) {
421
+ return c === '?' ? '\\?' : c;
422
+ }).join('|'), ")"));
423
+ var matched = !r.test(key);
424
+ if (!matched) {
425
+ var ki = key.indexOf(keySeparator);
426
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
427
+ matched = true;
428
+ }
429
+ }
430
+ return matched;
431
+ }
432
+ function deepFind(obj, path) {
433
+ var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
434
+ if (!obj) return undefined;
435
+ if (obj[path]) return obj[path];
436
+ var paths = path.split(keySeparator);
437
+ var current = obj;
438
+ for (var i = 0; i < paths.length; ++i) {
439
+ if (!current) return undefined;
440
+ if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
441
+ return undefined;
442
+ }
443
+ if (current[paths[i]] === undefined) {
444
+ var j = 2;
445
+ var p = paths.slice(i, i + j).join(keySeparator);
446
+ var mix = current[p];
447
+ while (mix === undefined && paths.length > i + j) {
448
+ j++;
449
+ p = paths.slice(i, i + j).join(keySeparator);
450
+ mix = current[p];
451
+ }
452
+ if (mix === undefined) return undefined;
453
+ if (mix === null) return null;
454
+ if (path.endsWith(p)) {
455
+ if (typeof mix === 'string') return mix;
456
+ if (p && typeof mix[p] === 'string') return mix[p];
457
+ }
458
+ var joinedPath = paths.slice(i + j).join(keySeparator);
459
+ if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
460
+ return undefined;
461
+ }
462
+ current = current[paths[i]];
463
+ }
464
+ return current;
465
+ }
466
+
467
+ 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; }
468
+ 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), true).forEach(function (key) { _defineProperty(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; }
469
+ 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); }; }
470
+ 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; } }
471
+ var ResourceStore = function (_EventEmitter) {
472
+ _inherits(ResourceStore, _EventEmitter);
473
+ var _super = _createSuper$3(ResourceStore);
474
+ function ResourceStore(data) {
475
+ var _this;
476
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
477
+ ns: ['translation'],
478
+ defaultNS: 'translation'
479
+ };
480
+ _classCallCheck(this, ResourceStore);
481
+ _this = _super.call(this);
482
+ if (isIE10) {
483
+ EventEmitter.call(_assertThisInitialized(_this));
484
+ }
485
+ _this.data = data || {};
486
+ _this.options = options;
487
+ if (_this.options.keySeparator === undefined) {
488
+ _this.options.keySeparator = '.';
489
+ }
490
+ if (_this.options.ignoreJSONStructure === undefined) {
491
+ _this.options.ignoreJSONStructure = true;
492
+ }
493
+ return _this;
494
+ }
495
+ _createClass(ResourceStore, [{
496
+ key: "addNamespaces",
497
+ value: function addNamespaces(ns) {
498
+ if (this.options.ns.indexOf(ns) < 0) {
499
+ this.options.ns.push(ns);
500
+ }
501
+ }
502
+ }, {
503
+ key: "removeNamespaces",
504
+ value: function removeNamespaces(ns) {
505
+ var index = this.options.ns.indexOf(ns);
506
+ if (index > -1) {
507
+ this.options.ns.splice(index, 1);
508
+ }
509
+ }
510
+ }, {
511
+ key: "getResource",
512
+ value: function getResource(lng, ns, key) {
513
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
514
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
515
+ var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
516
+ var path = [lng, ns];
517
+ if (key && typeof key !== 'string') path = path.concat(key);
518
+ if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
519
+ if (lng.indexOf('.') > -1) {
520
+ path = lng.split('.');
521
+ }
522
+ var result = getPath(this.data, path);
523
+ if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
524
+ return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
525
+ }
526
+ }, {
527
+ key: "addResource",
528
+ value: function addResource(lng, ns, key, value) {
529
+ var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
530
+ silent: false
531
+ };
532
+ var keySeparator = this.options.keySeparator;
533
+ if (keySeparator === undefined) keySeparator = '.';
534
+ var path = [lng, ns];
535
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
536
+ if (lng.indexOf('.') > -1) {
537
+ path = lng.split('.');
538
+ value = ns;
539
+ ns = path[1];
540
+ }
541
+ this.addNamespaces(ns);
542
+ setPath(this.data, path, value);
543
+ if (!options.silent) this.emit('added', lng, ns, key, value);
544
+ }
545
+ }, {
546
+ key: "addResources",
547
+ value: function addResources(lng, ns, resources) {
548
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
549
+ silent: false
550
+ };
551
+ for (var m in resources) {
552
+ if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
553
+ silent: true
554
+ });
555
+ }
556
+ if (!options.silent) this.emit('added', lng, ns, resources);
557
+ }
558
+ }, {
559
+ key: "addResourceBundle",
560
+ value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
561
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
562
+ silent: false
563
+ };
564
+ var path = [lng, ns];
565
+ if (lng.indexOf('.') > -1) {
566
+ path = lng.split('.');
567
+ deep = resources;
568
+ resources = ns;
569
+ ns = path[1];
570
+ }
571
+ this.addNamespaces(ns);
572
+ var pack = getPath(this.data, path) || {};
573
+ if (deep) {
574
+ deepExtend(pack, resources, overwrite);
575
+ } else {
576
+ pack = _objectSpread$5(_objectSpread$5({}, pack), resources);
577
+ }
578
+ setPath(this.data, path, pack);
579
+ if (!options.silent) this.emit('added', lng, ns, resources);
580
+ }
581
+ }, {
582
+ key: "removeResourceBundle",
583
+ value: function removeResourceBundle(lng, ns) {
584
+ if (this.hasResourceBundle(lng, ns)) {
585
+ delete this.data[lng][ns];
586
+ }
587
+ this.removeNamespaces(ns);
588
+ this.emit('removed', lng, ns);
589
+ }
590
+ }, {
591
+ key: "hasResourceBundle",
592
+ value: function hasResourceBundle(lng, ns) {
593
+ return this.getResource(lng, ns) !== undefined;
594
+ }
595
+ }, {
596
+ key: "getResourceBundle",
597
+ value: function getResourceBundle(lng, ns) {
598
+ if (!ns) ns = this.options.defaultNS;
599
+ if (this.options.compatibilityAPI === 'v1') return _objectSpread$5(_objectSpread$5({}, {}), this.getResource(lng, ns));
600
+ return this.getResource(lng, ns);
601
+ }
602
+ }, {
603
+ key: "getDataByLanguage",
604
+ value: function getDataByLanguage(lng) {
605
+ return this.data[lng];
606
+ }
607
+ }, {
608
+ key: "hasLanguageSomeTranslations",
609
+ value: function hasLanguageSomeTranslations(lng) {
610
+ var data = this.getDataByLanguage(lng);
611
+ var n = data && Object.keys(data) || [];
612
+ return !!n.find(function (v) {
613
+ return data[v] && Object.keys(data[v]).length > 0;
614
+ });
615
+ }
616
+ }, {
617
+ key: "toJSON",
618
+ value: function toJSON() {
619
+ return this.data;
620
+ }
621
+ }]);
622
+ return ResourceStore;
623
+ }(EventEmitter);
624
+
625
+ var postProcessor = {
626
+ processors: {},
627
+ addPostProcessor: function addPostProcessor(module) {
628
+ this.processors[module.name] = module;
629
+ },
630
+ handle: function handle(processors, value, key, options, translator) {
631
+ var _this = this;
632
+ processors.forEach(function (processor) {
633
+ if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
634
+ });
635
+ return value;
636
+ }
637
+ };
638
+
639
+ 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; }
640
+ 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), true).forEach(function (key) { _defineProperty(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; }
641
+ 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); }; }
642
+ 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; } }
643
+ var checkedLoadedFor = {};
644
+ var Translator = function (_EventEmitter) {
645
+ _inherits(Translator, _EventEmitter);
646
+ var _super = _createSuper$2(Translator);
647
+ function Translator(services) {
648
+ var _this;
649
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
650
+ _classCallCheck(this, Translator);
651
+ _this = _super.call(this);
652
+ if (isIE10) {
653
+ EventEmitter.call(_assertThisInitialized(_this));
654
+ }
655
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this));
656
+ _this.options = options;
657
+ if (_this.options.keySeparator === undefined) {
658
+ _this.options.keySeparator = '.';
659
+ }
660
+ _this.logger = baseLogger.create('translator');
661
+ return _this;
662
+ }
663
+ _createClass(Translator, [{
664
+ key: "changeLanguage",
665
+ value: function changeLanguage(lng) {
666
+ if (lng) this.language = lng;
667
+ }
668
+ }, {
669
+ key: "exists",
670
+ value: function exists(key) {
671
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
672
+ interpolation: {}
673
+ };
674
+ if (key === undefined || key === null) {
675
+ return false;
676
+ }
677
+ var resolved = this.resolve(key, options);
678
+ return resolved && resolved.res !== undefined;
679
+ }
680
+ }, {
681
+ key: "extractFromKey",
682
+ value: function extractFromKey(key, options) {
683
+ var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
684
+ if (nsSeparator === undefined) nsSeparator = ':';
685
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
686
+ var namespaces = options.ns || this.options.defaultNS || [];
687
+ var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
688
+ var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
689
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
690
+ var m = key.match(this.interpolator.nestingRegexp);
691
+ if (m && m.length > 0) {
692
+ return {
693
+ key: key,
694
+ namespaces: namespaces
695
+ };
696
+ }
697
+ var parts = key.split(nsSeparator);
698
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
699
+ key = parts.join(keySeparator);
700
+ }
701
+ if (typeof namespaces === 'string') namespaces = [namespaces];
702
+ return {
703
+ key: key,
704
+ namespaces: namespaces
705
+ };
706
+ }
707
+ }, {
708
+ key: "translate",
709
+ value: function translate(keys, options, lastKey) {
710
+ var _this2 = this;
711
+ if (_typeof(options) !== 'object' && this.options.overloadTranslationOptionHandler) {
712
+ options = this.options.overloadTranslationOptionHandler(arguments);
713
+ }
714
+ if (_typeof(options) === 'object') options = _objectSpread$4({}, options);
715
+ if (!options) options = {};
716
+ if (keys === undefined || keys === null) return '';
717
+ if (!Array.isArray(keys)) keys = [String(keys)];
718
+ var returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
719
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
720
+ var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
721
+ key = _this$extractFromKey.key,
722
+ namespaces = _this$extractFromKey.namespaces;
723
+ var namespace = namespaces[namespaces.length - 1];
724
+ var lng = options.lng || this.language;
725
+ var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
726
+ if (lng && lng.toLowerCase() === 'cimode') {
727
+ if (appendNamespaceToCIMode) {
728
+ var nsSeparator = options.nsSeparator || this.options.nsSeparator;
729
+ if (returnDetails) {
730
+ return {
731
+ res: "".concat(namespace).concat(nsSeparator).concat(key),
732
+ usedKey: key,
733
+ exactUsedKey: key,
734
+ usedLng: lng,
735
+ usedNS: namespace
736
+ };
737
+ }
738
+ return "".concat(namespace).concat(nsSeparator).concat(key);
739
+ }
740
+ if (returnDetails) {
741
+ return {
742
+ res: key,
743
+ usedKey: key,
744
+ exactUsedKey: key,
745
+ usedLng: lng,
746
+ usedNS: namespace
747
+ };
748
+ }
749
+ return key;
750
+ }
751
+ var resolved = this.resolve(keys, options);
752
+ var res = resolved && resolved.res;
753
+ var resUsedKey = resolved && resolved.usedKey || key;
754
+ var resExactUsedKey = resolved && resolved.exactUsedKey || key;
755
+ var resType = Object.prototype.toString.apply(res);
756
+ var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
757
+ var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
758
+ var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
759
+ var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
760
+ if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
761
+ if (!options.returnObjects && !this.options.returnObjects) {
762
+ if (!this.options.returnedObjectHandler) {
763
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
764
+ }
765
+ var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$4(_objectSpread$4({}, options), {}, {
766
+ ns: namespaces
767
+ })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
768
+ if (returnDetails) {
769
+ resolved.res = r;
770
+ return resolved;
771
+ }
772
+ return r;
773
+ }
774
+ if (keySeparator) {
775
+ var resTypeIsArray = resType === '[object Array]';
776
+ var copy = resTypeIsArray ? [] : {};
777
+ var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
778
+ for (var m in res) {
779
+ if (Object.prototype.hasOwnProperty.call(res, m)) {
780
+ var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
781
+ copy[m] = this.translate(deepKey, _objectSpread$4(_objectSpread$4({}, options), {
782
+ joinArrays: false,
783
+ ns: namespaces
784
+ }));
785
+ if (copy[m] === deepKey) copy[m] = res[m];
786
+ }
787
+ }
788
+ res = copy;
789
+ }
790
+ } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
791
+ res = res.join(joinArrays);
792
+ if (res) res = this.extendTranslation(res, keys, options, lastKey);
793
+ } else {
794
+ var usedDefault = false;
795
+ var usedKey = false;
796
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
797
+ var hasDefaultValue = Translator.hasDefaultValue(options);
798
+ var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
799
+ var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
800
+ if (!this.isValidLookup(res) && hasDefaultValue) {
801
+ usedDefault = true;
802
+ res = defaultValue;
803
+ }
804
+ if (!this.isValidLookup(res)) {
805
+ usedKey = true;
806
+ res = key;
807
+ }
808
+ var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
809
+ var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
810
+ var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
811
+ if (usedKey || usedDefault || updateMissing) {
812
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
813
+ if (keySeparator) {
814
+ var fk = this.resolve(key, _objectSpread$4(_objectSpread$4({}, options), {}, {
815
+ keySeparator: false
816
+ }));
817
+ 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.');
818
+ }
819
+ var lngs = [];
820
+ var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
821
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
822
+ for (var i = 0; i < fallbackLngs.length; i++) {
823
+ lngs.push(fallbackLngs[i]);
824
+ }
825
+ } else if (this.options.saveMissingTo === 'all') {
826
+ lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
827
+ } else {
828
+ lngs.push(options.lng || this.language);
829
+ }
830
+ var send = function send(l, k, specificDefaultValue) {
831
+ var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
832
+ if (_this2.options.missingKeyHandler) {
833
+ _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
834
+ } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
835
+ _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
836
+ }
837
+ _this2.emit('missingKey', l, namespace, k, res);
838
+ };
839
+ if (this.options.saveMissing) {
840
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
841
+ lngs.forEach(function (language) {
842
+ _this2.pluralResolver.getSuffixes(language, options).forEach(function (suffix) {
843
+ send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
844
+ });
845
+ });
846
+ } else {
847
+ send(lngs, key, defaultValue);
848
+ }
849
+ }
850
+ }
851
+ res = this.extendTranslation(res, keys, options, resolved, lastKey);
852
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
853
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
854
+ if (this.options.compatibilityAPI !== 'v1') {
855
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : undefined);
856
+ } else {
857
+ res = this.options.parseMissingKeyHandler(res);
858
+ }
859
+ }
860
+ }
861
+ if (returnDetails) {
862
+ resolved.res = res;
863
+ return resolved;
864
+ }
865
+ return res;
866
+ }
867
+ }, {
868
+ key: "extendTranslation",
869
+ value: function extendTranslation(res, key, options, resolved, lastKey) {
870
+ var _this3 = this;
871
+ if (this.i18nFormat && this.i18nFormat.parse) {
872
+ res = this.i18nFormat.parse(res, _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, {
873
+ resolved: resolved
874
+ });
875
+ } else if (!options.skipInterpolation) {
876
+ if (options.interpolation) this.interpolator.init(_objectSpread$4(_objectSpread$4({}, options), {
877
+ interpolation: _objectSpread$4(_objectSpread$4({}, this.options.interpolation), options.interpolation)
878
+ }));
879
+ var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
880
+ var nestBef;
881
+ if (skipOnVariables) {
882
+ var nb = res.match(this.interpolator.nestingRegexp);
883
+ nestBef = nb && nb.length;
884
+ }
885
+ var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
886
+ if (this.options.interpolation.defaultVariables) data = _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), data);
887
+ res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
888
+ if (skipOnVariables) {
889
+ var na = res.match(this.interpolator.nestingRegexp);
890
+ var nestAft = na && na.length;
891
+ if (nestBef < nestAft) options.nest = false;
892
+ }
893
+ if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;
894
+ if (options.nest !== false) res = this.interpolator.nest(res, function () {
895
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
896
+ args[_key] = arguments[_key];
897
+ }
898
+ if (lastKey && lastKey[0] === args[0] && !options.context) {
899
+ _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
900
+ return null;
901
+ }
902
+ return _this3.translate.apply(_this3, args.concat([key]));
903
+ }, options);
904
+ if (options.interpolation) this.interpolator.reset();
905
+ }
906
+ var postProcess = options.postProcess || this.options.postProcess;
907
+ var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
908
+ if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
909
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$4({
910
+ i18nResolved: resolved
911
+ }, options) : options, this);
912
+ }
913
+ return res;
914
+ }
915
+ }, {
916
+ key: "resolve",
917
+ value: function resolve(keys) {
918
+ var _this4 = this;
919
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
920
+ var found;
921
+ var usedKey;
922
+ var exactUsedKey;
923
+ var usedLng;
924
+ var usedNS;
925
+ if (typeof keys === 'string') keys = [keys];
926
+ keys.forEach(function (k) {
927
+ if (_this4.isValidLookup(found)) return;
928
+ var extracted = _this4.extractFromKey(k, options);
929
+ var key = extracted.key;
930
+ usedKey = key;
931
+ var namespaces = extracted.namespaces;
932
+ if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
933
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
934
+ var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
935
+ var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
936
+ var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
937
+ namespaces.forEach(function (ns) {
938
+ if (_this4.isValidLookup(found)) return;
939
+ usedNS = ns;
940
+ if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
941
+ checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
942
+ _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!!!');
943
+ }
944
+ codes.forEach(function (code) {
945
+ if (_this4.isValidLookup(found)) return;
946
+ usedLng = code;
947
+ var finalKeys = [key];
948
+ if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
949
+ _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
950
+ } else {
951
+ var pluralSuffix;
952
+ if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
953
+ var zeroSuffix = "".concat(_this4.options.pluralSeparator, "zero");
954
+ if (needsPluralHandling) {
955
+ finalKeys.push(key + pluralSuffix);
956
+ if (needsZeroSuffixLookup) {
957
+ finalKeys.push(key + zeroSuffix);
958
+ }
959
+ }
960
+ if (needsContextHandling) {
961
+ var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
962
+ finalKeys.push(contextKey);
963
+ if (needsPluralHandling) {
964
+ finalKeys.push(contextKey + pluralSuffix);
965
+ if (needsZeroSuffixLookup) {
966
+ finalKeys.push(contextKey + zeroSuffix);
967
+ }
968
+ }
969
+ }
970
+ }
971
+ var possibleKey;
972
+ while (possibleKey = finalKeys.pop()) {
973
+ if (!_this4.isValidLookup(found)) {
974
+ exactUsedKey = possibleKey;
975
+ found = _this4.getResource(code, ns, possibleKey, options);
976
+ }
977
+ }
978
+ });
979
+ });
980
+ });
981
+ return {
982
+ res: found,
983
+ usedKey: usedKey,
984
+ exactUsedKey: exactUsedKey,
985
+ usedLng: usedLng,
986
+ usedNS: usedNS
987
+ };
988
+ }
989
+ }, {
990
+ key: "isValidLookup",
991
+ value: function isValidLookup(res) {
992
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
993
+ }
994
+ }, {
995
+ key: "getResource",
996
+ value: function getResource(code, ns, key) {
997
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
998
+ if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
999
+ return this.resourceStore.getResource(code, ns, key, options);
1000
+ }
1001
+ }], [{
1002
+ key: "hasDefaultValue",
1003
+ value: function hasDefaultValue(options) {
1004
+ var prefix = 'defaultValue';
1005
+ for (var option in options) {
1006
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1007
+ return true;
1008
+ }
1009
+ }
1010
+ return false;
1011
+ }
1012
+ }]);
1013
+ return Translator;
1014
+ }(EventEmitter);
1015
+
1016
+ function capitalize(string) {
1017
+ return string.charAt(0).toUpperCase() + string.slice(1);
1018
+ }
1019
+ var LanguageUtil = function () {
1020
+ function LanguageUtil(options) {
1021
+ _classCallCheck(this, LanguageUtil);
1022
+ this.options = options;
1023
+ this.supportedLngs = this.options.supportedLngs || false;
1024
+ this.logger = baseLogger.create('languageUtils');
1025
+ }
1026
+ _createClass(LanguageUtil, [{
1027
+ key: "getScriptPartFromCode",
1028
+ value: function getScriptPartFromCode(code) {
1029
+ if (!code || code.indexOf('-') < 0) return null;
1030
+ var p = code.split('-');
1031
+ if (p.length === 2) return null;
1032
+ p.pop();
1033
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
1034
+ return this.formatLanguageCode(p.join('-'));
1035
+ }
1036
+ }, {
1037
+ key: "getLanguagePartFromCode",
1038
+ value: function getLanguagePartFromCode(code) {
1039
+ if (!code || code.indexOf('-') < 0) return code;
1040
+ var p = code.split('-');
1041
+ return this.formatLanguageCode(p[0]);
1042
+ }
1043
+ }, {
1044
+ key: "formatLanguageCode",
1045
+ value: function formatLanguageCode(code) {
1046
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
1047
+ var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
1048
+ var p = code.split('-');
1049
+ if (this.options.lowerCaseLng) {
1050
+ p = p.map(function (part) {
1051
+ return part.toLowerCase();
1052
+ });
1053
+ } else if (p.length === 2) {
1054
+ p[0] = p[0].toLowerCase();
1055
+ p[1] = p[1].toUpperCase();
1056
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1057
+ } else if (p.length === 3) {
1058
+ p[0] = p[0].toLowerCase();
1059
+ if (p[1].length === 2) p[1] = p[1].toUpperCase();
1060
+ if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
1061
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1062
+ if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
1063
+ }
1064
+ return p.join('-');
1065
+ }
1066
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1067
+ }
1068
+ }, {
1069
+ key: "isSupportedCode",
1070
+ value: function isSupportedCode(code) {
1071
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1072
+ code = this.getLanguagePartFromCode(code);
1073
+ }
1074
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1075
+ }
1076
+ }, {
1077
+ key: "getBestMatchFromCodes",
1078
+ value: function getBestMatchFromCodes(codes) {
1079
+ var _this = this;
1080
+ if (!codes) return null;
1081
+ var found;
1082
+ codes.forEach(function (code) {
1083
+ if (found) return;
1084
+ var cleanedLng = _this.formatLanguageCode(code);
1085
+ if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
1086
+ });
1087
+ if (!found && this.options.supportedLngs) {
1088
+ codes.forEach(function (code) {
1089
+ if (found) return;
1090
+ var lngOnly = _this.getLanguagePartFromCode(code);
1091
+ if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
1092
+ found = _this.options.supportedLngs.find(function (supportedLng) {
1093
+ if (supportedLng === lngOnly) return supportedLng;
1094
+ if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1095
+ if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
1096
+ });
1097
+ });
1098
+ }
1099
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1100
+ return found;
1101
+ }
1102
+ }, {
1103
+ key: "getFallbackCodes",
1104
+ value: function getFallbackCodes(fallbacks, code) {
1105
+ if (!fallbacks) return [];
1106
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1107
+ if (typeof fallbacks === 'string') fallbacks = [fallbacks];
1108
+ if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
1109
+ if (!code) return fallbacks["default"] || [];
1110
+ var found = fallbacks[code];
1111
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1112
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1113
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1114
+ if (!found) found = fallbacks["default"];
1115
+ return found || [];
1116
+ }
1117
+ }, {
1118
+ key: "toResolveHierarchy",
1119
+ value: function toResolveHierarchy(code, fallbackCode) {
1120
+ var _this2 = this;
1121
+ var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
1122
+ var codes = [];
1123
+ var addCode = function addCode(c) {
1124
+ if (!c) return;
1125
+ if (_this2.isSupportedCode(c)) {
1126
+ codes.push(c);
1127
+ } else {
1128
+ _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
1129
+ }
1130
+ };
1131
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
1132
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1133
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1134
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1135
+ } else if (typeof code === 'string') {
1136
+ addCode(this.formatLanguageCode(code));
1137
+ }
1138
+ fallbackCodes.forEach(function (fc) {
1139
+ if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
1140
+ });
1141
+ return codes;
1142
+ }
1143
+ }]);
1144
+ return LanguageUtil;
1145
+ }();
1146
+
1147
+ var sets = [{
1148
+ lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
1149
+ nr: [1, 2],
1150
+ fc: 1
1151
+ }, {
1152
+ lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
1153
+ nr: [1, 2],
1154
+ fc: 2
1155
+ }, {
1156
+ lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
1157
+ nr: [1],
1158
+ fc: 3
1159
+ }, {
1160
+ lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
1161
+ nr: [1, 2, 5],
1162
+ fc: 4
1163
+ }, {
1164
+ lngs: ['ar'],
1165
+ nr: [0, 1, 2, 3, 11, 100],
1166
+ fc: 5
1167
+ }, {
1168
+ lngs: ['cs', 'sk'],
1169
+ nr: [1, 2, 5],
1170
+ fc: 6
1171
+ }, {
1172
+ lngs: ['csb', 'pl'],
1173
+ nr: [1, 2, 5],
1174
+ fc: 7
1175
+ }, {
1176
+ lngs: ['cy'],
1177
+ nr: [1, 2, 3, 8],
1178
+ fc: 8
1179
+ }, {
1180
+ lngs: ['fr'],
1181
+ nr: [1, 2],
1182
+ fc: 9
1183
+ }, {
1184
+ lngs: ['ga'],
1185
+ nr: [1, 2, 3, 7, 11],
1186
+ fc: 10
1187
+ }, {
1188
+ lngs: ['gd'],
1189
+ nr: [1, 2, 3, 20],
1190
+ fc: 11
1191
+ }, {
1192
+ lngs: ['is'],
1193
+ nr: [1, 2],
1194
+ fc: 12
1195
+ }, {
1196
+ lngs: ['jv'],
1197
+ nr: [0, 1],
1198
+ fc: 13
1199
+ }, {
1200
+ lngs: ['kw'],
1201
+ nr: [1, 2, 3, 4],
1202
+ fc: 14
1203
+ }, {
1204
+ lngs: ['lt'],
1205
+ nr: [1, 2, 10],
1206
+ fc: 15
1207
+ }, {
1208
+ lngs: ['lv'],
1209
+ nr: [1, 2, 0],
1210
+ fc: 16
1211
+ }, {
1212
+ lngs: ['mk'],
1213
+ nr: [1, 2],
1214
+ fc: 17
1215
+ }, {
1216
+ lngs: ['mnk'],
1217
+ nr: [0, 1, 2],
1218
+ fc: 18
1219
+ }, {
1220
+ lngs: ['mt'],
1221
+ nr: [1, 2, 11, 20],
1222
+ fc: 19
1223
+ }, {
1224
+ lngs: ['or'],
1225
+ nr: [2, 1],
1226
+ fc: 2
1227
+ }, {
1228
+ lngs: ['ro'],
1229
+ nr: [1, 2, 20],
1230
+ fc: 20
1231
+ }, {
1232
+ lngs: ['sl'],
1233
+ nr: [5, 1, 2, 3],
1234
+ fc: 21
1235
+ }, {
1236
+ lngs: ['he', 'iw'],
1237
+ nr: [1, 2, 20, 21],
1238
+ fc: 22
1239
+ }];
1240
+ var _rulesPluralsTypes = {
1241
+ 1: function _(n) {
1242
+ return Number(n > 1);
1243
+ },
1244
+ 2: function _(n) {
1245
+ return Number(n != 1);
1246
+ },
1247
+ 3: function _(n) {
1248
+ return 0;
1249
+ },
1250
+ 4: function _(n) {
1251
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1252
+ },
1253
+ 5: function _(n) {
1254
+ return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
1255
+ },
1256
+ 6: function _(n) {
1257
+ return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
1258
+ },
1259
+ 7: function _(n) {
1260
+ return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1261
+ },
1262
+ 8: function _(n) {
1263
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
1264
+ },
1265
+ 9: function _(n) {
1266
+ return Number(n >= 2);
1267
+ },
1268
+ 10: function _(n) {
1269
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
1270
+ },
1271
+ 11: function _(n) {
1272
+ return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
1273
+ },
1274
+ 12: function _(n) {
1275
+ return Number(n % 10 != 1 || n % 100 == 11);
1276
+ },
1277
+ 13: function _(n) {
1278
+ return Number(n !== 0);
1279
+ },
1280
+ 14: function _(n) {
1281
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
1282
+ },
1283
+ 15: function _(n) {
1284
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1285
+ },
1286
+ 16: function _(n) {
1287
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
1288
+ },
1289
+ 17: function _(n) {
1290
+ return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
1291
+ },
1292
+ 18: function _(n) {
1293
+ return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
1294
+ },
1295
+ 19: function _(n) {
1296
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
1297
+ },
1298
+ 20: function _(n) {
1299
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
1300
+ },
1301
+ 21: function _(n) {
1302
+ return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
1303
+ },
1304
+ 22: function _(n) {
1305
+ return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
1306
+ }
1307
+ };
1308
+ var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
1309
+ var suffixesOrder = {
1310
+ zero: 0,
1311
+ one: 1,
1312
+ two: 2,
1313
+ few: 3,
1314
+ many: 4,
1315
+ other: 5
1316
+ };
1317
+ function createRules() {
1318
+ var rules = {};
1319
+ sets.forEach(function (set) {
1320
+ set.lngs.forEach(function (l) {
1321
+ rules[l] = {
1322
+ numbers: set.nr,
1323
+ plurals: _rulesPluralsTypes[set.fc]
1324
+ };
1325
+ });
1326
+ });
1327
+ return rules;
1328
+ }
1329
+ var PluralResolver = function () {
1330
+ function PluralResolver(languageUtils) {
1331
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1332
+ _classCallCheck(this, PluralResolver);
1333
+ this.languageUtils = languageUtils;
1334
+ this.options = options;
1335
+ this.logger = baseLogger.create('pluralResolver');
1336
+ if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
1337
+ this.options.compatibilityJSON = 'v3';
1338
+ this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
1339
+ }
1340
+ this.rules = createRules();
1341
+ }
1342
+ _createClass(PluralResolver, [{
1343
+ key: "addRule",
1344
+ value: function addRule(lng, obj) {
1345
+ this.rules[lng] = obj;
1346
+ }
1347
+ }, {
1348
+ key: "getRule",
1349
+ value: function getRule(code) {
1350
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1351
+ if (this.shouldUseIntlApi()) {
1352
+ try {
1353
+ return new Intl.PluralRules(code, {
1354
+ type: options.ordinal ? 'ordinal' : 'cardinal'
1355
+ });
1356
+ } catch (_unused) {
1357
+ return;
1358
+ }
1359
+ }
1360
+ return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1361
+ }
1362
+ }, {
1363
+ key: "needsPlural",
1364
+ value: function needsPlural(code) {
1365
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1366
+ var rule = this.getRule(code, options);
1367
+ if (this.shouldUseIntlApi()) {
1368
+ return rule && rule.resolvedOptions().pluralCategories.length > 1;
1369
+ }
1370
+ return rule && rule.numbers.length > 1;
1371
+ }
1372
+ }, {
1373
+ key: "getPluralFormsOfKey",
1374
+ value: function getPluralFormsOfKey(code, key) {
1375
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1376
+ return this.getSuffixes(code, options).map(function (suffix) {
1377
+ return "".concat(key).concat(suffix);
1378
+ });
1379
+ }
1380
+ }, {
1381
+ key: "getSuffixes",
1382
+ value: function getSuffixes(code) {
1383
+ var _this = this;
1384
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1385
+ var rule = this.getRule(code, options);
1386
+ if (!rule) {
1387
+ return [];
1388
+ }
1389
+ if (this.shouldUseIntlApi()) {
1390
+ return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
1391
+ return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
1392
+ }).map(function (pluralCategory) {
1393
+ return "".concat(_this.options.prepend).concat(pluralCategory);
1394
+ });
1395
+ }
1396
+ return rule.numbers.map(function (number) {
1397
+ return _this.getSuffix(code, number, options);
1398
+ });
1399
+ }
1400
+ }, {
1401
+ key: "getSuffix",
1402
+ value: function getSuffix(code, count) {
1403
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1404
+ var rule = this.getRule(code, options);
1405
+ if (rule) {
1406
+ if (this.shouldUseIntlApi()) {
1407
+ return "".concat(this.options.prepend).concat(rule.select(count));
1408
+ }
1409
+ return this.getSuffixRetroCompatible(rule, count);
1410
+ }
1411
+ this.logger.warn("no plural rule found for: ".concat(code));
1412
+ return '';
1413
+ }
1414
+ }, {
1415
+ key: "getSuffixRetroCompatible",
1416
+ value: function getSuffixRetroCompatible(rule, count) {
1417
+ var _this2 = this;
1418
+ var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
1419
+ var suffix = rule.numbers[idx];
1420
+ if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1421
+ if (suffix === 2) {
1422
+ suffix = 'plural';
1423
+ } else if (suffix === 1) {
1424
+ suffix = '';
1425
+ }
1426
+ }
1427
+ var returnSuffix = function returnSuffix() {
1428
+ return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
1429
+ };
1430
+ if (this.options.compatibilityJSON === 'v1') {
1431
+ if (suffix === 1) return '';
1432
+ if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
1433
+ return returnSuffix();
1434
+ } else if (this.options.compatibilityJSON === 'v2') {
1435
+ return returnSuffix();
1436
+ } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1437
+ return returnSuffix();
1438
+ }
1439
+ return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
1440
+ }
1441
+ }, {
1442
+ key: "shouldUseIntlApi",
1443
+ value: function shouldUseIntlApi() {
1444
+ return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
1445
+ }
1446
+ }]);
1447
+ return PluralResolver;
1448
+ }();
1449
+
1450
+ function ownKeys$3(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; }
1451
+ function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1452
+ function deepFindWithDefaults(data, defaultData, key) {
1453
+ var keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
1454
+ var ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
1455
+ var path = getPathWithDefaults(data, defaultData, key);
1456
+ if (!path && ignoreJSONStructure && typeof key === 'string') {
1457
+ path = deepFind(data, key, keySeparator);
1458
+ if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1459
+ }
1460
+ return path;
1461
+ }
1462
+ var Interpolator = function () {
1463
+ function Interpolator() {
1464
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1465
+ _classCallCheck(this, Interpolator);
1466
+ this.logger = baseLogger.create('interpolator');
1467
+ this.options = options;
1468
+ this.format = options.interpolation && options.interpolation.format || function (value) {
1469
+ return value;
1470
+ };
1471
+ this.init(options);
1472
+ }
1473
+ _createClass(Interpolator, [{
1474
+ key: "init",
1475
+ value: function init() {
1476
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1477
+ if (!options.interpolation) options.interpolation = {
1478
+ escapeValue: true
1479
+ };
1480
+ var iOpts = options.interpolation;
1481
+ this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
1482
+ this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
1483
+ this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
1484
+ this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
1485
+ this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
1486
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1487
+ this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
1488
+ this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
1489
+ this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
1490
+ this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
1491
+ this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
1492
+ this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
1493
+ this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
1494
+ this.resetRegExp();
1495
+ }
1496
+ }, {
1497
+ key: "reset",
1498
+ value: function reset() {
1499
+ if (this.options) this.init(this.options);
1500
+ }
1501
+ }, {
1502
+ key: "resetRegExp",
1503
+ value: function resetRegExp() {
1504
+ var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
1505
+ this.regexp = new RegExp(regexpStr, 'g');
1506
+ var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
1507
+ this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
1508
+ var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
1509
+ this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
1510
+ }
1511
+ }, {
1512
+ key: "interpolate",
1513
+ value: function interpolate(str, data, lng, options) {
1514
+ var _this = this;
1515
+ var match;
1516
+ var value;
1517
+ var replaces;
1518
+ var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1519
+ function regexSafe(val) {
1520
+ return val.replace(/\$/g, '$$$$');
1521
+ }
1522
+ var handleFormat = function handleFormat(key) {
1523
+ if (key.indexOf(_this.formatSeparator) < 0) {
1524
+ var path = deepFindWithDefaults(data, defaultData, key, _this.options.keySeparator, _this.options.ignoreJSONStructure);
1525
+ return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
1526
+ interpolationkey: key
1527
+ })) : path;
1528
+ }
1529
+ var p = key.split(_this.formatSeparator);
1530
+ var k = p.shift().trim();
1531
+ var f = p.join(_this.formatSeparator).trim();
1532
+ return _this.format(deepFindWithDefaults(data, defaultData, k, _this.options.keySeparator, _this.options.ignoreJSONStructure), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
1533
+ interpolationkey: k
1534
+ }));
1535
+ };
1536
+ this.resetRegExp();
1537
+ var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
1538
+ var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1539
+ var todos = [{
1540
+ regex: this.regexpUnescape,
1541
+ safeValue: function safeValue(val) {
1542
+ return regexSafe(val);
1543
+ }
1544
+ }, {
1545
+ regex: this.regexp,
1546
+ safeValue: function safeValue(val) {
1547
+ return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
1548
+ }
1549
+ }];
1550
+ todos.forEach(function (todo) {
1551
+ replaces = 0;
1552
+ while (match = todo.regex.exec(str)) {
1553
+ var matchedVar = match[1].trim();
1554
+ value = handleFormat(matchedVar);
1555
+ if (value === undefined) {
1556
+ if (typeof missingInterpolationHandler === 'function') {
1557
+ var temp = missingInterpolationHandler(str, match, options);
1558
+ value = typeof temp === 'string' ? temp : '';
1559
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1560
+ value = '';
1561
+ } else if (skipOnVariables) {
1562
+ value = match[0];
1563
+ continue;
1564
+ } else {
1565
+ _this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str));
1566
+ value = '';
1567
+ }
1568
+ } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
1569
+ value = makeString(value);
1570
+ }
1571
+ var safeValue = todo.safeValue(value);
1572
+ str = str.replace(match[0], safeValue);
1573
+ if (skipOnVariables) {
1574
+ todo.regex.lastIndex += value.length;
1575
+ todo.regex.lastIndex -= match[0].length;
1576
+ } else {
1577
+ todo.regex.lastIndex = 0;
1578
+ }
1579
+ replaces++;
1580
+ if (replaces >= _this.maxReplaces) {
1581
+ break;
1582
+ }
1583
+ }
1584
+ });
1585
+ return str;
1586
+ }
1587
+ }, {
1588
+ key: "nest",
1589
+ value: function nest(str, fc) {
1590
+ var _this2 = this;
1591
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1592
+ var match;
1593
+ var value;
1594
+ var clonedOptions;
1595
+ function handleHasOptions(key, inheritedOptions) {
1596
+ var sep = this.nestingOptionsSeparator;
1597
+ if (key.indexOf(sep) < 0) return key;
1598
+ var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
1599
+ var optionsString = "{".concat(c[1]);
1600
+ key = c[0];
1601
+ optionsString = this.interpolate(optionsString, clonedOptions);
1602
+ var matchedSingleQuotes = optionsString.match(/'/g);
1603
+ var matchedDoubleQuotes = optionsString.match(/"/g);
1604
+ if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1605
+ optionsString = optionsString.replace(/'/g, '"');
1606
+ }
1607
+ try {
1608
+ clonedOptions = JSON.parse(optionsString);
1609
+ if (inheritedOptions) clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
1610
+ } catch (e) {
1611
+ this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
1612
+ return "".concat(key).concat(sep).concat(optionsString);
1613
+ }
1614
+ delete clonedOptions.defaultValue;
1615
+ return key;
1616
+ }
1617
+ while (match = this.nestingRegexp.exec(str)) {
1618
+ var formatters = [];
1619
+ clonedOptions = _objectSpread$3({}, options);
1620
+ clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
1621
+ clonedOptions.applyPostProcessor = false;
1622
+ delete clonedOptions.defaultValue;
1623
+ var doReduce = false;
1624
+ if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1625
+ var r = match[1].split(this.formatSeparator).map(function (elem) {
1626
+ return elem.trim();
1627
+ });
1628
+ match[1] = r.shift();
1629
+ formatters = r;
1630
+ doReduce = true;
1631
+ }
1632
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1633
+ if (value && match[0] === str && typeof value !== 'string') return value;
1634
+ if (typeof value !== 'string') value = makeString(value);
1635
+ if (!value) {
1636
+ this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
1637
+ value = '';
1638
+ }
1639
+ if (doReduce) {
1640
+ value = formatters.reduce(function (v, f) {
1641
+ return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
1642
+ interpolationkey: match[1].trim()
1643
+ }));
1644
+ }, value.trim());
1645
+ }
1646
+ str = str.replace(match[0], value);
1647
+ this.regexp.lastIndex = 0;
1648
+ }
1649
+ return str;
1650
+ }
1651
+ }]);
1652
+ return Interpolator;
1653
+ }();
1654
+
1655
+ function ownKeys$2(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; }
1656
+ function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1657
+ function parseFormatStr(formatStr) {
1658
+ var formatName = formatStr.toLowerCase().trim();
1659
+ var formatOptions = {};
1660
+ if (formatStr.indexOf('(') > -1) {
1661
+ var p = formatStr.split('(');
1662
+ formatName = p[0].toLowerCase().trim();
1663
+ var optStr = p[1].substring(0, p[1].length - 1);
1664
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1665
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1666
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1667
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1668
+ } else {
1669
+ var opts = optStr.split(';');
1670
+ opts.forEach(function (opt) {
1671
+ if (!opt) return;
1672
+ var _opt$split = opt.split(':'),
1673
+ _opt$split2 = _toArray(_opt$split),
1674
+ key = _opt$split2[0],
1675
+ rest = _opt$split2.slice(1);
1676
+ var val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1677
+ if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
1678
+ if (val === 'false') formatOptions[key.trim()] = false;
1679
+ if (val === 'true') formatOptions[key.trim()] = true;
1680
+ if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
1681
+ });
1682
+ }
1683
+ }
1684
+ return {
1685
+ formatName: formatName,
1686
+ formatOptions: formatOptions
1687
+ };
1688
+ }
1689
+ function createCachedFormatter(fn) {
1690
+ var cache = {};
1691
+ return function invokeFormatter(val, lng, options) {
1692
+ var key = lng + JSON.stringify(options);
1693
+ var formatter = cache[key];
1694
+ if (!formatter) {
1695
+ formatter = fn(lng, options);
1696
+ cache[key] = formatter;
1697
+ }
1698
+ return formatter(val);
1699
+ };
1700
+ }
1701
+ var Formatter = function () {
1702
+ function Formatter() {
1703
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1704
+ _classCallCheck(this, Formatter);
1705
+ this.logger = baseLogger.create('formatter');
1706
+ this.options = options;
1707
+ this.formats = {
1708
+ number: createCachedFormatter(function (lng, opt) {
1709
+ var formatter = new Intl.NumberFormat(lng, _objectSpread$2({}, opt));
1710
+ return function (val) {
1711
+ return formatter.format(val);
1712
+ };
1713
+ }),
1714
+ currency: createCachedFormatter(function (lng, opt) {
1715
+ var formatter = new Intl.NumberFormat(lng, _objectSpread$2(_objectSpread$2({}, opt), {}, {
1716
+ style: 'currency'
1717
+ }));
1718
+ return function (val) {
1719
+ return formatter.format(val);
1720
+ };
1721
+ }),
1722
+ datetime: createCachedFormatter(function (lng, opt) {
1723
+ var formatter = new Intl.DateTimeFormat(lng, _objectSpread$2({}, opt));
1724
+ return function (val) {
1725
+ return formatter.format(val);
1726
+ };
1727
+ }),
1728
+ relativetime: createCachedFormatter(function (lng, opt) {
1729
+ var formatter = new Intl.RelativeTimeFormat(lng, _objectSpread$2({}, opt));
1730
+ return function (val) {
1731
+ return formatter.format(val, opt.range || 'day');
1732
+ };
1733
+ }),
1734
+ list: createCachedFormatter(function (lng, opt) {
1735
+ var formatter = new Intl.ListFormat(lng, _objectSpread$2({}, opt));
1736
+ return function (val) {
1737
+ return formatter.format(val);
1738
+ };
1739
+ })
1740
+ };
1741
+ this.init(options);
1742
+ }
1743
+ _createClass(Formatter, [{
1744
+ key: "init",
1745
+ value: function init(services) {
1746
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1747
+ interpolation: {}
1748
+ };
1749
+ var iOpts = options.interpolation;
1750
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1751
+ }
1752
+ }, {
1753
+ key: "add",
1754
+ value: function add(name, fc) {
1755
+ this.formats[name.toLowerCase().trim()] = fc;
1756
+ }
1757
+ }, {
1758
+ key: "addCached",
1759
+ value: function addCached(name, fc) {
1760
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1761
+ }
1762
+ }, {
1763
+ key: "format",
1764
+ value: function format(value, _format, lng) {
1765
+ var _this = this;
1766
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1767
+ var formats = _format.split(this.formatSeparator);
1768
+ var result = formats.reduce(function (mem, f) {
1769
+ var _parseFormatStr = parseFormatStr(f),
1770
+ formatName = _parseFormatStr.formatName,
1771
+ formatOptions = _parseFormatStr.formatOptions;
1772
+ if (_this.formats[formatName]) {
1773
+ var formatted = mem;
1774
+ try {
1775
+ var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
1776
+ var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1777
+ formatted = _this.formats[formatName](mem, l, _objectSpread$2(_objectSpread$2(_objectSpread$2({}, formatOptions), options), valOptions));
1778
+ } catch (error) {
1779
+ _this.logger.warn(error);
1780
+ }
1781
+ return formatted;
1782
+ } else {
1783
+ _this.logger.warn("there was no format function for ".concat(formatName));
1784
+ }
1785
+ return mem;
1786
+ }, value);
1787
+ return result;
1788
+ }
1789
+ }]);
1790
+ return Formatter;
1791
+ }();
1792
+
1793
+ function ownKeys$1(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; }
1794
+ function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1795
+ function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); 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); }; }
1796
+ function _isNativeReflectConstruct$1() { 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; } }
1797
+ function removePending(q, name) {
1798
+ if (q.pending[name] !== undefined) {
1799
+ delete q.pending[name];
1800
+ q.pendingCount--;
1801
+ }
1802
+ }
1803
+ var Connector = function (_EventEmitter) {
1804
+ _inherits(Connector, _EventEmitter);
1805
+ var _super = _createSuper$1(Connector);
1806
+ function Connector(backend, store, services) {
1807
+ var _this;
1808
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1809
+ _classCallCheck(this, Connector);
1810
+ _this = _super.call(this);
1811
+ if (isIE10) {
1812
+ EventEmitter.call(_assertThisInitialized(_this));
1813
+ }
1814
+ _this.backend = backend;
1815
+ _this.store = store;
1816
+ _this.services = services;
1817
+ _this.languageUtils = services.languageUtils;
1818
+ _this.options = options;
1819
+ _this.logger = baseLogger.create('backendConnector');
1820
+ _this.waitingReads = [];
1821
+ _this.maxParallelReads = options.maxParallelReads || 10;
1822
+ _this.readingCalls = 0;
1823
+ _this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1824
+ _this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1825
+ _this.state = {};
1826
+ _this.queue = [];
1827
+ if (_this.backend && _this.backend.init) {
1828
+ _this.backend.init(services, options.backend, options);
1829
+ }
1830
+ return _this;
1831
+ }
1832
+ _createClass(Connector, [{
1833
+ key: "queueLoad",
1834
+ value: function queueLoad(languages, namespaces, options, callback) {
1835
+ var _this2 = this;
1836
+ var toLoad = {};
1837
+ var pending = {};
1838
+ var toLoadLanguages = {};
1839
+ var toLoadNamespaces = {};
1840
+ languages.forEach(function (lng) {
1841
+ var hasAllNamespaces = true;
1842
+ namespaces.forEach(function (ns) {
1843
+ var name = "".concat(lng, "|").concat(ns);
1844
+ if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
1845
+ _this2.state[name] = 2;
1846
+ } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
1847
+ if (pending[name] === undefined) pending[name] = true;
1848
+ } else {
1849
+ _this2.state[name] = 1;
1850
+ hasAllNamespaces = false;
1851
+ if (pending[name] === undefined) pending[name] = true;
1852
+ if (toLoad[name] === undefined) toLoad[name] = true;
1853
+ if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1854
+ }
1855
+ });
1856
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1857
+ });
1858
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
1859
+ this.queue.push({
1860
+ pending: pending,
1861
+ pendingCount: Object.keys(pending).length,
1862
+ loaded: {},
1863
+ errors: [],
1864
+ callback: callback
1865
+ });
1866
+ }
1867
+ return {
1868
+ toLoad: Object.keys(toLoad),
1869
+ pending: Object.keys(pending),
1870
+ toLoadLanguages: Object.keys(toLoadLanguages),
1871
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1872
+ };
1873
+ }
1874
+ }, {
1875
+ key: "loaded",
1876
+ value: function loaded(name, err, data) {
1877
+ var s = name.split('|');
1878
+ var lng = s[0];
1879
+ var ns = s[1];
1880
+ if (err) this.emit('failedLoading', lng, ns, err);
1881
+ if (data) {
1882
+ this.store.addResourceBundle(lng, ns, data);
1883
+ }
1884
+ this.state[name] = err ? -1 : 2;
1885
+ var loaded = {};
1886
+ this.queue.forEach(function (q) {
1887
+ pushPath(q.loaded, [lng], ns);
1888
+ removePending(q, name);
1889
+ if (err) q.errors.push(err);
1890
+ if (q.pendingCount === 0 && !q.done) {
1891
+ Object.keys(q.loaded).forEach(function (l) {
1892
+ if (!loaded[l]) loaded[l] = {};
1893
+ var loadedKeys = q.loaded[l];
1894
+ if (loadedKeys.length) {
1895
+ loadedKeys.forEach(function (n) {
1896
+ if (loaded[l][n] === undefined) loaded[l][n] = true;
1897
+ });
1898
+ }
1899
+ });
1900
+ q.done = true;
1901
+ if (q.errors.length) {
1902
+ q.callback(q.errors);
1903
+ } else {
1904
+ q.callback();
1905
+ }
1906
+ }
1907
+ });
1908
+ this.emit('loaded', loaded);
1909
+ this.queue = this.queue.filter(function (q) {
1910
+ return !q.done;
1911
+ });
1912
+ }
1913
+ }, {
1914
+ key: "read",
1915
+ value: function read(lng, ns, fcName) {
1916
+ var _this3 = this;
1917
+ var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1918
+ var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
1919
+ var callback = arguments.length > 5 ? arguments[5] : undefined;
1920
+ if (!lng.length) return callback(null, {});
1921
+ if (this.readingCalls >= this.maxParallelReads) {
1922
+ this.waitingReads.push({
1923
+ lng: lng,
1924
+ ns: ns,
1925
+ fcName: fcName,
1926
+ tried: tried,
1927
+ wait: wait,
1928
+ callback: callback
1929
+ });
1930
+ return;
1931
+ }
1932
+ this.readingCalls++;
1933
+ var resolver = function resolver(err, data) {
1934
+ _this3.readingCalls--;
1935
+ if (_this3.waitingReads.length > 0) {
1936
+ var next = _this3.waitingReads.shift();
1937
+ _this3.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1938
+ }
1939
+ if (err && data && tried < _this3.maxRetries) {
1940
+ setTimeout(function () {
1941
+ _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
1942
+ }, wait);
1943
+ return;
1944
+ }
1945
+ callback(err, data);
1946
+ };
1947
+ var fc = this.backend[fcName].bind(this.backend);
1948
+ if (fc.length === 2) {
1949
+ try {
1950
+ var r = fc(lng, ns);
1951
+ if (r && typeof r.then === 'function') {
1952
+ r.then(function (data) {
1953
+ return resolver(null, data);
1954
+ })["catch"](resolver);
1955
+ } else {
1956
+ resolver(null, r);
1957
+ }
1958
+ } catch (err) {
1959
+ resolver(err);
1960
+ }
1961
+ return;
1962
+ }
1963
+ return fc(lng, ns, resolver);
1964
+ }
1965
+ }, {
1966
+ key: "prepareLoading",
1967
+ value: function prepareLoading(languages, namespaces) {
1968
+ var _this4 = this;
1969
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1970
+ var callback = arguments.length > 3 ? arguments[3] : undefined;
1971
+ if (!this.backend) {
1972
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1973
+ return callback && callback();
1974
+ }
1975
+ if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
1976
+ if (typeof namespaces === 'string') namespaces = [namespaces];
1977
+ var toLoad = this.queueLoad(languages, namespaces, options, callback);
1978
+ if (!toLoad.toLoad.length) {
1979
+ if (!toLoad.pending.length) callback();
1980
+ return null;
1981
+ }
1982
+ toLoad.toLoad.forEach(function (name) {
1983
+ _this4.loadOne(name);
1984
+ });
1985
+ }
1986
+ }, {
1987
+ key: "load",
1988
+ value: function load(languages, namespaces, callback) {
1989
+ this.prepareLoading(languages, namespaces, {}, callback);
1990
+ }
1991
+ }, {
1992
+ key: "reload",
1993
+ value: function reload(languages, namespaces, callback) {
1994
+ this.prepareLoading(languages, namespaces, {
1995
+ reload: true
1996
+ }, callback);
1997
+ }
1998
+ }, {
1999
+ key: "loadOne",
2000
+ value: function loadOne(name) {
2001
+ var _this5 = this;
2002
+ var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2003
+ var s = name.split('|');
2004
+ var lng = s[0];
2005
+ var ns = s[1];
2006
+ this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
2007
+ if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
2008
+ if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
2009
+ _this5.loaded(name, err, data);
2010
+ });
2011
+ }
2012
+ }, {
2013
+ key: "saveMissing",
2014
+ value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
2015
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
2016
+ var clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : function () {};
2017
+ if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
2018
+ this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(namespace, "\" 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!!!');
2019
+ return;
2020
+ }
2021
+ if (key === undefined || key === null || key === '') return;
2022
+ if (this.backend && this.backend.create) {
2023
+ var opts = _objectSpread$1(_objectSpread$1({}, options), {}, {
2024
+ isUpdate: isUpdate
2025
+ });
2026
+ var fc = this.backend.create.bind(this.backend);
2027
+ if (fc.length < 6) {
2028
+ try {
2029
+ var r;
2030
+ if (fc.length === 5) {
2031
+ r = fc(languages, namespace, key, fallbackValue, opts);
2032
+ } else {
2033
+ r = fc(languages, namespace, key, fallbackValue);
2034
+ }
2035
+ if (r && typeof r.then === 'function') {
2036
+ r.then(function (data) {
2037
+ return clb(null, data);
2038
+ })["catch"](clb);
2039
+ } else {
2040
+ clb(null, r);
2041
+ }
2042
+ } catch (err) {
2043
+ clb(err);
2044
+ }
2045
+ } else {
2046
+ fc(languages, namespace, key, fallbackValue, clb, opts);
2047
+ }
2048
+ }
2049
+ if (!languages || !languages[0]) return;
2050
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
2051
+ }
2052
+ }]);
2053
+ return Connector;
2054
+ }(EventEmitter);
2055
+
2056
+ function get() {
2057
+ return {
2058
+ debug: false,
2059
+ initImmediate: true,
2060
+ ns: ['translation'],
2061
+ defaultNS: ['translation'],
2062
+ fallbackLng: ['dev'],
2063
+ fallbackNS: false,
2064
+ supportedLngs: false,
2065
+ nonExplicitSupportedLngs: false,
2066
+ load: 'all',
2067
+ preload: false,
2068
+ simplifyPluralSuffix: true,
2069
+ keySeparator: '.',
2070
+ nsSeparator: ':',
2071
+ pluralSeparator: '_',
2072
+ contextSeparator: '_',
2073
+ partialBundledLanguages: false,
2074
+ saveMissing: false,
2075
+ updateMissing: false,
2076
+ saveMissingTo: 'fallback',
2077
+ saveMissingPlurals: true,
2078
+ missingKeyHandler: false,
2079
+ missingInterpolationHandler: false,
2080
+ postProcess: false,
2081
+ postProcessPassResolved: false,
2082
+ returnNull: true,
2083
+ returnEmptyString: true,
2084
+ returnObjects: false,
2085
+ joinArrays: false,
2086
+ returnedObjectHandler: false,
2087
+ parseMissingKeyHandler: false,
2088
+ appendNamespaceToMissingKey: false,
2089
+ appendNamespaceToCIMode: false,
2090
+ overloadTranslationOptionHandler: function handle(args) {
2091
+ var ret = {};
2092
+ if (_typeof(args[1]) === 'object') ret = args[1];
2093
+ if (typeof args[1] === 'string') ret.defaultValue = args[1];
2094
+ if (typeof args[2] === 'string') ret.tDescription = args[2];
2095
+ if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') {
2096
+ var options = args[3] || args[2];
2097
+ Object.keys(options).forEach(function (key) {
2098
+ ret[key] = options[key];
2099
+ });
2100
+ }
2101
+ return ret;
2102
+ },
2103
+ interpolation: {
2104
+ escapeValue: true,
2105
+ format: function format(value, _format, lng, options) {
2106
+ return value;
2107
+ },
2108
+ prefix: '{{',
2109
+ suffix: '}}',
2110
+ formatSeparator: ',',
2111
+ unescapePrefix: '-',
2112
+ nestingPrefix: '$t(',
2113
+ nestingSuffix: ')',
2114
+ nestingOptionsSeparator: ',',
2115
+ maxReplaces: 1000,
2116
+ skipOnVariables: true
2117
+ }
2118
+ };
2119
+ }
2120
+ function transformOptions(options) {
2121
+ if (typeof options.ns === 'string') options.ns = [options.ns];
2122
+ if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
2123
+ if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
2124
+ if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
2125
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
2126
+ }
2127
+ return options;
2128
+ }
2129
+
2130
+ function ownKeys$7(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; }
2131
+ function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2132
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); 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); }; }
2133
+ function _isNativeReflectConstruct() { 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; } }
2134
+ function noop() {}
2135
+ function bindMemberFunctions(inst) {
2136
+ var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
2137
+ mems.forEach(function (mem) {
2138
+ if (typeof inst[mem] === 'function') {
2139
+ inst[mem] = inst[mem].bind(inst);
2140
+ }
2141
+ });
2142
+ }
2143
+ var I18n = function (_EventEmitter) {
2144
+ _inherits(I18n, _EventEmitter);
2145
+ var _super = _createSuper(I18n);
2146
+ function I18n() {
2147
+ var _this;
2148
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2149
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
2150
+ _classCallCheck(this, I18n);
2151
+ _this = _super.call(this);
2152
+ if (isIE10) {
2153
+ EventEmitter.call(_assertThisInitialized(_this));
2154
+ }
2155
+ _this.options = transformOptions(options);
2156
+ _this.services = {};
2157
+ _this.logger = baseLogger;
2158
+ _this.modules = {
2159
+ external: []
2160
+ };
2161
+ bindMemberFunctions(_assertThisInitialized(_this));
2162
+ if (callback && !_this.isInitialized && !options.isClone) {
2163
+ if (!_this.options.initImmediate) {
2164
+ _this.init(options, callback);
2165
+ return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
2166
+ }
2167
+ setTimeout(function () {
2168
+ _this.init(options, callback);
2169
+ }, 0);
2170
+ }
2171
+ return _this;
2172
+ }
2173
+ _createClass(I18n, [{
2174
+ key: "init",
2175
+ value: function init() {
2176
+ var _this2 = this;
2177
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2178
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
2179
+ if (typeof options === 'function') {
2180
+ callback = options;
2181
+ options = {};
2182
+ }
2183
+ if (!options.defaultNS && options.defaultNS !== false && options.ns) {
2184
+ if (typeof options.ns === 'string') {
2185
+ options.defaultNS = options.ns;
2186
+ } else if (options.ns.indexOf('translation') < 0) {
2187
+ options.defaultNS = options.ns[0];
2188
+ }
2189
+ }
2190
+ var defOpts = get();
2191
+ this.options = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, defOpts), this.options), transformOptions(options));
2192
+ if (this.options.compatibilityAPI !== 'v1') {
2193
+ this.options.interpolation = _objectSpread$7(_objectSpread$7({}, defOpts.interpolation), this.options.interpolation);
2194
+ }
2195
+ if (options.keySeparator !== undefined) {
2196
+ this.options.userDefinedKeySeparator = options.keySeparator;
2197
+ }
2198
+ if (options.nsSeparator !== undefined) {
2199
+ this.options.userDefinedNsSeparator = options.nsSeparator;
2200
+ }
2201
+ function createClassOnDemand(ClassOrObject) {
2202
+ if (!ClassOrObject) return null;
2203
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
2204
+ return ClassOrObject;
2205
+ }
2206
+ if (!this.options.isClone) {
2207
+ if (this.modules.logger) {
2208
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2209
+ } else {
2210
+ baseLogger.init(null, this.options);
2211
+ }
2212
+ var formatter;
2213
+ if (this.modules.formatter) {
2214
+ formatter = this.modules.formatter;
2215
+ } else if (typeof Intl !== 'undefined') {
2216
+ formatter = Formatter;
2217
+ }
2218
+ var lu = new LanguageUtil(this.options);
2219
+ this.store = new ResourceStore(this.options.resources, this.options);
2220
+ var s = this.services;
2221
+ s.logger = baseLogger;
2222
+ s.resourceStore = this.store;
2223
+ s.languageUtils = lu;
2224
+ s.pluralResolver = new PluralResolver(lu, {
2225
+ prepend: this.options.pluralSeparator,
2226
+ compatibilityJSON: this.options.compatibilityJSON,
2227
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
2228
+ });
2229
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2230
+ s.formatter = createClassOnDemand(formatter);
2231
+ s.formatter.init(s, this.options);
2232
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2233
+ }
2234
+ s.interpolator = new Interpolator(this.options);
2235
+ s.utils = {
2236
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2237
+ };
2238
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2239
+ s.backendConnector.on('*', function (event) {
2240
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2241
+ args[_key - 1] = arguments[_key];
2242
+ }
2243
+ _this2.emit.apply(_this2, [event].concat(args));
2244
+ });
2245
+ if (this.modules.languageDetector) {
2246
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2247
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2248
+ }
2249
+ if (this.modules.i18nFormat) {
2250
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2251
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
2252
+ }
2253
+ this.translator = new Translator(this.services, this.options);
2254
+ this.translator.on('*', function (event) {
2255
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2256
+ args[_key2 - 1] = arguments[_key2];
2257
+ }
2258
+ _this2.emit.apply(_this2, [event].concat(args));
2259
+ });
2260
+ this.modules.external.forEach(function (m) {
2261
+ if (m.init) m.init(_this2);
2262
+ });
2263
+ }
2264
+ this.format = this.options.interpolation.format;
2265
+ if (!callback) callback = noop;
2266
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2267
+ var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2268
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2269
+ }
2270
+ if (!this.services.languageDetector && !this.options.lng) {
2271
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
2272
+ }
2273
+ var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2274
+ storeApi.forEach(function (fcName) {
2275
+ _this2[fcName] = function () {
2276
+ var _this2$store;
2277
+ return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
2278
+ };
2279
+ });
2280
+ var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2281
+ storeApiChained.forEach(function (fcName) {
2282
+ _this2[fcName] = function () {
2283
+ var _this2$store2;
2284
+ (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
2285
+ return _this2;
2286
+ };
2287
+ });
2288
+ var deferred = defer();
2289
+ var load = function load() {
2290
+ var finish = function finish(err, t) {
2291
+ if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
2292
+ _this2.isInitialized = true;
2293
+ if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
2294
+ _this2.emit('initialized', _this2.options);
2295
+ deferred.resolve(t);
2296
+ callback(err, t);
2297
+ };
2298
+ if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
2299
+ _this2.changeLanguage(_this2.options.lng, finish);
2300
+ };
2301
+ if (this.options.resources || !this.options.initImmediate) {
2302
+ load();
2303
+ } else {
2304
+ setTimeout(load, 0);
2305
+ }
2306
+ return deferred;
2307
+ }
2308
+ }, {
2309
+ key: "loadResources",
2310
+ value: function loadResources(language) {
2311
+ var _this3 = this;
2312
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2313
+ var usedCallback = callback;
2314
+ var usedLng = typeof language === 'string' ? language : this.language;
2315
+ if (typeof language === 'function') usedCallback = language;
2316
+ if (!this.options.resources || this.options.partialBundledLanguages) {
2317
+ if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
2318
+ var toLoad = [];
2319
+ var append = function append(lng) {
2320
+ if (!lng) return;
2321
+ var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
2322
+ lngs.forEach(function (l) {
2323
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
2324
+ });
2325
+ };
2326
+ if (!usedLng) {
2327
+ var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2328
+ fallbacks.forEach(function (l) {
2329
+ return append(l);
2330
+ });
2331
+ } else {
2332
+ append(usedLng);
2333
+ }
2334
+ if (this.options.preload) {
2335
+ this.options.preload.forEach(function (l) {
2336
+ return append(l);
2337
+ });
2338
+ }
2339
+ this.services.backendConnector.load(toLoad, this.options.ns, function (e) {
2340
+ if (!e && !_this3.resolvedLanguage && _this3.language) _this3.setResolvedLanguage(_this3.language);
2341
+ usedCallback(e);
2342
+ });
2343
+ } else {
2344
+ usedCallback(null);
2345
+ }
2346
+ }
2347
+ }, {
2348
+ key: "reloadResources",
2349
+ value: function reloadResources(lngs, ns, callback) {
2350
+ var deferred = defer();
2351
+ if (!lngs) lngs = this.languages;
2352
+ if (!ns) ns = this.options.ns;
2353
+ if (!callback) callback = noop;
2354
+ this.services.backendConnector.reload(lngs, ns, function (err) {
2355
+ deferred.resolve();
2356
+ callback(err);
2357
+ });
2358
+ return deferred;
2359
+ }
2360
+ }, {
2361
+ key: "use",
2362
+ value: function use(module) {
2363
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2364
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2365
+ if (module.type === 'backend') {
2366
+ this.modules.backend = module;
2367
+ }
2368
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
2369
+ this.modules.logger = module;
2370
+ }
2371
+ if (module.type === 'languageDetector') {
2372
+ this.modules.languageDetector = module;
2373
+ }
2374
+ if (module.type === 'i18nFormat') {
2375
+ this.modules.i18nFormat = module;
2376
+ }
2377
+ if (module.type === 'postProcessor') {
2378
+ postProcessor.addPostProcessor(module);
2379
+ }
2380
+ if (module.type === 'formatter') {
2381
+ this.modules.formatter = module;
2382
+ }
2383
+ if (module.type === '3rdParty') {
2384
+ this.modules.external.push(module);
2385
+ }
2386
+ return this;
2387
+ }
2388
+ }, {
2389
+ key: "setResolvedLanguage",
2390
+ value: function setResolvedLanguage(l) {
2391
+ if (!l || !this.languages) return;
2392
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
2393
+ for (var li = 0; li < this.languages.length; li++) {
2394
+ var lngInLngs = this.languages[li];
2395
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2396
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2397
+ this.resolvedLanguage = lngInLngs;
2398
+ break;
2399
+ }
2400
+ }
2401
+ }
2402
+ }, {
2403
+ key: "changeLanguage",
2404
+ value: function changeLanguage(lng, callback) {
2405
+ var _this4 = this;
2406
+ this.isLanguageChangingTo = lng;
2407
+ var deferred = defer();
2408
+ this.emit('languageChanging', lng);
2409
+ var setLngProps = function setLngProps(l) {
2410
+ _this4.language = l;
2411
+ _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
2412
+ _this4.resolvedLanguage = undefined;
2413
+ _this4.setResolvedLanguage(l);
2414
+ };
2415
+ var done = function done(err, l) {
2416
+ if (l) {
2417
+ setLngProps(l);
2418
+ _this4.translator.changeLanguage(l);
2419
+ _this4.isLanguageChangingTo = undefined;
2420
+ _this4.emit('languageChanged', l);
2421
+ _this4.logger.log('languageChanged', l);
2422
+ } else {
2423
+ _this4.isLanguageChangingTo = undefined;
2424
+ }
2425
+ deferred.resolve(function () {
2426
+ return _this4.t.apply(_this4, arguments);
2427
+ });
2428
+ if (callback) callback(err, function () {
2429
+ return _this4.t.apply(_this4, arguments);
2430
+ });
2431
+ };
2432
+ var setLng = function setLng(lngs) {
2433
+ if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
2434
+ var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
2435
+ if (l) {
2436
+ if (!_this4.language) {
2437
+ setLngProps(l);
2438
+ }
2439
+ if (!_this4.translator.language) _this4.translator.changeLanguage(l);
2440
+ if (_this4.services.languageDetector && _this4.services.languageDetector.cacheUserLanguage) _this4.services.languageDetector.cacheUserLanguage(l);
2441
+ }
2442
+ _this4.loadResources(l, function (err) {
2443
+ done(err, l);
2444
+ });
2445
+ };
2446
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2447
+ setLng(this.services.languageDetector.detect());
2448
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2449
+ if (this.services.languageDetector.detect.length === 0) {
2450
+ this.services.languageDetector.detect().then(setLng);
2451
+ } else {
2452
+ this.services.languageDetector.detect(setLng);
2453
+ }
2454
+ } else {
2455
+ setLng(lng);
2456
+ }
2457
+ return deferred;
2458
+ }
2459
+ }, {
2460
+ key: "getFixedT",
2461
+ value: function getFixedT(lng, ns, keyPrefix) {
2462
+ var _this5 = this;
2463
+ var fixedT = function fixedT(key, opts) {
2464
+ var options;
2465
+ if (_typeof(opts) !== 'object') {
2466
+ for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2467
+ rest[_key3 - 2] = arguments[_key3];
2468
+ }
2469
+ options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2470
+ } else {
2471
+ options = _objectSpread$7({}, opts);
2472
+ }
2473
+ options.lng = options.lng || fixedT.lng;
2474
+ options.lngs = options.lngs || fixedT.lngs;
2475
+ options.ns = options.ns || fixedT.ns;
2476
+ options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2477
+ var keySeparator = _this5.options.keySeparator || '.';
2478
+ var resultKey;
2479
+ if (options.keyPrefix && Array.isArray(key)) {
2480
+ resultKey = key.map(function (k) {
2481
+ return "".concat(options.keyPrefix).concat(keySeparator).concat(k);
2482
+ });
2483
+ } else {
2484
+ resultKey = options.keyPrefix ? "".concat(options.keyPrefix).concat(keySeparator).concat(key) : key;
2485
+ }
2486
+ return _this5.t(resultKey, options);
2487
+ };
2488
+ if (typeof lng === 'string') {
2489
+ fixedT.lng = lng;
2490
+ } else {
2491
+ fixedT.lngs = lng;
2492
+ }
2493
+ fixedT.ns = ns;
2494
+ fixedT.keyPrefix = keyPrefix;
2495
+ return fixedT;
2496
+ }
2497
+ }, {
2498
+ key: "t",
2499
+ value: function t() {
2500
+ var _this$translator;
2501
+ return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
2502
+ }
2503
+ }, {
2504
+ key: "exists",
2505
+ value: function exists() {
2506
+ var _this$translator2;
2507
+ return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
2508
+ }
2509
+ }, {
2510
+ key: "setDefaultNamespace",
2511
+ value: function setDefaultNamespace(ns) {
2512
+ this.options.defaultNS = ns;
2513
+ }
2514
+ }, {
2515
+ key: "hasLoadedNamespace",
2516
+ value: function hasLoadedNamespace(ns) {
2517
+ var _this6 = this;
2518
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2519
+ if (!this.isInitialized) {
2520
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2521
+ return false;
2522
+ }
2523
+ if (!this.languages || !this.languages.length) {
2524
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2525
+ return false;
2526
+ }
2527
+ var lng = options.lng || this.resolvedLanguage || this.languages[0];
2528
+ var fallbackLng = this.options ? this.options.fallbackLng : false;
2529
+ var lastLng = this.languages[this.languages.length - 1];
2530
+ if (lng.toLowerCase() === 'cimode') return true;
2531
+ var loadNotPending = function loadNotPending(l, n) {
2532
+ var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
2533
+ return loadState === -1 || loadState === 2;
2534
+ };
2535
+ if (options.precheck) {
2536
+ var preResult = options.precheck(this, loadNotPending);
2537
+ if (preResult !== undefined) return preResult;
2538
+ }
2539
+ if (this.hasResourceBundle(lng, ns)) return true;
2540
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2541
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2542
+ return false;
2543
+ }
2544
+ }, {
2545
+ key: "loadNamespaces",
2546
+ value: function loadNamespaces(ns, callback) {
2547
+ var _this7 = this;
2548
+ var deferred = defer();
2549
+ if (!this.options.ns) {
2550
+ if (callback) callback();
2551
+ return Promise.resolve();
2552
+ }
2553
+ if (typeof ns === 'string') ns = [ns];
2554
+ ns.forEach(function (n) {
2555
+ if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
2556
+ });
2557
+ this.loadResources(function (err) {
2558
+ deferred.resolve();
2559
+ if (callback) callback(err);
2560
+ });
2561
+ return deferred;
2562
+ }
2563
+ }, {
2564
+ key: "loadLanguages",
2565
+ value: function loadLanguages(lngs, callback) {
2566
+ var deferred = defer();
2567
+ if (typeof lngs === 'string') lngs = [lngs];
2568
+ var preloaded = this.options.preload || [];
2569
+ var newLngs = lngs.filter(function (lng) {
2570
+ return preloaded.indexOf(lng) < 0;
2571
+ });
2572
+ if (!newLngs.length) {
2573
+ if (callback) callback();
2574
+ return Promise.resolve();
2575
+ }
2576
+ this.options.preload = preloaded.concat(newLngs);
2577
+ this.loadResources(function (err) {
2578
+ deferred.resolve();
2579
+ if (callback) callback(err);
2580
+ });
2581
+ return deferred;
2582
+ }
2583
+ }, {
2584
+ key: "dir",
2585
+ value: function dir(lng) {
2586
+ if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
2587
+ if (!lng) return 'rtl';
2588
+ var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
2589
+ var languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
2590
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2591
+ }
2592
+ }, {
2593
+ key: "cloneInstance",
2594
+ value: function cloneInstance() {
2595
+ var _this8 = this;
2596
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2597
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2598
+ var mergedOptions = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, this.options), options), {
2599
+ isClone: true
2600
+ });
2601
+ var clone = new I18n(mergedOptions);
2602
+ if (options.debug !== undefined || options.prefix !== undefined) {
2603
+ clone.logger = clone.logger.clone(options);
2604
+ }
2605
+ var membersToCopy = ['store', 'services', 'language'];
2606
+ membersToCopy.forEach(function (m) {
2607
+ clone[m] = _this8[m];
2608
+ });
2609
+ clone.services = _objectSpread$7({}, this.services);
2610
+ clone.services.utils = {
2611
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2612
+ };
2613
+ clone.translator = new Translator(clone.services, clone.options);
2614
+ clone.translator.on('*', function (event) {
2615
+ for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
2616
+ args[_key4 - 1] = arguments[_key4];
2617
+ }
2618
+ clone.emit.apply(clone, [event].concat(args));
2619
+ });
2620
+ clone.init(mergedOptions, callback);
2621
+ clone.translator.options = clone.options;
2622
+ clone.translator.backendConnector.services.utils = {
2623
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2624
+ };
2625
+ return clone;
2626
+ }
2627
+ }, {
2628
+ key: "toJSON",
2629
+ value: function toJSON() {
2630
+ return {
2631
+ options: this.options,
2632
+ store: this.store,
2633
+ language: this.language,
2634
+ languages: this.languages,
2635
+ resolvedLanguage: this.resolvedLanguage
2636
+ };
2637
+ }
2638
+ }]);
2639
+ return I18n;
2640
+ }(EventEmitter);
2641
+ _defineProperty(I18n, "createInstance", function () {
2642
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2643
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
2644
+ return new I18n(options, callback);
2645
+ });
2646
+ var instance = I18n.createInstance();
2647
+ instance.createInstance = I18n.createInstance;
2648
+
2649
+ instance.createInstance;
2650
+ instance.dir;
2651
+ instance.init;
2652
+ instance.loadResources;
2653
+ instance.reloadResources;
2654
+ instance.use;
2655
+ instance.changeLanguage;
2656
+ instance.getFixedT;
2657
+ instance.t;
2658
+ instance.exists;
2659
+ instance.setDefaultNamespace;
2660
+ instance.hasLoadedNamespace;
2661
+ instance.loadNamespaces;
2662
+ instance.loadLanguages;
2663
+
2664
+ var en = {
2665
+ translation: {
2666
+ categorize: {
2667
+ limitMaxChoicesPerCategory: "You've reached the limit of {{maxChoicesPerCategory}} responses per area. To add another response, one must first be removed.",
2668
+ maxChoicesPerCategoryRestriction: 'To change this value to {{maxChoicesPerCategory}}, each category must have {{maxChoicesPerCategory}} or fewer answer choice[s].'
2669
+ },
2670
+ ebsr: {
2671
+ part: 'Part {{index}}'
2672
+ },
2673
+ numberLine: {
2674
+ addElementLimit_one: 'You can only add {{count}} element',
2675
+ addElementLimit_other: 'You can only add {{count}} elements',
2676
+ clearAll: 'Clear all'
2677
+ },
2678
+ imageClozeAssociation: {
2679
+ reachedLimit_one: 'You’ve reached the limit of {{count}} response per area. To add another response, one must first be removed.',
2680
+ reachedLimit_other: 'Full'
2681
+ },
2682
+ drawingResponse: {
2683
+ fillColor: 'Fill color',
2684
+ outlineColor: 'Outline color',
2685
+ noFill: 'No fill',
2686
+ lightblue: 'Light blue',
2687
+ lightyellow: 'Light yellow',
2688
+ red: 'Red',
2689
+ orange: 'Orange',
2690
+ yellow: 'Yellow',
2691
+ violet: 'Violet',
2692
+ blue: 'Blue',
2693
+ green: 'Green',
2694
+ white: 'White',
2695
+ black: 'Black',
2696
+ onDoubleClick: 'Double click to edit this text. Press Enter to submit.'
2697
+ },
2698
+ charting: {
2699
+ addCategory: 'Add category',
2700
+ actions: 'Actions',
2701
+ add: 'Add',
2702
+ delete: 'Delete',
2703
+ newLabel: 'New label',
2704
+ reachedLimit_other: "There can't be more than {{count}} categories.",
2705
+ keyLegend: {
2706
+ incorrectAnswer: 'Student incorrect answer',
2707
+ correctAnswer: 'Student correct answer',
2708
+ correctKeyAnswer: 'Answer key correct'
2709
+ }
2710
+ },
2711
+ graphing: {
2712
+ point: 'Point',
2713
+ circle: 'Circle',
2714
+ line: 'Line',
2715
+ parabola: 'Parabola',
2716
+ absolute: 'Absolute Value',
2717
+ exponential: 'Exponential',
2718
+ polygon: 'Polygon',
2719
+ ray: 'Ray',
2720
+ segment: 'Segment',
2721
+ sine: 'Sine',
2722
+ vector: 'Vector',
2723
+ label: 'Label',
2724
+ redo: 'Redo',
2725
+ reset: 'Reset'
2726
+ },
2727
+ mathInline: {
2728
+ primaryCorrectWithAlternates: 'Note: The answer shown above is the primary correct answer specified by the author for this item, but other answers may also be recognized as correct.'
2729
+ },
2730
+ multipleChoice: {
2731
+ minSelections: 'Select at least {{minSelections}}.',
2732
+ maxSelections_one: 'Only {{maxSelections}} answer is allowed.',
2733
+ maxSelections_other: 'Only {{maxSelections}} answers are allowed.',
2734
+ minmaxSelections_equal: 'Select {{minSelections}}.',
2735
+ minmaxSelections_range: 'Select between {{minSelections}} and {{maxSelections}}.'
2736
+ },
2737
+ selectText: {
2738
+ correctAnswerSelected: 'Correct',
2739
+ correctAnswerNotSelected: 'Correct Answer Not Selected',
2740
+ incorrectSelection: 'Incorrect Selection',
2741
+ key: 'Key'
2742
+ }
2743
+ },
2744
+ common: {
2745
+ undo: 'Undo',
2746
+ clearAll: 'Clear all',
2747
+ correct: 'Correct',
2748
+ incorrect: 'Incorrect',
2749
+ showCorrectAnswer: 'Show correct answer',
2750
+ hideCorrectAnswer: 'Hide correct answer',
2751
+ commonCorrectAnswerWithAlternates: 'Note: The answer shown above is the most common correct answer for this item. One or more additional correct answers are also defined, and will also be recognized as correct.',
2752
+ warning: 'Warning',
2753
+ showNote: 'Show Note',
2754
+ hideNote: 'Hide Note',
2755
+ cancel: 'Cancel'
2756
+ }
2757
+ };
2758
+
2759
+ var es = {
2760
+ translation: {
2761
+ categorize: {
2762
+ limitMaxChoicesPerCategory: 'Has alcanzado el límite de {{maxChoicesPerCategory}} respuestas por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
2763
+ maxChoicesPerCategoryRestriction: 'Para cambiar este valor a {{maxChoicesPerCategory}}, cada categoría debe tener {{maxChoicesPerCategory}} o menos opciones de respuesta'
2764
+ },
2765
+ ebsr: {
2766
+ part: 'Parte {{index}}'
2767
+ },
2768
+ numberLine: {
2769
+ addElementLimit_one: 'Solo puedes agregar {{count}} elemento',
2770
+ addElementLimit_other: 'Solo puedes agregar {{count}} elementos',
2771
+ clearAll: 'Borrar todo'
2772
+ },
2773
+ imageClozeAssociation: {
2774
+ reachedLimit_one: 'Has alcanzado el límite de {{count}} respuesta por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
2775
+ reachedLimit_other: 'Lleno'
2776
+ },
2777
+ drawingResponse: {
2778
+ fillColor: 'Color de relleno',
2779
+ outlineColor: 'Color del contorno',
2780
+ noFill: 'Sin relleno',
2781
+ lightblue: 'Azul claro',
2782
+ lightyellow: 'Amarillo claro',
2783
+ red: 'Rojo',
2784
+ orange: 'Naranja',
2785
+ yellow: 'Amarillo',
2786
+ violet: 'Violeta',
2787
+ blue: 'Azul',
2788
+ green: 'Verde',
2789
+ white: 'Blanco',
2790
+ black: 'Negro',
2791
+ onDoubleClick: 'Haz doble clic para revisar este texto. Presiona el botón de ingreso para enviar'
2792
+ },
2793
+ charting: {
2794
+ addCategory: 'Añadir categoría',
2795
+ actions: 'Acciones',
2796
+ add: 'Añadir',
2797
+ delete: 'Eliminar',
2798
+ newLabel: 'Nueva etiqueta',
2799
+ reachedLimit_other: 'No puede haber más de {{count}} categorías.',
2800
+ keyLegend: {
2801
+ incorrectAnswer: 'Respuesta incorrecta del estudiante',
2802
+ correctAnswer: 'Respuesta correcta del estudiante',
2803
+ correctKeyAnswer: 'Clave de respuesta correcta'
2804
+ }
2805
+ },
2806
+ graphing: {
2807
+ point: 'Punto',
2808
+ circle: 'Circulo',
2809
+ line: 'Línea',
2810
+ parabola: 'Parábola',
2811
+ absolute: 'Valor absoluto',
2812
+ exponential: 'Exponencial',
2813
+ polygon: 'Polígono',
2814
+ ray: 'Semirrecta',
2815
+ segment: 'Segmento ',
2816
+ sine: 'Seno',
2817
+ vector: 'Vector',
2818
+ label: 'Etiqueta',
2819
+ redo: 'Rehacer',
2820
+ reset: 'Reiniciar'
2821
+ },
2822
+ mathInline: {
2823
+ primaryCorrectWithAlternates: 'Nota: La respuesta que se muestra arriba es la respuesta correcta principal especificada por el autor para esta pregunta, pero también se pueden reconocer otras respuestas como correctas.'
2824
+ },
2825
+ multipleChoice: {
2826
+ minSelections: 'Seleccione al menos {{minSelections}}.',
2827
+ maxSelections_one: 'Sólo se permite {{maxSelections}} respuesta.',
2828
+ maxSelections_other: 'Sólo se permiten {{maxSelections}} respuestas.',
2829
+ minmaxSelections_equal: 'Seleccione {{minSelections}}.',
2830
+ minmaxSelections_range: 'Seleccione entre {{minSelections}} y {{maxSelections}}.'
2831
+ },
2832
+ selectText: {
2833
+ correctAnswerSelected: 'Respuesta Correcta',
2834
+ correctAnswerNotSelected: 'Respuesta Correcta No Seleccionada',
2835
+ incorrectSelection: 'Selección Incorrecta',
2836
+ key: 'Clave'
2837
+ }
2838
+ },
2839
+ common: {
2840
+ undo: 'Deshacer',
2841
+ clearAll: 'Borrar todo',
2842
+ correct: 'Correct',
2843
+ incorrect: 'Incorrect',
2844
+ showCorrectAnswer: 'Mostrar respuesta correcta',
2845
+ hideCorrectAnswer: 'Ocultar respuesta correcta',
2846
+ commonCorrectAnswerWithAlternates: 'Nota: La respuesta que se muestra arriba es la respuesta correcta más común para esta pregunta. También se definen una o más respuestas correctas adicionales, y también se reconocerán como correctas.',
2847
+ warning: 'Advertencia',
2848
+ showNote: 'Mostrar Nota',
2849
+ hideNote: 'Ocultar Nota',
2850
+ cancel: 'Cancelar'
2851
+ }
2852
+ };
2853
+
2854
+ function ownKeys(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; }
2855
+
2856
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2857
+ instance.init({
2858
+ fallbackLng: 'en',
2859
+ lng: 'en',
2860
+ debug: true,
2861
+ resources: {
2862
+ en: en,
2863
+ es: es
2864
+ }
2865
+ });
2866
+ var index = {
2867
+ translator: _objectSpread(_objectSpread({}, instance), {}, {
2868
+ t: (key, options) => {
2869
+ var {
2870
+ lng
2871
+ } = options;
2872
+
2873
+ switch (lng) {
2874
+ // these keys don't work with plurals, don't know why, so I added a workaround to convert them to the correct lng
2875
+ case 'en_US':
2876
+ case 'en-US':
2877
+ options.lng = 'en';
2878
+ break;
2879
+
2880
+ case 'es_ES':
2881
+ case 'es-ES':
2882
+ case 'es_MX':
2883
+ case 'es-MX':
2884
+ options.lng = 'es';
2885
+ break;
2886
+ }
2887
+
2888
+ return instance.t(key, _objectSpread({
2889
+ lng
2890
+ }, options));
2891
+ }
2892
+ }),
2893
+ languageOptions: [{
2894
+ value: 'en_US',
2895
+ label: 'English (US)'
2896
+ }, {
2897
+ value: 'es_ES',
2898
+ label: 'Spanish'
2899
+ }]
2900
+ };
2901
+
2902
+ export { index as default };
2903
+ //# sourceMappingURL=index.js.map