@thanh01.pmt/interactive-quiz-kit 1.0.89 → 1.1.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/dist/i18n.cjs CHANGED
@@ -2,2385 +2,16 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var i18n = require('i18next');
5
6
  var reactI18next = require('react-i18next');
6
7
  var LanguageDetector = require('i18next-browser-languagedetector');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
11
+ var i18n__default = /*#__PURE__*/_interopDefault(i18n);
10
12
  var LanguageDetector__default = /*#__PURE__*/_interopDefault(LanguageDetector);
11
13
 
12
- // ../../node_modules/.pnpm/i18next@23.16.8/node_modules/i18next/dist/esm/i18next.js
13
- var isString = (obj) => typeof obj === "string";
14
- var defer = () => {
15
- let res;
16
- let rej;
17
- const promise = new Promise((resolve, reject) => {
18
- res = resolve;
19
- rej = reject;
20
- });
21
- promise.resolve = res;
22
- promise.reject = rej;
23
- return promise;
24
- };
25
- var makeString = (object) => {
26
- if (object == null) return "";
27
- return "" + object;
28
- };
29
- var copy = (a, s, t2) => {
30
- a.forEach((m) => {
31
- if (s[m]) t2[m] = s[m];
32
- });
33
- };
34
- var lastOfPathSeparatorRegExp = /###/g;
35
- var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
36
- var canNotTraverseDeeper = (object) => !object || isString(object);
37
- var getLastOfPath = (object, path, Empty) => {
38
- const stack = !isString(path) ? path : path.split(".");
39
- let stackIndex = 0;
40
- while (stackIndex < stack.length - 1) {
41
- if (canNotTraverseDeeper(object)) return {};
42
- const key = cleanKey(stack[stackIndex]);
43
- if (!object[key] && Empty) object[key] = new Empty();
44
- if (Object.prototype.hasOwnProperty.call(object, key)) {
45
- object = object[key];
46
- } else {
47
- object = {};
48
- }
49
- ++stackIndex;
50
- }
51
- if (canNotTraverseDeeper(object)) return {};
52
- return {
53
- obj: object,
54
- k: cleanKey(stack[stackIndex])
55
- };
56
- };
57
- var setPath = (object, path, newValue) => {
58
- const {
59
- obj,
60
- k
61
- } = getLastOfPath(object, path, Object);
62
- if (obj !== void 0 || path.length === 1) {
63
- obj[k] = newValue;
64
- return;
65
- }
66
- let e = path[path.length - 1];
67
- let p = path.slice(0, path.length - 1);
68
- let last = getLastOfPath(object, p, Object);
69
- while (last.obj === void 0 && p.length) {
70
- e = `${p[p.length - 1]}.${e}`;
71
- p = p.slice(0, p.length - 1);
72
- last = getLastOfPath(object, p, Object);
73
- if (last && last.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
74
- last.obj = void 0;
75
- }
76
- }
77
- last.obj[`${last.k}.${e}`] = newValue;
78
- };
79
- var pushPath = (object, path, newValue, concat) => {
80
- const {
81
- obj,
82
- k
83
- } = getLastOfPath(object, path, Object);
84
- obj[k] = obj[k] || [];
85
- obj[k].push(newValue);
86
- };
87
- var getPath = (object, path) => {
88
- const {
89
- obj,
90
- k
91
- } = getLastOfPath(object, path);
92
- if (!obj) return void 0;
93
- return obj[k];
94
- };
95
- var getPathWithDefaults = (data, defaultData, key) => {
96
- const value = getPath(data, key);
97
- if (value !== void 0) {
98
- return value;
99
- }
100
- return getPath(defaultData, key);
101
- };
102
- var deepExtend = (target, source, overwrite) => {
103
- for (const prop in source) {
104
- if (prop !== "__proto__" && prop !== "constructor") {
105
- if (prop in target) {
106
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
107
- if (overwrite) target[prop] = source[prop];
108
- } else {
109
- deepExtend(target[prop], source[prop], overwrite);
110
- }
111
- } else {
112
- target[prop] = source[prop];
113
- }
114
- }
115
- }
116
- return target;
117
- };
118
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
119
- var _entityMap = {
120
- "&": "&amp;",
121
- "<": "&lt;",
122
- ">": "&gt;",
123
- '"': "&quot;",
124
- "'": "&#39;",
125
- "/": "&#x2F;"
126
- };
127
- var escape = (data) => {
128
- if (isString(data)) {
129
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
130
- }
131
- return data;
132
- };
133
- var RegExpCache = class {
134
- constructor(capacity) {
135
- this.capacity = capacity;
136
- this.regExpMap = /* @__PURE__ */ new Map();
137
- this.regExpQueue = [];
138
- }
139
- getRegExp(pattern) {
140
- const regExpFromCache = this.regExpMap.get(pattern);
141
- if (regExpFromCache !== void 0) {
142
- return regExpFromCache;
143
- }
144
- const regExpNew = new RegExp(pattern);
145
- if (this.regExpQueue.length === this.capacity) {
146
- this.regExpMap.delete(this.regExpQueue.shift());
147
- }
148
- this.regExpMap.set(pattern, regExpNew);
149
- this.regExpQueue.push(pattern);
150
- return regExpNew;
151
- }
152
- };
153
- var chars = [" ", ",", "?", "!", ";"];
154
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
155
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
156
- nsSeparator = nsSeparator || "";
157
- keySeparator = keySeparator || "";
158
- const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
159
- if (possibleChars.length === 0) return true;
160
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
161
- let matched = !r.test(key);
162
- if (!matched) {
163
- const ki = key.indexOf(keySeparator);
164
- if (ki > 0 && !r.test(key.substring(0, ki))) {
165
- matched = true;
166
- }
167
- }
168
- return matched;
169
- };
170
- var deepFind = function(obj, path) {
171
- let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
172
- if (!obj) return void 0;
173
- if (obj[path]) return obj[path];
174
- const tokens = path.split(keySeparator);
175
- let current = obj;
176
- for (let i = 0; i < tokens.length; ) {
177
- if (!current || typeof current !== "object") {
178
- return void 0;
179
- }
180
- let next;
181
- let nextPath = "";
182
- for (let j = i; j < tokens.length; ++j) {
183
- if (j !== i) {
184
- nextPath += keySeparator;
185
- }
186
- nextPath += tokens[j];
187
- next = current[nextPath];
188
- if (next !== void 0) {
189
- if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
190
- continue;
191
- }
192
- i += j - i + 1;
193
- break;
194
- }
195
- }
196
- current = next;
197
- }
198
- return current;
199
- };
200
- var getCleanedCode = (code) => code && code.replace("_", "-");
201
- var consoleLogger = {
202
- type: "logger",
203
- log(args) {
204
- this.output("log", args);
205
- },
206
- warn(args) {
207
- this.output("warn", args);
208
- },
209
- error(args) {
210
- this.output("error", args);
211
- },
212
- output(type, args) {
213
- if (console && console[type]) console[type].apply(console, args);
214
- }
215
- };
216
- var Logger = class _Logger {
217
- constructor(concreteLogger) {
218
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
219
- this.init(concreteLogger, options);
220
- }
221
- init(concreteLogger) {
222
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
223
- this.prefix = options.prefix || "i18next:";
224
- this.logger = concreteLogger || consoleLogger;
225
- this.options = options;
226
- this.debug = options.debug;
227
- }
228
- log() {
229
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
230
- args[_key] = arguments[_key];
231
- }
232
- return this.forward(args, "log", "", true);
233
- }
234
- warn() {
235
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
236
- args[_key2] = arguments[_key2];
237
- }
238
- return this.forward(args, "warn", "", true);
239
- }
240
- error() {
241
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
242
- args[_key3] = arguments[_key3];
243
- }
244
- return this.forward(args, "error", "");
245
- }
246
- deprecate() {
247
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
248
- args[_key4] = arguments[_key4];
249
- }
250
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
251
- }
252
- forward(args, lvl, prefix, debugOnly) {
253
- if (debugOnly && !this.debug) return null;
254
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
255
- return this.logger[lvl](args);
256
- }
257
- create(moduleName) {
258
- return new _Logger(this.logger, {
259
- ...{
260
- prefix: `${this.prefix}:${moduleName}:`
261
- },
262
- ...this.options
263
- });
264
- }
265
- clone(options) {
266
- options = options || this.options;
267
- options.prefix = options.prefix || this.prefix;
268
- return new _Logger(this.logger, options);
269
- }
270
- };
271
- var baseLogger = new Logger();
272
- var EventEmitter = class {
273
- constructor() {
274
- this.observers = {};
275
- }
276
- on(events, listener) {
277
- events.split(" ").forEach((event) => {
278
- if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
279
- const numListeners = this.observers[event].get(listener) || 0;
280
- this.observers[event].set(listener, numListeners + 1);
281
- });
282
- return this;
283
- }
284
- off(event, listener) {
285
- if (!this.observers[event]) return;
286
- if (!listener) {
287
- delete this.observers[event];
288
- return;
289
- }
290
- this.observers[event].delete(listener);
291
- }
292
- emit(event) {
293
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
294
- args[_key - 1] = arguments[_key];
295
- }
296
- if (this.observers[event]) {
297
- const cloned = Array.from(this.observers[event].entries());
298
- cloned.forEach((_ref) => {
299
- let [observer, numTimesAdded] = _ref;
300
- for (let i = 0; i < numTimesAdded; i++) {
301
- observer(...args);
302
- }
303
- });
304
- }
305
- if (this.observers["*"]) {
306
- const cloned = Array.from(this.observers["*"].entries());
307
- cloned.forEach((_ref2) => {
308
- let [observer, numTimesAdded] = _ref2;
309
- for (let i = 0; i < numTimesAdded; i++) {
310
- observer.apply(observer, [event, ...args]);
311
- }
312
- });
313
- }
314
- }
315
- };
316
- var ResourceStore = class extends EventEmitter {
317
- constructor(data) {
318
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
319
- ns: ["translation"],
320
- defaultNS: "translation"
321
- };
322
- super();
323
- this.data = data || {};
324
- this.options = options;
325
- if (this.options.keySeparator === void 0) {
326
- this.options.keySeparator = ".";
327
- }
328
- if (this.options.ignoreJSONStructure === void 0) {
329
- this.options.ignoreJSONStructure = true;
330
- }
331
- }
332
- addNamespaces(ns) {
333
- if (this.options.ns.indexOf(ns) < 0) {
334
- this.options.ns.push(ns);
335
- }
336
- }
337
- removeNamespaces(ns) {
338
- const index = this.options.ns.indexOf(ns);
339
- if (index > -1) {
340
- this.options.ns.splice(index, 1);
341
- }
342
- }
343
- getResource(lng, ns, key) {
344
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
345
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
346
- const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
347
- let path;
348
- if (lng.indexOf(".") > -1) {
349
- path = lng.split(".");
350
- } else {
351
- path = [lng, ns];
352
- if (key) {
353
- if (Array.isArray(key)) {
354
- path.push(...key);
355
- } else if (isString(key) && keySeparator) {
356
- path.push(...key.split(keySeparator));
357
- } else {
358
- path.push(key);
359
- }
360
- }
361
- }
362
- const result = getPath(this.data, path);
363
- if (!result && !ns && !key && lng.indexOf(".") > -1) {
364
- lng = path[0];
365
- ns = path[1];
366
- key = path.slice(2).join(".");
367
- }
368
- if (result || !ignoreJSONStructure || !isString(key)) return result;
369
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
370
- }
371
- addResource(lng, ns, key, value) {
372
- let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
373
- silent: false
374
- };
375
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
376
- let path = [lng, ns];
377
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
378
- if (lng.indexOf(".") > -1) {
379
- path = lng.split(".");
380
- value = ns;
381
- ns = path[1];
382
- }
383
- this.addNamespaces(ns);
384
- setPath(this.data, path, value);
385
- if (!options.silent) this.emit("added", lng, ns, key, value);
386
- }
387
- addResources(lng, ns, resources2) {
388
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
389
- silent: false
390
- };
391
- for (const m in resources2) {
392
- if (isString(resources2[m]) || Array.isArray(resources2[m])) this.addResource(lng, ns, m, resources2[m], {
393
- silent: true
394
- });
395
- }
396
- if (!options.silent) this.emit("added", lng, ns, resources2);
397
- }
398
- addResourceBundle(lng, ns, resources2, deep, overwrite) {
399
- let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
400
- silent: false,
401
- skipCopy: false
402
- };
403
- let path = [lng, ns];
404
- if (lng.indexOf(".") > -1) {
405
- path = lng.split(".");
406
- deep = resources2;
407
- resources2 = ns;
408
- ns = path[1];
409
- }
410
- this.addNamespaces(ns);
411
- let pack = getPath(this.data, path) || {};
412
- if (!options.skipCopy) resources2 = JSON.parse(JSON.stringify(resources2));
413
- if (deep) {
414
- deepExtend(pack, resources2, overwrite);
415
- } else {
416
- pack = {
417
- ...pack,
418
- ...resources2
419
- };
420
- }
421
- setPath(this.data, path, pack);
422
- if (!options.silent) this.emit("added", lng, ns, resources2);
423
- }
424
- removeResourceBundle(lng, ns) {
425
- if (this.hasResourceBundle(lng, ns)) {
426
- delete this.data[lng][ns];
427
- }
428
- this.removeNamespaces(ns);
429
- this.emit("removed", lng, ns);
430
- }
431
- hasResourceBundle(lng, ns) {
432
- return this.getResource(lng, ns) !== void 0;
433
- }
434
- getResourceBundle(lng, ns) {
435
- if (!ns) ns = this.options.defaultNS;
436
- if (this.options.compatibilityAPI === "v1") return {
437
- ...{},
438
- ...this.getResource(lng, ns)
439
- };
440
- return this.getResource(lng, ns);
441
- }
442
- getDataByLanguage(lng) {
443
- return this.data[lng];
444
- }
445
- hasLanguageSomeTranslations(lng) {
446
- const data = this.getDataByLanguage(lng);
447
- const n = data && Object.keys(data) || [];
448
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
449
- }
450
- toJSON() {
451
- return this.data;
452
- }
453
- };
454
- var postProcessor = {
455
- processors: {},
456
- addPostProcessor(module) {
457
- this.processors[module.name] = module;
458
- },
459
- handle(processors, value, key, options, translator) {
460
- processors.forEach((processor) => {
461
- if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);
462
- });
463
- return value;
464
- }
465
- };
466
- var checkedLoadedFor = {};
467
- var Translator = class _Translator extends EventEmitter {
468
- constructor(services) {
469
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
470
- super();
471
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
472
- this.options = options;
473
- if (this.options.keySeparator === void 0) {
474
- this.options.keySeparator = ".";
475
- }
476
- this.logger = baseLogger.create("translator");
477
- }
478
- changeLanguage(lng) {
479
- if (lng) this.language = lng;
480
- }
481
- exists(key) {
482
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
483
- interpolation: {}
484
- };
485
- if (key === void 0 || key === null) {
486
- return false;
487
- }
488
- const resolved = this.resolve(key, options);
489
- return resolved && resolved.res !== void 0;
490
- }
491
- extractFromKey(key, options) {
492
- let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
493
- if (nsSeparator === void 0) nsSeparator = ":";
494
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
495
- let namespaces = options.ns || this.options.defaultNS || [];
496
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
497
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
498
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
499
- const m = key.match(this.interpolator.nestingRegexp);
500
- if (m && m.length > 0) {
501
- return {
502
- key,
503
- namespaces: isString(namespaces) ? [namespaces] : namespaces
504
- };
505
- }
506
- const parts = key.split(nsSeparator);
507
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
508
- key = parts.join(keySeparator);
509
- }
510
- return {
511
- key,
512
- namespaces: isString(namespaces) ? [namespaces] : namespaces
513
- };
514
- }
515
- translate(keys, options, lastKey) {
516
- if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
517
- options = this.options.overloadTranslationOptionHandler(arguments);
518
- }
519
- if (typeof options === "object") options = {
520
- ...options
521
- };
522
- if (!options) options = {};
523
- if (keys === void 0 || keys === null) return "";
524
- if (!Array.isArray(keys)) keys = [String(keys)];
525
- const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
526
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
527
- const {
528
- key,
529
- namespaces
530
- } = this.extractFromKey(keys[keys.length - 1], options);
531
- const namespace = namespaces[namespaces.length - 1];
532
- const lng = options.lng || this.language;
533
- const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
534
- if (lng && lng.toLowerCase() === "cimode") {
535
- if (appendNamespaceToCIMode) {
536
- const nsSeparator = options.nsSeparator || this.options.nsSeparator;
537
- if (returnDetails) {
538
- return {
539
- res: `${namespace}${nsSeparator}${key}`,
540
- usedKey: key,
541
- exactUsedKey: key,
542
- usedLng: lng,
543
- usedNS: namespace,
544
- usedParams: this.getUsedParamsDetails(options)
545
- };
546
- }
547
- return `${namespace}${nsSeparator}${key}`;
548
- }
549
- if (returnDetails) {
550
- return {
551
- res: key,
552
- usedKey: key,
553
- exactUsedKey: key,
554
- usedLng: lng,
555
- usedNS: namespace,
556
- usedParams: this.getUsedParamsDetails(options)
557
- };
558
- }
559
- return key;
560
- }
561
- const resolved = this.resolve(keys, options);
562
- let res = resolved && resolved.res;
563
- const resUsedKey = resolved && resolved.usedKey || key;
564
- const resExactUsedKey = resolved && resolved.exactUsedKey || key;
565
- const resType = Object.prototype.toString.apply(res);
566
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
567
- const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
568
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
569
- const handleAsObject = !isString(res) && typeof res !== "boolean" && typeof res !== "number";
570
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(res))) {
571
- if (!options.returnObjects && !this.options.returnObjects) {
572
- if (!this.options.returnedObjectHandler) {
573
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
574
- }
575
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
576
- ...options,
577
- ns: namespaces
578
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
579
- if (returnDetails) {
580
- resolved.res = r;
581
- resolved.usedParams = this.getUsedParamsDetails(options);
582
- return resolved;
583
- }
584
- return r;
585
- }
586
- if (keySeparator) {
587
- const resTypeIsArray = Array.isArray(res);
588
- const copy2 = resTypeIsArray ? [] : {};
589
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
590
- for (const m in res) {
591
- if (Object.prototype.hasOwnProperty.call(res, m)) {
592
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
593
- copy2[m] = this.translate(deepKey, {
594
- ...options,
595
- ...{
596
- joinArrays: false,
597
- ns: namespaces
598
- }
599
- });
600
- if (copy2[m] === deepKey) copy2[m] = res[m];
601
- }
602
- }
603
- res = copy2;
604
- }
605
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
606
- res = res.join(joinArrays);
607
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
608
- } else {
609
- let usedDefault = false;
610
- let usedKey = false;
611
- const needsPluralHandling = options.count !== void 0 && !isString(options.count);
612
- const hasDefaultValue = _Translator.hasDefaultValue(options);
613
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
614
- const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
615
- ordinal: false
616
- }) : "";
617
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
618
- const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
619
- if (!this.isValidLookup(res) && hasDefaultValue) {
620
- usedDefault = true;
621
- res = defaultValue;
622
- }
623
- if (!this.isValidLookup(res)) {
624
- usedKey = true;
625
- res = key;
626
- }
627
- const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
628
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
629
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
630
- if (usedKey || usedDefault || updateMissing) {
631
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
632
- if (keySeparator) {
633
- const fk = this.resolve(key, {
634
- ...options,
635
- keySeparator: false
636
- });
637
- 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.");
638
- }
639
- let lngs = [];
640
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
641
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
642
- for (let i = 0; i < fallbackLngs.length; i++) {
643
- lngs.push(fallbackLngs[i]);
644
- }
645
- } else if (this.options.saveMissingTo === "all") {
646
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
647
- } else {
648
- lngs.push(options.lng || this.language);
649
- }
650
- const send = (l, k, specificDefaultValue) => {
651
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
652
- if (this.options.missingKeyHandler) {
653
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
654
- } else if (this.backendConnector && this.backendConnector.saveMissing) {
655
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
656
- }
657
- this.emit("missingKey", l, namespace, k, res);
658
- };
659
- if (this.options.saveMissing) {
660
- if (this.options.saveMissingPlurals && needsPluralHandling) {
661
- lngs.forEach((language) => {
662
- const suffixes = this.pluralResolver.getSuffixes(language, options);
663
- if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
664
- suffixes.push(`${this.options.pluralSeparator}zero`);
665
- }
666
- suffixes.forEach((suffix) => {
667
- send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
668
- });
669
- });
670
- } else {
671
- send(lngs, key, defaultValue);
672
- }
673
- }
674
- }
675
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
676
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
677
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
678
- if (this.options.compatibilityAPI !== "v1") {
679
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
680
- } else {
681
- res = this.options.parseMissingKeyHandler(res);
682
- }
683
- }
684
- }
685
- if (returnDetails) {
686
- resolved.res = res;
687
- resolved.usedParams = this.getUsedParamsDetails(options);
688
- return resolved;
689
- }
690
- return res;
691
- }
692
- extendTranslation(res, key, options, resolved, lastKey) {
693
- var _this = this;
694
- if (this.i18nFormat && this.i18nFormat.parse) {
695
- res = this.i18nFormat.parse(res, {
696
- ...this.options.interpolation.defaultVariables,
697
- ...options
698
- }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
699
- resolved
700
- });
701
- } else if (!options.skipInterpolation) {
702
- if (options.interpolation) this.interpolator.init({
703
- ...options,
704
- ...{
705
- interpolation: {
706
- ...this.options.interpolation,
707
- ...options.interpolation
708
- }
709
- }
710
- });
711
- const skipOnVariables = isString(res) && (options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
712
- let nestBef;
713
- if (skipOnVariables) {
714
- const nb = res.match(this.interpolator.nestingRegexp);
715
- nestBef = nb && nb.length;
716
- }
717
- let data = options.replace && !isString(options.replace) ? options.replace : options;
718
- if (this.options.interpolation.defaultVariables) data = {
719
- ...this.options.interpolation.defaultVariables,
720
- ...data
721
- };
722
- res = this.interpolator.interpolate(res, data, options.lng || this.language || resolved.usedLng, options);
723
- if (skipOnVariables) {
724
- const na = res.match(this.interpolator.nestingRegexp);
725
- const nestAft = na && na.length;
726
- if (nestBef < nestAft) options.nest = false;
727
- }
728
- if (!options.lng && this.options.compatibilityAPI !== "v1" && resolved && resolved.res) options.lng = this.language || resolved.usedLng;
729
- if (options.nest !== false) res = this.interpolator.nest(res, function() {
730
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
731
- args[_key] = arguments[_key];
732
- }
733
- if (lastKey && lastKey[0] === args[0] && !options.context) {
734
- _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
735
- return null;
736
- }
737
- return _this.translate(...args, key);
738
- }, options);
739
- if (options.interpolation) this.interpolator.reset();
740
- }
741
- const postProcess = options.postProcess || this.options.postProcess;
742
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
743
- if (res !== void 0 && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
744
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
745
- i18nResolved: {
746
- ...resolved,
747
- usedParams: this.getUsedParamsDetails(options)
748
- },
749
- ...options
750
- } : options, this);
751
- }
752
- return res;
753
- }
754
- resolve(keys) {
755
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
756
- let found;
757
- let usedKey;
758
- let exactUsedKey;
759
- let usedLng;
760
- let usedNS;
761
- if (isString(keys)) keys = [keys];
762
- keys.forEach((k) => {
763
- if (this.isValidLookup(found)) return;
764
- const extracted = this.extractFromKey(k, options);
765
- const key = extracted.key;
766
- usedKey = key;
767
- let namespaces = extracted.namespaces;
768
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
769
- const needsPluralHandling = options.count !== void 0 && !isString(options.count);
770
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
771
- const needsContextHandling = options.context !== void 0 && (isString(options.context) || typeof options.context === "number") && options.context !== "";
772
- const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
773
- namespaces.forEach((ns) => {
774
- if (this.isValidLookup(found)) return;
775
- usedNS = ns;
776
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
777
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
778
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${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!!!");
779
- }
780
- codes.forEach((code) => {
781
- if (this.isValidLookup(found)) return;
782
- usedLng = code;
783
- const finalKeys = [key];
784
- if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
785
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
786
- } else {
787
- let pluralSuffix;
788
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
789
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
790
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
791
- if (needsPluralHandling) {
792
- finalKeys.push(key + pluralSuffix);
793
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
794
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
795
- }
796
- if (needsZeroSuffixLookup) {
797
- finalKeys.push(key + zeroSuffix);
798
- }
799
- }
800
- if (needsContextHandling) {
801
- const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
802
- finalKeys.push(contextKey);
803
- if (needsPluralHandling) {
804
- finalKeys.push(contextKey + pluralSuffix);
805
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
806
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
807
- }
808
- if (needsZeroSuffixLookup) {
809
- finalKeys.push(contextKey + zeroSuffix);
810
- }
811
- }
812
- }
813
- }
814
- let possibleKey;
815
- while (possibleKey = finalKeys.pop()) {
816
- if (!this.isValidLookup(found)) {
817
- exactUsedKey = possibleKey;
818
- found = this.getResource(code, ns, possibleKey, options);
819
- }
820
- }
821
- });
822
- });
823
- });
824
- return {
825
- res: found,
826
- usedKey,
827
- exactUsedKey,
828
- usedLng,
829
- usedNS
830
- };
831
- }
832
- isValidLookup(res) {
833
- return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
834
- }
835
- getResource(code, ns, key) {
836
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
837
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
838
- return this.resourceStore.getResource(code, ns, key, options);
839
- }
840
- getUsedParamsDetails() {
841
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
842
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
843
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
844
- let data = useOptionsReplaceForData ? options.replace : options;
845
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
846
- data.count = options.count;
847
- }
848
- if (this.options.interpolation.defaultVariables) {
849
- data = {
850
- ...this.options.interpolation.defaultVariables,
851
- ...data
852
- };
853
- }
854
- if (!useOptionsReplaceForData) {
855
- data = {
856
- ...data
857
- };
858
- for (const key of optionsKeys) {
859
- delete data[key];
860
- }
861
- }
862
- return data;
863
- }
864
- static hasDefaultValue(options) {
865
- const prefix = "defaultValue";
866
- for (const option in options) {
867
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
868
- return true;
869
- }
870
- }
871
- return false;
872
- }
873
- };
874
- var capitalize = (string) => string.charAt(0).toUpperCase() + string.slice(1);
875
- var LanguageUtil = class {
876
- constructor(options) {
877
- this.options = options;
878
- this.supportedLngs = this.options.supportedLngs || false;
879
- this.logger = baseLogger.create("languageUtils");
880
- }
881
- getScriptPartFromCode(code) {
882
- code = getCleanedCode(code);
883
- if (!code || code.indexOf("-") < 0) return null;
884
- const p = code.split("-");
885
- if (p.length === 2) return null;
886
- p.pop();
887
- if (p[p.length - 1].toLowerCase() === "x") return null;
888
- return this.formatLanguageCode(p.join("-"));
889
- }
890
- getLanguagePartFromCode(code) {
891
- code = getCleanedCode(code);
892
- if (!code || code.indexOf("-") < 0) return code;
893
- const p = code.split("-");
894
- return this.formatLanguageCode(p[0]);
895
- }
896
- formatLanguageCode(code) {
897
- if (isString(code) && code.indexOf("-") > -1) {
898
- if (typeof Intl !== "undefined" && typeof Intl.getCanonicalLocales !== "undefined") {
899
- try {
900
- let formattedCode = Intl.getCanonicalLocales(code)[0];
901
- if (formattedCode && this.options.lowerCaseLng) {
902
- formattedCode = formattedCode.toLowerCase();
903
- }
904
- if (formattedCode) return formattedCode;
905
- } catch (e) {
906
- }
907
- }
908
- const specialCases = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"];
909
- let p = code.split("-");
910
- if (this.options.lowerCaseLng) {
911
- p = p.map((part) => part.toLowerCase());
912
- } else if (p.length === 2) {
913
- p[0] = p[0].toLowerCase();
914
- p[1] = p[1].toUpperCase();
915
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
916
- } else if (p.length === 3) {
917
- p[0] = p[0].toLowerCase();
918
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
919
- if (p[0] !== "sgn" && p[2].length === 2) p[2] = p[2].toUpperCase();
920
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
921
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
922
- }
923
- return p.join("-");
924
- }
925
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
926
- }
927
- isSupportedCode(code) {
928
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
929
- code = this.getLanguagePartFromCode(code);
930
- }
931
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
932
- }
933
- getBestMatchFromCodes(codes) {
934
- if (!codes) return null;
935
- let found;
936
- codes.forEach((code) => {
937
- if (found) return;
938
- const cleanedLng = this.formatLanguageCode(code);
939
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
940
- });
941
- if (!found && this.options.supportedLngs) {
942
- codes.forEach((code) => {
943
- if (found) return;
944
- const lngOnly = this.getLanguagePartFromCode(code);
945
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
946
- found = this.options.supportedLngs.find((supportedLng) => {
947
- if (supportedLng === lngOnly) return supportedLng;
948
- if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
949
- if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
950
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
951
- });
952
- });
953
- }
954
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
955
- return found;
956
- }
957
- getFallbackCodes(fallbacks, code) {
958
- if (!fallbacks) return [];
959
- if (typeof fallbacks === "function") fallbacks = fallbacks(code);
960
- if (isString(fallbacks)) fallbacks = [fallbacks];
961
- if (Array.isArray(fallbacks)) return fallbacks;
962
- if (!code) return fallbacks.default || [];
963
- let found = fallbacks[code];
964
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
965
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
966
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
967
- if (!found) found = fallbacks.default;
968
- return found || [];
969
- }
970
- toResolveHierarchy(code, fallbackCode) {
971
- const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
972
- const codes = [];
973
- const addCode = (c) => {
974
- if (!c) return;
975
- if (this.isSupportedCode(c)) {
976
- codes.push(c);
977
- } else {
978
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
979
- }
980
- };
981
- if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
982
- if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
983
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
984
- if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
985
- } else if (isString(code)) {
986
- addCode(this.formatLanguageCode(code));
987
- }
988
- fallbackCodes.forEach((fc) => {
989
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
990
- });
991
- return codes;
992
- }
993
- };
994
- var sets = [{
995
- lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"],
996
- nr: [1, 2],
997
- fc: 1
998
- }, {
999
- 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"],
1000
- nr: [1, 2],
1001
- fc: 2
1002
- }, {
1003
- lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"],
1004
- nr: [1],
1005
- fc: 3
1006
- }, {
1007
- lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"],
1008
- nr: [1, 2, 5],
1009
- fc: 4
1010
- }, {
1011
- lngs: ["ar"],
1012
- nr: [0, 1, 2, 3, 11, 100],
1013
- fc: 5
1014
- }, {
1015
- lngs: ["cs", "sk"],
1016
- nr: [1, 2, 5],
1017
- fc: 6
1018
- }, {
1019
- lngs: ["csb", "pl"],
1020
- nr: [1, 2, 5],
1021
- fc: 7
1022
- }, {
1023
- lngs: ["cy"],
1024
- nr: [1, 2, 3, 8],
1025
- fc: 8
1026
- }, {
1027
- lngs: ["fr"],
1028
- nr: [1, 2],
1029
- fc: 9
1030
- }, {
1031
- lngs: ["ga"],
1032
- nr: [1, 2, 3, 7, 11],
1033
- fc: 10
1034
- }, {
1035
- lngs: ["gd"],
1036
- nr: [1, 2, 3, 20],
1037
- fc: 11
1038
- }, {
1039
- lngs: ["is"],
1040
- nr: [1, 2],
1041
- fc: 12
1042
- }, {
1043
- lngs: ["jv"],
1044
- nr: [0, 1],
1045
- fc: 13
1046
- }, {
1047
- lngs: ["kw"],
1048
- nr: [1, 2, 3, 4],
1049
- fc: 14
1050
- }, {
1051
- lngs: ["lt"],
1052
- nr: [1, 2, 10],
1053
- fc: 15
1054
- }, {
1055
- lngs: ["lv"],
1056
- nr: [1, 2, 0],
1057
- fc: 16
1058
- }, {
1059
- lngs: ["mk"],
1060
- nr: [1, 2],
1061
- fc: 17
1062
- }, {
1063
- lngs: ["mnk"],
1064
- nr: [0, 1, 2],
1065
- fc: 18
1066
- }, {
1067
- lngs: ["mt"],
1068
- nr: [1, 2, 11, 20],
1069
- fc: 19
1070
- }, {
1071
- lngs: ["or"],
1072
- nr: [2, 1],
1073
- fc: 2
1074
- }, {
1075
- lngs: ["ro"],
1076
- nr: [1, 2, 20],
1077
- fc: 20
1078
- }, {
1079
- lngs: ["sl"],
1080
- nr: [5, 1, 2, 3],
1081
- fc: 21
1082
- }, {
1083
- lngs: ["he", "iw"],
1084
- nr: [1, 2, 20, 21],
1085
- fc: 22
1086
- }];
1087
- var _rulesPluralsTypes = {
1088
- 1: (n) => Number(n > 1),
1089
- 2: (n) => Number(n != 1),
1090
- 3: (n) => 0,
1091
- 4: (n) => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
1092
- 5: (n) => Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5),
1093
- 6: (n) => Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2),
1094
- 7: (n) => Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
1095
- 8: (n) => Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3),
1096
- 9: (n) => Number(n >= 2),
1097
- 10: (n) => Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4),
1098
- 11: (n) => Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3),
1099
- 12: (n) => Number(n % 10 != 1 || n % 100 == 11),
1100
- 13: (n) => Number(n !== 0),
1101
- 14: (n) => Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3),
1102
- 15: (n) => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
1103
- 16: (n) => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2),
1104
- 17: (n) => Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1),
1105
- 18: (n) => Number(n == 0 ? 0 : n == 1 ? 1 : 2),
1106
- 19: (n) => Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3),
1107
- 20: (n) => Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2),
1108
- 21: (n) => Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0),
1109
- 22: (n) => Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3)
1110
- };
1111
- var nonIntlVersions = ["v1", "v2", "v3"];
1112
- var intlVersions = ["v4"];
1113
- var suffixesOrder = {
1114
- zero: 0,
1115
- one: 1,
1116
- two: 2,
1117
- few: 3,
1118
- many: 4,
1119
- other: 5
1120
- };
1121
- var createRules = () => {
1122
- const rules = {};
1123
- sets.forEach((set) => {
1124
- set.lngs.forEach((l) => {
1125
- rules[l] = {
1126
- numbers: set.nr,
1127
- plurals: _rulesPluralsTypes[set.fc]
1128
- };
1129
- });
1130
- });
1131
- return rules;
1132
- };
1133
- var PluralResolver = class {
1134
- constructor(languageUtils) {
1135
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1136
- this.languageUtils = languageUtils;
1137
- this.options = options;
1138
- this.logger = baseLogger.create("pluralResolver");
1139
- if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === "undefined" || !Intl.PluralRules)) {
1140
- this.options.compatibilityJSON = "v3";
1141
- 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.");
1142
- }
1143
- this.rules = createRules();
1144
- this.pluralRulesCache = {};
1145
- }
1146
- addRule(lng, obj) {
1147
- this.rules[lng] = obj;
1148
- }
1149
- clearCache() {
1150
- this.pluralRulesCache = {};
1151
- }
1152
- getRule(code) {
1153
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1154
- if (this.shouldUseIntlApi()) {
1155
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1156
- const type = options.ordinal ? "ordinal" : "cardinal";
1157
- const cacheKey = JSON.stringify({
1158
- cleanedCode,
1159
- type
1160
- });
1161
- if (cacheKey in this.pluralRulesCache) {
1162
- return this.pluralRulesCache[cacheKey];
1163
- }
1164
- let rule;
1165
- try {
1166
- rule = new Intl.PluralRules(cleanedCode, {
1167
- type
1168
- });
1169
- } catch (err) {
1170
- if (!code.match(/-|_/)) return;
1171
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1172
- rule = this.getRule(lngPart, options);
1173
- }
1174
- this.pluralRulesCache[cacheKey] = rule;
1175
- return rule;
1176
- }
1177
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1178
- }
1179
- needsPlural(code) {
1180
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1181
- const rule = this.getRule(code, options);
1182
- if (this.shouldUseIntlApi()) {
1183
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
1184
- }
1185
- return rule && rule.numbers.length > 1;
1186
- }
1187
- getPluralFormsOfKey(code, key) {
1188
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1189
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1190
- }
1191
- getSuffixes(code) {
1192
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1193
- const rule = this.getRule(code, options);
1194
- if (!rule) {
1195
- return [];
1196
- }
1197
- if (this.shouldUseIntlApi()) {
1198
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1199
- }
1200
- return rule.numbers.map((number) => this.getSuffix(code, number, options));
1201
- }
1202
- getSuffix(code, count) {
1203
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1204
- const rule = this.getRule(code, options);
1205
- if (rule) {
1206
- if (this.shouldUseIntlApi()) {
1207
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1208
- }
1209
- return this.getSuffixRetroCompatible(rule, count);
1210
- }
1211
- this.logger.warn(`no plural rule found for: ${code}`);
1212
- return "";
1213
- }
1214
- getSuffixRetroCompatible(rule, count) {
1215
- const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
1216
- let suffix = rule.numbers[idx];
1217
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1218
- if (suffix === 2) {
1219
- suffix = "plural";
1220
- } else if (suffix === 1) {
1221
- suffix = "";
1222
- }
1223
- }
1224
- const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
1225
- if (this.options.compatibilityJSON === "v1") {
1226
- if (suffix === 1) return "";
1227
- if (typeof suffix === "number") return `_plural_${suffix.toString()}`;
1228
- return returnSuffix();
1229
- } else if (this.options.compatibilityJSON === "v2") {
1230
- return returnSuffix();
1231
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1232
- return returnSuffix();
1233
- }
1234
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
1235
- }
1236
- shouldUseIntlApi() {
1237
- return !nonIntlVersions.includes(this.options.compatibilityJSON);
1238
- }
1239
- };
1240
- var deepFindWithDefaults = function(data, defaultData, key) {
1241
- let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
1242
- let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
1243
- let path = getPathWithDefaults(data, defaultData, key);
1244
- if (!path && ignoreJSONStructure && isString(key)) {
1245
- path = deepFind(data, key, keySeparator);
1246
- if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1247
- }
1248
- return path;
1249
- };
1250
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1251
- var Interpolator = class {
1252
- constructor() {
1253
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1254
- this.logger = baseLogger.create("interpolator");
1255
- this.options = options;
1256
- this.format = options.interpolation && options.interpolation.format || ((value) => value);
1257
- this.init(options);
1258
- }
1259
- init() {
1260
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1261
- if (!options.interpolation) options.interpolation = {
1262
- escapeValue: true
1263
- };
1264
- const {
1265
- escape: escape$1,
1266
- escapeValue,
1267
- useRawValueToEscape,
1268
- prefix,
1269
- prefixEscaped,
1270
- suffix,
1271
- suffixEscaped,
1272
- formatSeparator,
1273
- unescapeSuffix,
1274
- unescapePrefix,
1275
- nestingPrefix,
1276
- nestingPrefixEscaped,
1277
- nestingSuffix,
1278
- nestingSuffixEscaped,
1279
- nestingOptionsSeparator,
1280
- maxReplaces,
1281
- alwaysFormat
1282
- } = options.interpolation;
1283
- this.escape = escape$1 !== void 0 ? escape$1 : escape;
1284
- this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1285
- this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1286
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1287
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1288
- this.formatSeparator = formatSeparator || ",";
1289
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1290
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1291
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1292
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1293
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1294
- this.maxReplaces = maxReplaces || 1e3;
1295
- this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1296
- this.resetRegExp();
1297
- }
1298
- reset() {
1299
- if (this.options) this.init(this.options);
1300
- }
1301
- resetRegExp() {
1302
- const getOrResetRegExp = (existingRegExp, pattern) => {
1303
- if (existingRegExp && existingRegExp.source === pattern) {
1304
- existingRegExp.lastIndex = 0;
1305
- return existingRegExp;
1306
- }
1307
- return new RegExp(pattern, "g");
1308
- };
1309
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1310
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1311
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
1312
- }
1313
- interpolate(str, data, lng, options) {
1314
- let match;
1315
- let value;
1316
- let replaces;
1317
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1318
- const handleFormat = (key) => {
1319
- if (key.indexOf(this.formatSeparator) < 0) {
1320
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1321
- return this.alwaysFormat ? this.format(path, void 0, lng, {
1322
- ...options,
1323
- ...data,
1324
- interpolationkey: key
1325
- }) : path;
1326
- }
1327
- const p = key.split(this.formatSeparator);
1328
- const k = p.shift().trim();
1329
- const f = p.join(this.formatSeparator).trim();
1330
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1331
- ...options,
1332
- ...data,
1333
- interpolationkey: k
1334
- });
1335
- };
1336
- this.resetRegExp();
1337
- const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
1338
- const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1339
- const todos = [{
1340
- regex: this.regexpUnescape,
1341
- safeValue: (val) => regexSafe(val)
1342
- }, {
1343
- regex: this.regexp,
1344
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1345
- }];
1346
- todos.forEach((todo) => {
1347
- replaces = 0;
1348
- while (match = todo.regex.exec(str)) {
1349
- const matchedVar = match[1].trim();
1350
- value = handleFormat(matchedVar);
1351
- if (value === void 0) {
1352
- if (typeof missingInterpolationHandler === "function") {
1353
- const temp = missingInterpolationHandler(str, match, options);
1354
- value = isString(temp) ? temp : "";
1355
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1356
- value = "";
1357
- } else if (skipOnVariables) {
1358
- value = match[0];
1359
- continue;
1360
- } else {
1361
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1362
- value = "";
1363
- }
1364
- } else if (!isString(value) && !this.useRawValueToEscape) {
1365
- value = makeString(value);
1366
- }
1367
- const safeValue = todo.safeValue(value);
1368
- str = str.replace(match[0], safeValue);
1369
- if (skipOnVariables) {
1370
- todo.regex.lastIndex += value.length;
1371
- todo.regex.lastIndex -= match[0].length;
1372
- } else {
1373
- todo.regex.lastIndex = 0;
1374
- }
1375
- replaces++;
1376
- if (replaces >= this.maxReplaces) {
1377
- break;
1378
- }
1379
- }
1380
- });
1381
- return str;
1382
- }
1383
- nest(str, fc) {
1384
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1385
- let match;
1386
- let value;
1387
- let clonedOptions;
1388
- const handleHasOptions = (key, inheritedOptions) => {
1389
- const sep = this.nestingOptionsSeparator;
1390
- if (key.indexOf(sep) < 0) return key;
1391
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1392
- let optionsString = `{${c[1]}`;
1393
- key = c[0];
1394
- optionsString = this.interpolate(optionsString, clonedOptions);
1395
- const matchedSingleQuotes = optionsString.match(/'/g);
1396
- const matchedDoubleQuotes = optionsString.match(/"/g);
1397
- if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1398
- optionsString = optionsString.replace(/'/g, '"');
1399
- }
1400
- try {
1401
- clonedOptions = JSON.parse(optionsString);
1402
- if (inheritedOptions) clonedOptions = {
1403
- ...inheritedOptions,
1404
- ...clonedOptions
1405
- };
1406
- } catch (e) {
1407
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1408
- return `${key}${sep}${optionsString}`;
1409
- }
1410
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1411
- return key;
1412
- };
1413
- while (match = this.nestingRegexp.exec(str)) {
1414
- let formatters = [];
1415
- clonedOptions = {
1416
- ...options
1417
- };
1418
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1419
- clonedOptions.applyPostProcessor = false;
1420
- delete clonedOptions.defaultValue;
1421
- let doReduce = false;
1422
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1423
- const r = match[1].split(this.formatSeparator).map((elem) => elem.trim());
1424
- match[1] = r.shift();
1425
- formatters = r;
1426
- doReduce = true;
1427
- }
1428
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1429
- if (value && match[0] === str && !isString(value)) return value;
1430
- if (!isString(value)) value = makeString(value);
1431
- if (!value) {
1432
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1433
- value = "";
1434
- }
1435
- if (doReduce) {
1436
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1437
- ...options,
1438
- interpolationkey: match[1].trim()
1439
- }), value.trim());
1440
- }
1441
- str = str.replace(match[0], value);
1442
- this.regexp.lastIndex = 0;
1443
- }
1444
- return str;
1445
- }
1446
- };
1447
- var parseFormatStr = (formatStr) => {
1448
- let formatName = formatStr.toLowerCase().trim();
1449
- const formatOptions = {};
1450
- if (formatStr.indexOf("(") > -1) {
1451
- const p = formatStr.split("(");
1452
- formatName = p[0].toLowerCase().trim();
1453
- const optStr = p[1].substring(0, p[1].length - 1);
1454
- if (formatName === "currency" && optStr.indexOf(":") < 0) {
1455
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1456
- } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1457
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1458
- } else {
1459
- const opts = optStr.split(";");
1460
- opts.forEach((opt) => {
1461
- if (opt) {
1462
- const [key, ...rest] = opt.split(":");
1463
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1464
- const trimmedKey = key.trim();
1465
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1466
- if (val === "false") formatOptions[trimmedKey] = false;
1467
- if (val === "true") formatOptions[trimmedKey] = true;
1468
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1469
- }
1470
- });
1471
- }
1472
- }
1473
- return {
1474
- formatName,
1475
- formatOptions
1476
- };
1477
- };
1478
- var createCachedFormatter = (fn) => {
1479
- const cache = {};
1480
- return (val, lng, options) => {
1481
- let optForCache = options;
1482
- if (options && options.interpolationkey && options.formatParams && options.formatParams[options.interpolationkey] && options[options.interpolationkey]) {
1483
- optForCache = {
1484
- ...optForCache,
1485
- [options.interpolationkey]: void 0
1486
- };
1487
- }
1488
- const key = lng + JSON.stringify(optForCache);
1489
- let formatter = cache[key];
1490
- if (!formatter) {
1491
- formatter = fn(getCleanedCode(lng), options);
1492
- cache[key] = formatter;
1493
- }
1494
- return formatter(val);
1495
- };
1496
- };
1497
- var Formatter = class {
1498
- constructor() {
1499
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1500
- this.logger = baseLogger.create("formatter");
1501
- this.options = options;
1502
- this.formats = {
1503
- number: createCachedFormatter((lng, opt) => {
1504
- const formatter = new Intl.NumberFormat(lng, {
1505
- ...opt
1506
- });
1507
- return (val) => formatter.format(val);
1508
- }),
1509
- currency: createCachedFormatter((lng, opt) => {
1510
- const formatter = new Intl.NumberFormat(lng, {
1511
- ...opt,
1512
- style: "currency"
1513
- });
1514
- return (val) => formatter.format(val);
1515
- }),
1516
- datetime: createCachedFormatter((lng, opt) => {
1517
- const formatter = new Intl.DateTimeFormat(lng, {
1518
- ...opt
1519
- });
1520
- return (val) => formatter.format(val);
1521
- }),
1522
- relativetime: createCachedFormatter((lng, opt) => {
1523
- const formatter = new Intl.RelativeTimeFormat(lng, {
1524
- ...opt
1525
- });
1526
- return (val) => formatter.format(val, opt.range || "day");
1527
- }),
1528
- list: createCachedFormatter((lng, opt) => {
1529
- const formatter = new Intl.ListFormat(lng, {
1530
- ...opt
1531
- });
1532
- return (val) => formatter.format(val);
1533
- })
1534
- };
1535
- this.init(options);
1536
- }
1537
- init(services) {
1538
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
1539
- interpolation: {}
1540
- };
1541
- this.formatSeparator = options.interpolation.formatSeparator || ",";
1542
- }
1543
- add(name, fc) {
1544
- this.formats[name.toLowerCase().trim()] = fc;
1545
- }
1546
- addCached(name, fc) {
1547
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1548
- }
1549
- format(value, format, lng) {
1550
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1551
- const formats = format.split(this.formatSeparator);
1552
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1553
- const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1554
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1555
- }
1556
- const result = formats.reduce((mem, f) => {
1557
- const {
1558
- formatName,
1559
- formatOptions
1560
- } = parseFormatStr(f);
1561
- if (this.formats[formatName]) {
1562
- let formatted = mem;
1563
- try {
1564
- const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
1565
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1566
- formatted = this.formats[formatName](mem, l, {
1567
- ...formatOptions,
1568
- ...options,
1569
- ...valOptions
1570
- });
1571
- } catch (error) {
1572
- this.logger.warn(error);
1573
- }
1574
- return formatted;
1575
- } else {
1576
- this.logger.warn(`there was no format function for ${formatName}`);
1577
- }
1578
- return mem;
1579
- }, value);
1580
- return result;
1581
- }
1582
- };
1583
- var removePending = (q, name) => {
1584
- if (q.pending[name] !== void 0) {
1585
- delete q.pending[name];
1586
- q.pendingCount--;
1587
- }
1588
- };
1589
- var Connector = class extends EventEmitter {
1590
- constructor(backend, store, services) {
1591
- let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1592
- super();
1593
- this.backend = backend;
1594
- this.store = store;
1595
- this.services = services;
1596
- this.languageUtils = services.languageUtils;
1597
- this.options = options;
1598
- this.logger = baseLogger.create("backendConnector");
1599
- this.waitingReads = [];
1600
- this.maxParallelReads = options.maxParallelReads || 10;
1601
- this.readingCalls = 0;
1602
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1603
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1604
- this.state = {};
1605
- this.queue = [];
1606
- if (this.backend && this.backend.init) {
1607
- this.backend.init(services, options.backend, options);
1608
- }
1609
- }
1610
- queueLoad(languages, namespaces, options, callback) {
1611
- const toLoad = {};
1612
- const pending = {};
1613
- const toLoadLanguages = {};
1614
- const toLoadNamespaces = {};
1615
- languages.forEach((lng) => {
1616
- let hasAllNamespaces = true;
1617
- namespaces.forEach((ns) => {
1618
- const name = `${lng}|${ns}`;
1619
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1620
- this.state[name] = 2;
1621
- } else if (this.state[name] < 0) ;
1622
- else if (this.state[name] === 1) {
1623
- if (pending[name] === void 0) pending[name] = true;
1624
- } else {
1625
- this.state[name] = 1;
1626
- hasAllNamespaces = false;
1627
- if (pending[name] === void 0) pending[name] = true;
1628
- if (toLoad[name] === void 0) toLoad[name] = true;
1629
- if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1630
- }
1631
- });
1632
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1633
- });
1634
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1635
- this.queue.push({
1636
- pending,
1637
- pendingCount: Object.keys(pending).length,
1638
- loaded: {},
1639
- errors: [],
1640
- callback
1641
- });
1642
- }
1643
- return {
1644
- toLoad: Object.keys(toLoad),
1645
- pending: Object.keys(pending),
1646
- toLoadLanguages: Object.keys(toLoadLanguages),
1647
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1648
- };
1649
- }
1650
- loaded(name, err, data) {
1651
- const s = name.split("|");
1652
- const lng = s[0];
1653
- const ns = s[1];
1654
- if (err) this.emit("failedLoading", lng, ns, err);
1655
- if (!err && data) {
1656
- this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1657
- skipCopy: true
1658
- });
1659
- }
1660
- this.state[name] = err ? -1 : 2;
1661
- if (err && data) this.state[name] = 0;
1662
- const loaded = {};
1663
- this.queue.forEach((q) => {
1664
- pushPath(q.loaded, [lng], ns);
1665
- removePending(q, name);
1666
- if (err) q.errors.push(err);
1667
- if (q.pendingCount === 0 && !q.done) {
1668
- Object.keys(q.loaded).forEach((l) => {
1669
- if (!loaded[l]) loaded[l] = {};
1670
- const loadedKeys = q.loaded[l];
1671
- if (loadedKeys.length) {
1672
- loadedKeys.forEach((n) => {
1673
- if (loaded[l][n] === void 0) loaded[l][n] = true;
1674
- });
1675
- }
1676
- });
1677
- q.done = true;
1678
- if (q.errors.length) {
1679
- q.callback(q.errors);
1680
- } else {
1681
- q.callback();
1682
- }
1683
- }
1684
- });
1685
- this.emit("loaded", loaded);
1686
- this.queue = this.queue.filter((q) => !q.done);
1687
- }
1688
- read(lng, ns, fcName) {
1689
- let tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
1690
- let wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout;
1691
- let callback = arguments.length > 5 ? arguments[5] : void 0;
1692
- if (!lng.length) return callback(null, {});
1693
- if (this.readingCalls >= this.maxParallelReads) {
1694
- this.waitingReads.push({
1695
- lng,
1696
- ns,
1697
- fcName,
1698
- tried,
1699
- wait,
1700
- callback
1701
- });
1702
- return;
1703
- }
1704
- this.readingCalls++;
1705
- const resolver = (err, data) => {
1706
- this.readingCalls--;
1707
- if (this.waitingReads.length > 0) {
1708
- const next = this.waitingReads.shift();
1709
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1710
- }
1711
- if (err && data && tried < this.maxRetries) {
1712
- setTimeout(() => {
1713
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1714
- }, wait);
1715
- return;
1716
- }
1717
- callback(err, data);
1718
- };
1719
- const fc = this.backend[fcName].bind(this.backend);
1720
- if (fc.length === 2) {
1721
- try {
1722
- const r = fc(lng, ns);
1723
- if (r && typeof r.then === "function") {
1724
- r.then((data) => resolver(null, data)).catch(resolver);
1725
- } else {
1726
- resolver(null, r);
1727
- }
1728
- } catch (err) {
1729
- resolver(err);
1730
- }
1731
- return;
1732
- }
1733
- return fc(lng, ns, resolver);
1734
- }
1735
- prepareLoading(languages, namespaces) {
1736
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1737
- let callback = arguments.length > 3 ? arguments[3] : void 0;
1738
- if (!this.backend) {
1739
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1740
- return callback && callback();
1741
- }
1742
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1743
- if (isString(namespaces)) namespaces = [namespaces];
1744
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1745
- if (!toLoad.toLoad.length) {
1746
- if (!toLoad.pending.length) callback();
1747
- return null;
1748
- }
1749
- toLoad.toLoad.forEach((name) => {
1750
- this.loadOne(name);
1751
- });
1752
- }
1753
- load(languages, namespaces, callback) {
1754
- this.prepareLoading(languages, namespaces, {}, callback);
1755
- }
1756
- reload(languages, namespaces, callback) {
1757
- this.prepareLoading(languages, namespaces, {
1758
- reload: true
1759
- }, callback);
1760
- }
1761
- loadOne(name) {
1762
- let prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
1763
- const s = name.split("|");
1764
- const lng = s[0];
1765
- const ns = s[1];
1766
- this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1767
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1768
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1769
- this.loaded(name, err, data);
1770
- });
1771
- }
1772
- saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
1773
- let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
1774
- let clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : () => {
1775
- };
1776
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
1777
- this.logger.warn(`did not save key "${key}" as the namespace "${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!!!");
1778
- return;
1779
- }
1780
- if (key === void 0 || key === null || key === "") return;
1781
- if (this.backend && this.backend.create) {
1782
- const opts = {
1783
- ...options,
1784
- isUpdate
1785
- };
1786
- const fc = this.backend.create.bind(this.backend);
1787
- if (fc.length < 6) {
1788
- try {
1789
- let r;
1790
- if (fc.length === 5) {
1791
- r = fc(languages, namespace, key, fallbackValue, opts);
1792
- } else {
1793
- r = fc(languages, namespace, key, fallbackValue);
1794
- }
1795
- if (r && typeof r.then === "function") {
1796
- r.then((data) => clb(null, data)).catch(clb);
1797
- } else {
1798
- clb(null, r);
1799
- }
1800
- } catch (err) {
1801
- clb(err);
1802
- }
1803
- } else {
1804
- fc(languages, namespace, key, fallbackValue, clb, opts);
1805
- }
1806
- }
1807
- if (!languages || !languages[0]) return;
1808
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1809
- }
1810
- };
1811
- var get = () => ({
1812
- debug: false,
1813
- initImmediate: true,
1814
- ns: ["translation"],
1815
- defaultNS: ["translation"],
1816
- fallbackLng: ["dev"],
1817
- fallbackNS: false,
1818
- supportedLngs: false,
1819
- nonExplicitSupportedLngs: false,
1820
- load: "all",
1821
- preload: false,
1822
- simplifyPluralSuffix: true,
1823
- keySeparator: ".",
1824
- nsSeparator: ":",
1825
- pluralSeparator: "_",
1826
- contextSeparator: "_",
1827
- partialBundledLanguages: false,
1828
- saveMissing: false,
1829
- updateMissing: false,
1830
- saveMissingTo: "fallback",
1831
- saveMissingPlurals: true,
1832
- missingKeyHandler: false,
1833
- missingInterpolationHandler: false,
1834
- postProcess: false,
1835
- postProcessPassResolved: false,
1836
- returnNull: false,
1837
- returnEmptyString: true,
1838
- returnObjects: false,
1839
- joinArrays: false,
1840
- returnedObjectHandler: false,
1841
- parseMissingKeyHandler: false,
1842
- appendNamespaceToMissingKey: false,
1843
- appendNamespaceToCIMode: false,
1844
- overloadTranslationOptionHandler: (args) => {
1845
- let ret = {};
1846
- if (typeof args[1] === "object") ret = args[1];
1847
- if (isString(args[1])) ret.defaultValue = args[1];
1848
- if (isString(args[2])) ret.tDescription = args[2];
1849
- if (typeof args[2] === "object" || typeof args[3] === "object") {
1850
- const options = args[3] || args[2];
1851
- Object.keys(options).forEach((key) => {
1852
- ret[key] = options[key];
1853
- });
1854
- }
1855
- return ret;
1856
- },
1857
- interpolation: {
1858
- escapeValue: true,
1859
- format: (value) => value,
1860
- prefix: "{{",
1861
- suffix: "}}",
1862
- formatSeparator: ",",
1863
- unescapePrefix: "-",
1864
- nestingPrefix: "$t(",
1865
- nestingSuffix: ")",
1866
- nestingOptionsSeparator: ",",
1867
- maxReplaces: 1e3,
1868
- skipOnVariables: true
1869
- }
1870
- });
1871
- var transformOptions = (options) => {
1872
- if (isString(options.ns)) options.ns = [options.ns];
1873
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1874
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1875
- if (options.supportedLngs && options.supportedLngs.indexOf("cimode") < 0) {
1876
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1877
- }
1878
- return options;
1879
- };
1880
- var noop = () => {
1881
- };
1882
- var bindMemberFunctions = (inst) => {
1883
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1884
- mems.forEach((mem) => {
1885
- if (typeof inst[mem] === "function") {
1886
- inst[mem] = inst[mem].bind(inst);
1887
- }
1888
- });
1889
- };
1890
- var I18n = class _I18n extends EventEmitter {
1891
- constructor() {
1892
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1893
- let callback = arguments.length > 1 ? arguments[1] : void 0;
1894
- super();
1895
- this.options = transformOptions(options);
1896
- this.services = {};
1897
- this.logger = baseLogger;
1898
- this.modules = {
1899
- external: []
1900
- };
1901
- bindMemberFunctions(this);
1902
- if (callback && !this.isInitialized && !options.isClone) {
1903
- if (!this.options.initImmediate) {
1904
- this.init(options, callback);
1905
- return this;
1906
- }
1907
- setTimeout(() => {
1908
- this.init(options, callback);
1909
- }, 0);
1910
- }
1911
- }
1912
- init() {
1913
- var _this = this;
1914
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1915
- let callback = arguments.length > 1 ? arguments[1] : void 0;
1916
- this.isInitializing = true;
1917
- if (typeof options === "function") {
1918
- callback = options;
1919
- options = {};
1920
- }
1921
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
1922
- if (isString(options.ns)) {
1923
- options.defaultNS = options.ns;
1924
- } else if (options.ns.indexOf("translation") < 0) {
1925
- options.defaultNS = options.ns[0];
1926
- }
1927
- }
1928
- const defOpts = get();
1929
- this.options = {
1930
- ...defOpts,
1931
- ...this.options,
1932
- ...transformOptions(options)
1933
- };
1934
- if (this.options.compatibilityAPI !== "v1") {
1935
- this.options.interpolation = {
1936
- ...defOpts.interpolation,
1937
- ...this.options.interpolation
1938
- };
1939
- }
1940
- if (options.keySeparator !== void 0) {
1941
- this.options.userDefinedKeySeparator = options.keySeparator;
1942
- }
1943
- if (options.nsSeparator !== void 0) {
1944
- this.options.userDefinedNsSeparator = options.nsSeparator;
1945
- }
1946
- const createClassOnDemand = (ClassOrObject) => {
1947
- if (!ClassOrObject) return null;
1948
- if (typeof ClassOrObject === "function") return new ClassOrObject();
1949
- return ClassOrObject;
1950
- };
1951
- if (!this.options.isClone) {
1952
- if (this.modules.logger) {
1953
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1954
- } else {
1955
- baseLogger.init(null, this.options);
1956
- }
1957
- let formatter;
1958
- if (this.modules.formatter) {
1959
- formatter = this.modules.formatter;
1960
- } else if (typeof Intl !== "undefined") {
1961
- formatter = Formatter;
1962
- }
1963
- const lu = new LanguageUtil(this.options);
1964
- this.store = new ResourceStore(this.options.resources, this.options);
1965
- const s = this.services;
1966
- s.logger = baseLogger;
1967
- s.resourceStore = this.store;
1968
- s.languageUtils = lu;
1969
- s.pluralResolver = new PluralResolver(lu, {
1970
- prepend: this.options.pluralSeparator,
1971
- compatibilityJSON: this.options.compatibilityJSON,
1972
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1973
- });
1974
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1975
- s.formatter = createClassOnDemand(formatter);
1976
- s.formatter.init(s, this.options);
1977
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1978
- }
1979
- s.interpolator = new Interpolator(this.options);
1980
- s.utils = {
1981
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1982
- };
1983
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1984
- s.backendConnector.on("*", function(event) {
1985
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1986
- args[_key - 1] = arguments[_key];
1987
- }
1988
- _this.emit(event, ...args);
1989
- });
1990
- if (this.modules.languageDetector) {
1991
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1992
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1993
- }
1994
- if (this.modules.i18nFormat) {
1995
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1996
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1997
- }
1998
- this.translator = new Translator(this.services, this.options);
1999
- this.translator.on("*", function(event) {
2000
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2001
- args[_key2 - 1] = arguments[_key2];
2002
- }
2003
- _this.emit(event, ...args);
2004
- });
2005
- this.modules.external.forEach((m) => {
2006
- if (m.init) m.init(this);
2007
- });
2008
- }
2009
- this.format = this.options.interpolation.format;
2010
- if (!callback) callback = noop;
2011
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2012
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2013
- if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
2014
- }
2015
- if (!this.services.languageDetector && !this.options.lng) {
2016
- this.logger.warn("init: no languageDetector is used and no lng is defined");
2017
- }
2018
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
2019
- storeApi.forEach((fcName) => {
2020
- this[fcName] = function() {
2021
- return _this.store[fcName](...arguments);
2022
- };
2023
- });
2024
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
2025
- storeApiChained.forEach((fcName) => {
2026
- this[fcName] = function() {
2027
- _this.store[fcName](...arguments);
2028
- return _this;
2029
- };
2030
- });
2031
- const deferred = defer();
2032
- const load = () => {
2033
- const finish = (err, t2) => {
2034
- this.isInitializing = false;
2035
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
2036
- this.isInitialized = true;
2037
- if (!this.options.isClone) this.logger.log("initialized", this.options);
2038
- this.emit("initialized", this.options);
2039
- deferred.resolve(t2);
2040
- callback(err, t2);
2041
- };
2042
- if (this.languages && this.options.compatibilityAPI !== "v1" && !this.isInitialized) return finish(null, this.t.bind(this));
2043
- this.changeLanguage(this.options.lng, finish);
2044
- };
2045
- if (this.options.resources || !this.options.initImmediate) {
2046
- load();
2047
- } else {
2048
- setTimeout(load, 0);
2049
- }
2050
- return deferred;
2051
- }
2052
- loadResources(language) {
2053
- let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
2054
- let usedCallback = callback;
2055
- const usedLng = isString(language) ? language : this.language;
2056
- if (typeof language === "function") usedCallback = language;
2057
- if (!this.options.resources || this.options.partialBundledLanguages) {
2058
- if (usedLng && usedLng.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
2059
- const toLoad = [];
2060
- const append = (lng) => {
2061
- if (!lng) return;
2062
- if (lng === "cimode") return;
2063
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
2064
- lngs.forEach((l) => {
2065
- if (l === "cimode") return;
2066
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
2067
- });
2068
- };
2069
- if (!usedLng) {
2070
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2071
- fallbacks.forEach((l) => append(l));
2072
- } else {
2073
- append(usedLng);
2074
- }
2075
- if (this.options.preload) {
2076
- this.options.preload.forEach((l) => append(l));
2077
- }
2078
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
2079
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
2080
- usedCallback(e);
2081
- });
2082
- } else {
2083
- usedCallback(null);
2084
- }
2085
- }
2086
- reloadResources(lngs, ns, callback) {
2087
- const deferred = defer();
2088
- if (typeof lngs === "function") {
2089
- callback = lngs;
2090
- lngs = void 0;
2091
- }
2092
- if (typeof ns === "function") {
2093
- callback = ns;
2094
- ns = void 0;
2095
- }
2096
- if (!lngs) lngs = this.languages;
2097
- if (!ns) ns = this.options.ns;
2098
- if (!callback) callback = noop;
2099
- this.services.backendConnector.reload(lngs, ns, (err) => {
2100
- deferred.resolve();
2101
- callback(err);
2102
- });
2103
- return deferred;
2104
- }
2105
- use(module) {
2106
- if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
2107
- if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
2108
- if (module.type === "backend") {
2109
- this.modules.backend = module;
2110
- }
2111
- if (module.type === "logger" || module.log && module.warn && module.error) {
2112
- this.modules.logger = module;
2113
- }
2114
- if (module.type === "languageDetector") {
2115
- this.modules.languageDetector = module;
2116
- }
2117
- if (module.type === "i18nFormat") {
2118
- this.modules.i18nFormat = module;
2119
- }
2120
- if (module.type === "postProcessor") {
2121
- postProcessor.addPostProcessor(module);
2122
- }
2123
- if (module.type === "formatter") {
2124
- this.modules.formatter = module;
2125
- }
2126
- if (module.type === "3rdParty") {
2127
- this.modules.external.push(module);
2128
- }
2129
- return this;
2130
- }
2131
- setResolvedLanguage(l) {
2132
- if (!l || !this.languages) return;
2133
- if (["cimode", "dev"].indexOf(l) > -1) return;
2134
- for (let li = 0; li < this.languages.length; li++) {
2135
- const lngInLngs = this.languages[li];
2136
- if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
2137
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2138
- this.resolvedLanguage = lngInLngs;
2139
- break;
2140
- }
2141
- }
2142
- }
2143
- changeLanguage(lng, callback) {
2144
- var _this2 = this;
2145
- this.isLanguageChangingTo = lng;
2146
- const deferred = defer();
2147
- this.emit("languageChanging", lng);
2148
- const setLngProps = (l) => {
2149
- this.language = l;
2150
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2151
- this.resolvedLanguage = void 0;
2152
- this.setResolvedLanguage(l);
2153
- };
2154
- const done = (err, l) => {
2155
- if (l) {
2156
- setLngProps(l);
2157
- this.translator.changeLanguage(l);
2158
- this.isLanguageChangingTo = void 0;
2159
- this.emit("languageChanged", l);
2160
- this.logger.log("languageChanged", l);
2161
- } else {
2162
- this.isLanguageChangingTo = void 0;
2163
- }
2164
- deferred.resolve(function() {
2165
- return _this2.t(...arguments);
2166
- });
2167
- if (callback) callback(err, function() {
2168
- return _this2.t(...arguments);
2169
- });
2170
- };
2171
- const setLng = (lngs) => {
2172
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2173
- const l = isString(lngs) ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
2174
- if (l) {
2175
- if (!this.language) {
2176
- setLngProps(l);
2177
- }
2178
- if (!this.translator.language) this.translator.changeLanguage(l);
2179
- if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
2180
- }
2181
- this.loadResources(l, (err) => {
2182
- done(err, l);
2183
- });
2184
- };
2185
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2186
- setLng(this.services.languageDetector.detect());
2187
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2188
- if (this.services.languageDetector.detect.length === 0) {
2189
- this.services.languageDetector.detect().then(setLng);
2190
- } else {
2191
- this.services.languageDetector.detect(setLng);
2192
- }
2193
- } else {
2194
- setLng(lng);
2195
- }
2196
- return deferred;
2197
- }
2198
- getFixedT(lng, ns, keyPrefix) {
2199
- var _this3 = this;
2200
- const fixedT = function(key, opts) {
2201
- let options;
2202
- if (typeof opts !== "object") {
2203
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2204
- rest[_key3 - 2] = arguments[_key3];
2205
- }
2206
- options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2207
- } else {
2208
- options = {
2209
- ...opts
2210
- };
2211
- }
2212
- options.lng = options.lng || fixedT.lng;
2213
- options.lngs = options.lngs || fixedT.lngs;
2214
- options.ns = options.ns || fixedT.ns;
2215
- if (options.keyPrefix !== "") options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2216
- const keySeparator = _this3.options.keySeparator || ".";
2217
- let resultKey;
2218
- if (options.keyPrefix && Array.isArray(key)) {
2219
- resultKey = key.map((k) => `${options.keyPrefix}${keySeparator}${k}`);
2220
- } else {
2221
- resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
2222
- }
2223
- return _this3.t(resultKey, options);
2224
- };
2225
- if (isString(lng)) {
2226
- fixedT.lng = lng;
2227
- } else {
2228
- fixedT.lngs = lng;
2229
- }
2230
- fixedT.ns = ns;
2231
- fixedT.keyPrefix = keyPrefix;
2232
- return fixedT;
2233
- }
2234
- t() {
2235
- return this.translator && this.translator.translate(...arguments);
2236
- }
2237
- exists() {
2238
- return this.translator && this.translator.exists(...arguments);
2239
- }
2240
- setDefaultNamespace(ns) {
2241
- this.options.defaultNS = ns;
2242
- }
2243
- hasLoadedNamespace(ns) {
2244
- let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2245
- if (!this.isInitialized) {
2246
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2247
- return false;
2248
- }
2249
- if (!this.languages || !this.languages.length) {
2250
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2251
- return false;
2252
- }
2253
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2254
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2255
- const lastLng = this.languages[this.languages.length - 1];
2256
- if (lng.toLowerCase() === "cimode") return true;
2257
- const loadNotPending = (l, n) => {
2258
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2259
- return loadState === -1 || loadState === 0 || loadState === 2;
2260
- };
2261
- if (options.precheck) {
2262
- const preResult = options.precheck(this, loadNotPending);
2263
- if (preResult !== void 0) return preResult;
2264
- }
2265
- if (this.hasResourceBundle(lng, ns)) return true;
2266
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2267
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2268
- return false;
2269
- }
2270
- loadNamespaces(ns, callback) {
2271
- const deferred = defer();
2272
- if (!this.options.ns) {
2273
- if (callback) callback();
2274
- return Promise.resolve();
2275
- }
2276
- if (isString(ns)) ns = [ns];
2277
- ns.forEach((n) => {
2278
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2279
- });
2280
- this.loadResources((err) => {
2281
- deferred.resolve();
2282
- if (callback) callback(err);
2283
- });
2284
- return deferred;
2285
- }
2286
- loadLanguages(lngs, callback) {
2287
- const deferred = defer();
2288
- if (isString(lngs)) lngs = [lngs];
2289
- const preloaded = this.options.preload || [];
2290
- const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2291
- if (!newLngs.length) {
2292
- if (callback) callback();
2293
- return Promise.resolve();
2294
- }
2295
- this.options.preload = preloaded.concat(newLngs);
2296
- this.loadResources((err) => {
2297
- deferred.resolve();
2298
- if (callback) callback(err);
2299
- });
2300
- return deferred;
2301
- }
2302
- dir(lng) {
2303
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
2304
- if (!lng) return "rtl";
2305
- const 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"];
2306
- const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
2307
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2308
- }
2309
- static createInstance() {
2310
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2311
- let callback = arguments.length > 1 ? arguments[1] : void 0;
2312
- return new _I18n(options, callback);
2313
- }
2314
- cloneInstance() {
2315
- let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2316
- let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
2317
- const forkResourceStore = options.forkResourceStore;
2318
- if (forkResourceStore) delete options.forkResourceStore;
2319
- const mergedOptions = {
2320
- ...this.options,
2321
- ...options,
2322
- ...{
2323
- isClone: true
2324
- }
2325
- };
2326
- const clone = new _I18n(mergedOptions);
2327
- if (options.debug !== void 0 || options.prefix !== void 0) {
2328
- clone.logger = clone.logger.clone(options);
2329
- }
2330
- const membersToCopy = ["store", "services", "language"];
2331
- membersToCopy.forEach((m) => {
2332
- clone[m] = this[m];
2333
- });
2334
- clone.services = {
2335
- ...this.services
2336
- };
2337
- clone.services.utils = {
2338
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2339
- };
2340
- if (forkResourceStore) {
2341
- clone.store = new ResourceStore(this.store.data, mergedOptions);
2342
- clone.services.resourceStore = clone.store;
2343
- }
2344
- clone.translator = new Translator(clone.services, mergedOptions);
2345
- clone.translator.on("*", function(event) {
2346
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
2347
- args[_key4 - 1] = arguments[_key4];
2348
- }
2349
- clone.emit(event, ...args);
2350
- });
2351
- clone.init(mergedOptions, callback);
2352
- clone.translator.options = mergedOptions;
2353
- clone.translator.backendConnector.services.utils = {
2354
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2355
- };
2356
- return clone;
2357
- }
2358
- toJSON() {
2359
- return {
2360
- options: this.options,
2361
- store: this.store,
2362
- language: this.language,
2363
- languages: this.languages,
2364
- resolvedLanguage: this.resolvedLanguage
2365
- };
2366
- }
2367
- };
2368
- var instance = I18n.createInstance();
2369
- instance.createInstance = I18n.createInstance;
2370
- instance.createInstance;
2371
- instance.dir;
2372
- instance.init;
2373
- instance.loadResources;
2374
- instance.reloadResources;
2375
- instance.use;
2376
- instance.changeLanguage;
2377
- instance.getFixedT;
2378
- instance.t;
2379
- instance.exists;
2380
- instance.setDefaultNamespace;
2381
- instance.hasLoadedNamespace;
2382
- instance.loadNamespaces;
2383
- instance.loadLanguages;
14
+ // src/i18n.ts
2384
15
 
2385
16
  // src/locales/en/translation.ts
2386
17
  var translationEN = {
@@ -3994,7 +1625,7 @@ var resources = {
3994
1625
  translation: translationVI
3995
1626
  }
3996
1627
  };
3997
- instance.use(LanguageDetector__default.default).use(reactI18next.initReactI18next).init({
1628
+ i18n__default.default.use(LanguageDetector__default.default).use(reactI18next.initReactI18next).init({
3998
1629
  resources,
3999
1630
  fallbackLng: "en",
4000
1631
  // Use English if the detected language is not available
@@ -4019,7 +1650,7 @@ instance.use(LanguageDetector__default.default).use(reactI18next.initReactI18nex
4019
1650
  // Set to false for simpler integration without React.Suspense
4020
1651
  }
4021
1652
  });
4022
- var i18n_default = instance;
1653
+ var i18n_default = i18n__default.default;
4023
1654
 
4024
1655
  exports.default = i18n_default;
4025
1656
  exports.translationEN = translationEN;