@pie-element/math-inline 11.0.0-next.42 → 11.0.0-next.43

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.
@@ -0,0 +1,3857 @@
1
+ import * as mv from '@pie-framework/math-validation';
2
+
3
+ var debug = () => () => {};
4
+
5
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
+
7
+ /** Used for built-in method references. */
8
+
9
+ var objectProto$6 = Object.prototype;
10
+
11
+ /**
12
+ * Checks if `value` is likely a prototype object.
13
+ *
14
+ * @private
15
+ * @param {*} value The value to check.
16
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
17
+ */
18
+ function isPrototype$2(value) {
19
+ var Ctor = value && value.constructor,
20
+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$6;
21
+
22
+ return value === proto;
23
+ }
24
+
25
+ var _isPrototype = isPrototype$2;
26
+
27
+ /**
28
+ * Creates a unary function that invokes `func` with its argument transformed.
29
+ *
30
+ * @private
31
+ * @param {Function} func The function to wrap.
32
+ * @param {Function} transform The argument transform.
33
+ * @returns {Function} Returns the new function.
34
+ */
35
+
36
+ function overArg$1(func, transform) {
37
+ return function(arg) {
38
+ return func(transform(arg));
39
+ };
40
+ }
41
+
42
+ var _overArg = overArg$1;
43
+
44
+ var overArg = _overArg;
45
+
46
+ /* Built-in method references for those with the same name as other `lodash` methods. */
47
+ var nativeKeys$1 = overArg(Object.keys, Object);
48
+
49
+ var _nativeKeys = nativeKeys$1;
50
+
51
+ var isPrototype$1 = _isPrototype,
52
+ nativeKeys = _nativeKeys;
53
+
54
+ /** Used for built-in method references. */
55
+ var objectProto$5 = Object.prototype;
56
+
57
+ /** Used to check objects for own properties. */
58
+ var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
59
+
60
+ /**
61
+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
62
+ *
63
+ * @private
64
+ * @param {Object} object The object to query.
65
+ * @returns {Array} Returns the array of property names.
66
+ */
67
+ function baseKeys$1(object) {
68
+ if (!isPrototype$1(object)) {
69
+ return nativeKeys(object);
70
+ }
71
+ var result = [];
72
+ for (var key in Object(object)) {
73
+ if (hasOwnProperty$4.call(object, key) && key != 'constructor') {
74
+ result.push(key);
75
+ }
76
+ }
77
+ return result;
78
+ }
79
+
80
+ var _baseKeys = baseKeys$1;
81
+
82
+ /** Detect free variable `global` from Node.js. */
83
+
84
+ var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
85
+
86
+ var _freeGlobal = freeGlobal$1;
87
+
88
+ var freeGlobal = _freeGlobal;
89
+
90
+ /** Detect free variable `self`. */
91
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
92
+
93
+ /** Used as a reference to the global object. */
94
+ var root$7 = freeGlobal || freeSelf || Function('return this')();
95
+
96
+ var _root = root$7;
97
+
98
+ var root$6 = _root;
99
+
100
+ /** Built-in value references. */
101
+ var Symbol$3 = root$6.Symbol;
102
+
103
+ var _Symbol = Symbol$3;
104
+
105
+ var Symbol$2 = _Symbol;
106
+
107
+ /** Used for built-in method references. */
108
+ var objectProto$4 = Object.prototype;
109
+
110
+ /** Used to check objects for own properties. */
111
+ var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
112
+
113
+ /**
114
+ * Used to resolve the
115
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
116
+ * of values.
117
+ */
118
+ var nativeObjectToString$1 = objectProto$4.toString;
119
+
120
+ /** Built-in value references. */
121
+ var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : undefined;
122
+
123
+ /**
124
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
125
+ *
126
+ * @private
127
+ * @param {*} value The value to query.
128
+ * @returns {string} Returns the raw `toStringTag`.
129
+ */
130
+ function getRawTag$1(value) {
131
+ var isOwn = hasOwnProperty$3.call(value, symToStringTag$1),
132
+ tag = value[symToStringTag$1];
133
+
134
+ try {
135
+ value[symToStringTag$1] = undefined;
136
+ var unmasked = true;
137
+ } catch (e) {}
138
+
139
+ var result = nativeObjectToString$1.call(value);
140
+ if (unmasked) {
141
+ if (isOwn) {
142
+ value[symToStringTag$1] = tag;
143
+ } else {
144
+ delete value[symToStringTag$1];
145
+ }
146
+ }
147
+ return result;
148
+ }
149
+
150
+ var _getRawTag = getRawTag$1;
151
+
152
+ /** Used for built-in method references. */
153
+
154
+ var objectProto$3 = Object.prototype;
155
+
156
+ /**
157
+ * Used to resolve the
158
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
159
+ * of values.
160
+ */
161
+ var nativeObjectToString = objectProto$3.toString;
162
+
163
+ /**
164
+ * Converts `value` to a string using `Object.prototype.toString`.
165
+ *
166
+ * @private
167
+ * @param {*} value The value to convert.
168
+ * @returns {string} Returns the converted string.
169
+ */
170
+ function objectToString$1(value) {
171
+ return nativeObjectToString.call(value);
172
+ }
173
+
174
+ var _objectToString = objectToString$1;
175
+
176
+ var Symbol$1 = _Symbol,
177
+ getRawTag = _getRawTag,
178
+ objectToString = _objectToString;
179
+
180
+ /** `Object#toString` result references. */
181
+ var nullTag = '[object Null]',
182
+ undefinedTag = '[object Undefined]';
183
+
184
+ /** Built-in value references. */
185
+ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
186
+
187
+ /**
188
+ * The base implementation of `getTag` without fallbacks for buggy environments.
189
+ *
190
+ * @private
191
+ * @param {*} value The value to query.
192
+ * @returns {string} Returns the `toStringTag`.
193
+ */
194
+ function baseGetTag$4(value) {
195
+ if (value == null) {
196
+ return value === undefined ? undefinedTag : nullTag;
197
+ }
198
+ return (symToStringTag && symToStringTag in Object(value))
199
+ ? getRawTag(value)
200
+ : objectToString(value);
201
+ }
202
+
203
+ var _baseGetTag = baseGetTag$4;
204
+
205
+ /**
206
+ * Checks if `value` is the
207
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
208
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
209
+ *
210
+ * @static
211
+ * @memberOf _
212
+ * @since 0.1.0
213
+ * @category Lang
214
+ * @param {*} value The value to check.
215
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
216
+ * @example
217
+ *
218
+ * _.isObject({});
219
+ * // => true
220
+ *
221
+ * _.isObject([1, 2, 3]);
222
+ * // => true
223
+ *
224
+ * _.isObject(_.noop);
225
+ * // => true
226
+ *
227
+ * _.isObject(null);
228
+ * // => false
229
+ */
230
+
231
+ function isObject$2(value) {
232
+ var type = typeof value;
233
+ return value != null && (type == 'object' || type == 'function');
234
+ }
235
+
236
+ var isObject_1 = isObject$2;
237
+
238
+ var baseGetTag$3 = _baseGetTag,
239
+ isObject$1 = isObject_1;
240
+
241
+ /** `Object#toString` result references. */
242
+ var asyncTag = '[object AsyncFunction]',
243
+ funcTag$1 = '[object Function]',
244
+ genTag = '[object GeneratorFunction]',
245
+ proxyTag = '[object Proxy]';
246
+
247
+ /**
248
+ * Checks if `value` is classified as a `Function` object.
249
+ *
250
+ * @static
251
+ * @memberOf _
252
+ * @since 0.1.0
253
+ * @category Lang
254
+ * @param {*} value The value to check.
255
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
256
+ * @example
257
+ *
258
+ * _.isFunction(_);
259
+ * // => true
260
+ *
261
+ * _.isFunction(/abc/);
262
+ * // => false
263
+ */
264
+ function isFunction$2(value) {
265
+ if (!isObject$1(value)) {
266
+ return false;
267
+ }
268
+ // The use of `Object#toString` avoids issues with the `typeof` operator
269
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
270
+ var tag = baseGetTag$3(value);
271
+ return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
272
+ }
273
+
274
+ var isFunction_1 = isFunction$2;
275
+
276
+ var root$5 = _root;
277
+
278
+ /** Used to detect overreaching core-js shims. */
279
+ var coreJsData$1 = root$5['__core-js_shared__'];
280
+
281
+ var _coreJsData = coreJsData$1;
282
+
283
+ var coreJsData = _coreJsData;
284
+
285
+ /** Used to detect methods masquerading as native. */
286
+ var maskSrcKey = (function() {
287
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
288
+ return uid ? ('Symbol(src)_1.' + uid) : '';
289
+ }());
290
+
291
+ /**
292
+ * Checks if `func` has its source masked.
293
+ *
294
+ * @private
295
+ * @param {Function} func The function to check.
296
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
297
+ */
298
+ function isMasked$1(func) {
299
+ return !!maskSrcKey && (maskSrcKey in func);
300
+ }
301
+
302
+ var _isMasked = isMasked$1;
303
+
304
+ /** Used for built-in method references. */
305
+
306
+ var funcProto$1 = Function.prototype;
307
+
308
+ /** Used to resolve the decompiled source of functions. */
309
+ var funcToString$1 = funcProto$1.toString;
310
+
311
+ /**
312
+ * Converts `func` to its source code.
313
+ *
314
+ * @private
315
+ * @param {Function} func The function to convert.
316
+ * @returns {string} Returns the source code.
317
+ */
318
+ function toSource$2(func) {
319
+ if (func != null) {
320
+ try {
321
+ return funcToString$1.call(func);
322
+ } catch (e) {}
323
+ try {
324
+ return (func + '');
325
+ } catch (e) {}
326
+ }
327
+ return '';
328
+ }
329
+
330
+ var _toSource = toSource$2;
331
+
332
+ var isFunction$1 = isFunction_1,
333
+ isMasked = _isMasked,
334
+ isObject = isObject_1,
335
+ toSource$1 = _toSource;
336
+
337
+ /**
338
+ * Used to match `RegExp`
339
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
340
+ */
341
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
342
+
343
+ /** Used to detect host constructors (Safari). */
344
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
345
+
346
+ /** Used for built-in method references. */
347
+ var funcProto = Function.prototype,
348
+ objectProto$2 = Object.prototype;
349
+
350
+ /** Used to resolve the decompiled source of functions. */
351
+ var funcToString = funcProto.toString;
352
+
353
+ /** Used to check objects for own properties. */
354
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
355
+
356
+ /** Used to detect if a method is native. */
357
+ var reIsNative = RegExp('^' +
358
+ funcToString.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
359
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
360
+ );
361
+
362
+ /**
363
+ * The base implementation of `_.isNative` without bad shim checks.
364
+ *
365
+ * @private
366
+ * @param {*} value The value to check.
367
+ * @returns {boolean} Returns `true` if `value` is a native function,
368
+ * else `false`.
369
+ */
370
+ function baseIsNative$1(value) {
371
+ if (!isObject(value) || isMasked(value)) {
372
+ return false;
373
+ }
374
+ var pattern = isFunction$1(value) ? reIsNative : reIsHostCtor;
375
+ return pattern.test(toSource$1(value));
376
+ }
377
+
378
+ var _baseIsNative = baseIsNative$1;
379
+
380
+ /**
381
+ * Gets the value at `key` of `object`.
382
+ *
383
+ * @private
384
+ * @param {Object} [object] The object to query.
385
+ * @param {string} key The key of the property to get.
386
+ * @returns {*} Returns the property value.
387
+ */
388
+
389
+ function getValue$1(object, key) {
390
+ return object == null ? undefined : object[key];
391
+ }
392
+
393
+ var _getValue = getValue$1;
394
+
395
+ var baseIsNative = _baseIsNative,
396
+ getValue = _getValue;
397
+
398
+ /**
399
+ * Gets the native function at `key` of `object`.
400
+ *
401
+ * @private
402
+ * @param {Object} object The object to query.
403
+ * @param {string} key The key of the method to get.
404
+ * @returns {*} Returns the function if it's native, else `undefined`.
405
+ */
406
+ function getNative$5(object, key) {
407
+ var value = getValue(object, key);
408
+ return baseIsNative(value) ? value : undefined;
409
+ }
410
+
411
+ var _getNative = getNative$5;
412
+
413
+ var getNative$4 = _getNative,
414
+ root$4 = _root;
415
+
416
+ /* Built-in method references that are verified to be native. */
417
+ var DataView$1 = getNative$4(root$4, 'DataView');
418
+
419
+ var _DataView = DataView$1;
420
+
421
+ var getNative$3 = _getNative,
422
+ root$3 = _root;
423
+
424
+ /* Built-in method references that are verified to be native. */
425
+ var Map$2 = getNative$3(root$3, 'Map');
426
+
427
+ var _Map = Map$2;
428
+
429
+ var getNative$2 = _getNative,
430
+ root$2 = _root;
431
+
432
+ /* Built-in method references that are verified to be native. */
433
+ var Promise$2 = getNative$2(root$2, 'Promise');
434
+
435
+ var _Promise = Promise$2;
436
+
437
+ var getNative$1 = _getNative,
438
+ root$1 = _root;
439
+
440
+ /* Built-in method references that are verified to be native. */
441
+ var Set$1 = getNative$1(root$1, 'Set');
442
+
443
+ var _Set = Set$1;
444
+
445
+ var getNative = _getNative,
446
+ root = _root;
447
+
448
+ /* Built-in method references that are verified to be native. */
449
+ var WeakMap$1 = getNative(root, 'WeakMap');
450
+
451
+ var _WeakMap = WeakMap$1;
452
+
453
+ var DataView = _DataView,
454
+ Map$1 = _Map,
455
+ Promise$1 = _Promise,
456
+ Set = _Set,
457
+ WeakMap = _WeakMap,
458
+ baseGetTag$2 = _baseGetTag,
459
+ toSource = _toSource;
460
+
461
+ /** `Object#toString` result references. */
462
+ var mapTag$2 = '[object Map]',
463
+ objectTag$1 = '[object Object]',
464
+ promiseTag = '[object Promise]',
465
+ setTag$2 = '[object Set]',
466
+ weakMapTag$1 = '[object WeakMap]';
467
+
468
+ var dataViewTag$1 = '[object DataView]';
469
+
470
+ /** Used to detect maps, sets, and weakmaps. */
471
+ var dataViewCtorString = toSource(DataView),
472
+ mapCtorString = toSource(Map$1),
473
+ promiseCtorString = toSource(Promise$1),
474
+ setCtorString = toSource(Set),
475
+ weakMapCtorString = toSource(WeakMap);
476
+
477
+ /**
478
+ * Gets the `toStringTag` of `value`.
479
+ *
480
+ * @private
481
+ * @param {*} value The value to query.
482
+ * @returns {string} Returns the `toStringTag`.
483
+ */
484
+ var getTag$1 = baseGetTag$2;
485
+
486
+ // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
487
+ if ((DataView && getTag$1(new DataView(new ArrayBuffer(1))) != dataViewTag$1) ||
488
+ (Map$1 && getTag$1(new Map$1) != mapTag$2) ||
489
+ (Promise$1 && getTag$1(Promise$1.resolve()) != promiseTag) ||
490
+ (Set && getTag$1(new Set) != setTag$2) ||
491
+ (WeakMap && getTag$1(new WeakMap) != weakMapTag$1)) {
492
+ getTag$1 = function(value) {
493
+ var result = baseGetTag$2(value),
494
+ Ctor = result == objectTag$1 ? value.constructor : undefined,
495
+ ctorString = Ctor ? toSource(Ctor) : '';
496
+
497
+ if (ctorString) {
498
+ switch (ctorString) {
499
+ case dataViewCtorString: return dataViewTag$1;
500
+ case mapCtorString: return mapTag$2;
501
+ case promiseCtorString: return promiseTag;
502
+ case setCtorString: return setTag$2;
503
+ case weakMapCtorString: return weakMapTag$1;
504
+ }
505
+ }
506
+ return result;
507
+ };
508
+ }
509
+
510
+ var _getTag = getTag$1;
511
+
512
+ /**
513
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
514
+ * and has a `typeof` result of "object".
515
+ *
516
+ * @static
517
+ * @memberOf _
518
+ * @since 4.0.0
519
+ * @category Lang
520
+ * @param {*} value The value to check.
521
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
522
+ * @example
523
+ *
524
+ * _.isObjectLike({});
525
+ * // => true
526
+ *
527
+ * _.isObjectLike([1, 2, 3]);
528
+ * // => true
529
+ *
530
+ * _.isObjectLike(_.noop);
531
+ * // => false
532
+ *
533
+ * _.isObjectLike(null);
534
+ * // => false
535
+ */
536
+
537
+ function isObjectLike$3(value) {
538
+ return value != null && typeof value == 'object';
539
+ }
540
+
541
+ var isObjectLike_1 = isObjectLike$3;
542
+
543
+ var baseGetTag$1 = _baseGetTag,
544
+ isObjectLike$2 = isObjectLike_1;
545
+
546
+ /** `Object#toString` result references. */
547
+ var argsTag$1 = '[object Arguments]';
548
+
549
+ /**
550
+ * The base implementation of `_.isArguments`.
551
+ *
552
+ * @private
553
+ * @param {*} value The value to check.
554
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
555
+ */
556
+ function baseIsArguments$1(value) {
557
+ return isObjectLike$2(value) && baseGetTag$1(value) == argsTag$1;
558
+ }
559
+
560
+ var _baseIsArguments = baseIsArguments$1;
561
+
562
+ var baseIsArguments = _baseIsArguments,
563
+ isObjectLike$1 = isObjectLike_1;
564
+
565
+ /** Used for built-in method references. */
566
+ var objectProto$1 = Object.prototype;
567
+
568
+ /** Used to check objects for own properties. */
569
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
570
+
571
+ /** Built-in value references. */
572
+ var propertyIsEnumerable = objectProto$1.propertyIsEnumerable;
573
+
574
+ /**
575
+ * Checks if `value` is likely an `arguments` object.
576
+ *
577
+ * @static
578
+ * @memberOf _
579
+ * @since 0.1.0
580
+ * @category Lang
581
+ * @param {*} value The value to check.
582
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
583
+ * else `false`.
584
+ * @example
585
+ *
586
+ * _.isArguments(function() { return arguments; }());
587
+ * // => true
588
+ *
589
+ * _.isArguments([1, 2, 3]);
590
+ * // => false
591
+ */
592
+ var isArguments$1 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
593
+ return isObjectLike$1(value) && hasOwnProperty$1.call(value, 'callee') &&
594
+ !propertyIsEnumerable.call(value, 'callee');
595
+ };
596
+
597
+ var isArguments_1 = isArguments$1;
598
+
599
+ /**
600
+ * Checks if `value` is classified as an `Array` object.
601
+ *
602
+ * @static
603
+ * @memberOf _
604
+ * @since 0.1.0
605
+ * @category Lang
606
+ * @param {*} value The value to check.
607
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
608
+ * @example
609
+ *
610
+ * _.isArray([1, 2, 3]);
611
+ * // => true
612
+ *
613
+ * _.isArray(document.body.children);
614
+ * // => false
615
+ *
616
+ * _.isArray('abc');
617
+ * // => false
618
+ *
619
+ * _.isArray(_.noop);
620
+ * // => false
621
+ */
622
+
623
+ var isArray$1 = Array.isArray;
624
+
625
+ var isArray_1 = isArray$1;
626
+
627
+ /** Used as references for various `Number` constants. */
628
+
629
+ var MAX_SAFE_INTEGER = 9007199254740991;
630
+
631
+ /**
632
+ * Checks if `value` is a valid array-like length.
633
+ *
634
+ * **Note:** This method is loosely based on
635
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
636
+ *
637
+ * @static
638
+ * @memberOf _
639
+ * @since 4.0.0
640
+ * @category Lang
641
+ * @param {*} value The value to check.
642
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
643
+ * @example
644
+ *
645
+ * _.isLength(3);
646
+ * // => true
647
+ *
648
+ * _.isLength(Number.MIN_VALUE);
649
+ * // => false
650
+ *
651
+ * _.isLength(Infinity);
652
+ * // => false
653
+ *
654
+ * _.isLength('3');
655
+ * // => false
656
+ */
657
+ function isLength$2(value) {
658
+ return typeof value == 'number' &&
659
+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
660
+ }
661
+
662
+ var isLength_1 = isLength$2;
663
+
664
+ var isFunction = isFunction_1,
665
+ isLength$1 = isLength_1;
666
+
667
+ /**
668
+ * Checks if `value` is array-like. A value is considered array-like if it's
669
+ * not a function and has a `value.length` that's an integer greater than or
670
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
671
+ *
672
+ * @static
673
+ * @memberOf _
674
+ * @since 4.0.0
675
+ * @category Lang
676
+ * @param {*} value The value to check.
677
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
678
+ * @example
679
+ *
680
+ * _.isArrayLike([1, 2, 3]);
681
+ * // => true
682
+ *
683
+ * _.isArrayLike(document.body.children);
684
+ * // => true
685
+ *
686
+ * _.isArrayLike('abc');
687
+ * // => true
688
+ *
689
+ * _.isArrayLike(_.noop);
690
+ * // => false
691
+ */
692
+ function isArrayLike$1(value) {
693
+ return value != null && isLength$1(value.length) && !isFunction(value);
694
+ }
695
+
696
+ var isArrayLike_1 = isArrayLike$1;
697
+
698
+ var isBuffer$1 = {exports: {}};
699
+
700
+ /**
701
+ * This method returns `false`.
702
+ *
703
+ * @static
704
+ * @memberOf _
705
+ * @since 4.13.0
706
+ * @category Util
707
+ * @returns {boolean} Returns `false`.
708
+ * @example
709
+ *
710
+ * _.times(2, _.stubFalse);
711
+ * // => [false, false]
712
+ */
713
+
714
+ function stubFalse() {
715
+ return false;
716
+ }
717
+
718
+ var stubFalse_1 = stubFalse;
719
+
720
+ (function (module, exports) {
721
+ var root = _root,
722
+ stubFalse = stubFalse_1;
723
+
724
+ /** Detect free variable `exports`. */
725
+ var freeExports = exports && !exports.nodeType && exports;
726
+
727
+ /** Detect free variable `module`. */
728
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
729
+
730
+ /** Detect the popular CommonJS extension `module.exports`. */
731
+ var moduleExports = freeModule && freeModule.exports === freeExports;
732
+
733
+ /** Built-in value references. */
734
+ var Buffer = moduleExports ? root.Buffer : undefined;
735
+
736
+ /* Built-in method references for those with the same name as other `lodash` methods. */
737
+ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
738
+
739
+ /**
740
+ * Checks if `value` is a buffer.
741
+ *
742
+ * @static
743
+ * @memberOf _
744
+ * @since 4.3.0
745
+ * @category Lang
746
+ * @param {*} value The value to check.
747
+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
748
+ * @example
749
+ *
750
+ * _.isBuffer(new Buffer(2));
751
+ * // => true
752
+ *
753
+ * _.isBuffer(new Uint8Array(2));
754
+ * // => false
755
+ */
756
+ var isBuffer = nativeIsBuffer || stubFalse;
757
+
758
+ module.exports = isBuffer;
759
+ }(isBuffer$1, isBuffer$1.exports));
760
+
761
+ var baseGetTag = _baseGetTag,
762
+ isLength = isLength_1,
763
+ isObjectLike = isObjectLike_1;
764
+
765
+ /** `Object#toString` result references. */
766
+ var argsTag = '[object Arguments]',
767
+ arrayTag = '[object Array]',
768
+ boolTag = '[object Boolean]',
769
+ dateTag = '[object Date]',
770
+ errorTag = '[object Error]',
771
+ funcTag = '[object Function]',
772
+ mapTag$1 = '[object Map]',
773
+ numberTag = '[object Number]',
774
+ objectTag = '[object Object]',
775
+ regexpTag = '[object RegExp]',
776
+ setTag$1 = '[object Set]',
777
+ stringTag = '[object String]',
778
+ weakMapTag = '[object WeakMap]';
779
+
780
+ var arrayBufferTag = '[object ArrayBuffer]',
781
+ dataViewTag = '[object DataView]',
782
+ float32Tag = '[object Float32Array]',
783
+ float64Tag = '[object Float64Array]',
784
+ int8Tag = '[object Int8Array]',
785
+ int16Tag = '[object Int16Array]',
786
+ int32Tag = '[object Int32Array]',
787
+ uint8Tag = '[object Uint8Array]',
788
+ uint8ClampedTag = '[object Uint8ClampedArray]',
789
+ uint16Tag = '[object Uint16Array]',
790
+ uint32Tag = '[object Uint32Array]';
791
+
792
+ /** Used to identify `toStringTag` values of typed arrays. */
793
+ var typedArrayTags = {};
794
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
795
+ typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
796
+ typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
797
+ typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
798
+ typedArrayTags[uint32Tag] = true;
799
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
800
+ typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
801
+ typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
802
+ typedArrayTags[errorTag] = typedArrayTags[funcTag] =
803
+ typedArrayTags[mapTag$1] = typedArrayTags[numberTag] =
804
+ typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
805
+ typedArrayTags[setTag$1] = typedArrayTags[stringTag] =
806
+ typedArrayTags[weakMapTag] = false;
807
+
808
+ /**
809
+ * The base implementation of `_.isTypedArray` without Node.js optimizations.
810
+ *
811
+ * @private
812
+ * @param {*} value The value to check.
813
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
814
+ */
815
+ function baseIsTypedArray$1(value) {
816
+ return isObjectLike(value) &&
817
+ isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
818
+ }
819
+
820
+ var _baseIsTypedArray = baseIsTypedArray$1;
821
+
822
+ /**
823
+ * The base implementation of `_.unary` without support for storing metadata.
824
+ *
825
+ * @private
826
+ * @param {Function} func The function to cap arguments for.
827
+ * @returns {Function} Returns the new capped function.
828
+ */
829
+
830
+ function baseUnary$1(func) {
831
+ return function(value) {
832
+ return func(value);
833
+ };
834
+ }
835
+
836
+ var _baseUnary = baseUnary$1;
837
+
838
+ var _nodeUtil = {exports: {}};
839
+
840
+ (function (module, exports) {
841
+ var freeGlobal = _freeGlobal;
842
+
843
+ /** Detect free variable `exports`. */
844
+ var freeExports = exports && !exports.nodeType && exports;
845
+
846
+ /** Detect free variable `module`. */
847
+ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
848
+
849
+ /** Detect the popular CommonJS extension `module.exports`. */
850
+ var moduleExports = freeModule && freeModule.exports === freeExports;
851
+
852
+ /** Detect free variable `process` from Node.js. */
853
+ var freeProcess = moduleExports && freeGlobal.process;
854
+
855
+ /** Used to access faster Node.js helpers. */
856
+ var nodeUtil = (function() {
857
+ try {
858
+ // Use `util.types` for Node.js 10+.
859
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
860
+
861
+ if (types) {
862
+ return types;
863
+ }
864
+
865
+ // Legacy `process.binding('util')` for Node.js < 10.
866
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
867
+ } catch (e) {}
868
+ }());
869
+
870
+ module.exports = nodeUtil;
871
+ }(_nodeUtil, _nodeUtil.exports));
872
+
873
+ var baseIsTypedArray = _baseIsTypedArray,
874
+ baseUnary = _baseUnary,
875
+ nodeUtil = _nodeUtil.exports;
876
+
877
+ /* Node.js helper references. */
878
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
879
+
880
+ /**
881
+ * Checks if `value` is classified as a typed array.
882
+ *
883
+ * @static
884
+ * @memberOf _
885
+ * @since 3.0.0
886
+ * @category Lang
887
+ * @param {*} value The value to check.
888
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
889
+ * @example
890
+ *
891
+ * _.isTypedArray(new Uint8Array);
892
+ * // => true
893
+ *
894
+ * _.isTypedArray([]);
895
+ * // => false
896
+ */
897
+ var isTypedArray$1 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
898
+
899
+ var isTypedArray_1 = isTypedArray$1;
900
+
901
+ var baseKeys = _baseKeys,
902
+ getTag = _getTag,
903
+ isArguments = isArguments_1,
904
+ isArray = isArray_1,
905
+ isArrayLike = isArrayLike_1,
906
+ isBuffer = isBuffer$1.exports,
907
+ isPrototype = _isPrototype,
908
+ isTypedArray = isTypedArray_1;
909
+
910
+ /** `Object#toString` result references. */
911
+ var mapTag = '[object Map]',
912
+ setTag = '[object Set]';
913
+
914
+ /** Used for built-in method references. */
915
+ var objectProto = Object.prototype;
916
+
917
+ /** Used to check objects for own properties. */
918
+ var hasOwnProperty = objectProto.hasOwnProperty;
919
+
920
+ /**
921
+ * Checks if `value` is an empty object, collection, map, or set.
922
+ *
923
+ * Objects are considered empty if they have no own enumerable string keyed
924
+ * properties.
925
+ *
926
+ * Array-like values such as `arguments` objects, arrays, buffers, strings, or
927
+ * jQuery-like collections are considered empty if they have a `length` of `0`.
928
+ * Similarly, maps and sets are considered empty if they have a `size` of `0`.
929
+ *
930
+ * @static
931
+ * @memberOf _
932
+ * @since 0.1.0
933
+ * @category Lang
934
+ * @param {*} value The value to check.
935
+ * @returns {boolean} Returns `true` if `value` is empty, else `false`.
936
+ * @example
937
+ *
938
+ * _.isEmpty(null);
939
+ * // => true
940
+ *
941
+ * _.isEmpty(true);
942
+ * // => true
943
+ *
944
+ * _.isEmpty(1);
945
+ * // => true
946
+ *
947
+ * _.isEmpty([1, 2, 3]);
948
+ * // => false
949
+ *
950
+ * _.isEmpty({ 'a': 1 });
951
+ * // => false
952
+ */
953
+ function isEmpty(value) {
954
+ if (value == null) {
955
+ return true;
956
+ }
957
+ if (isArrayLike(value) &&
958
+ (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
959
+ isBuffer(value) || isTypedArray(value) || isArguments(value))) {
960
+ return !value.length;
961
+ }
962
+ var tag = getTag(value);
963
+ if (tag == mapTag || tag == setTag) {
964
+ return !value.size;
965
+ }
966
+ if (isPrototype(value)) {
967
+ return !baseKeys(value).length;
968
+ }
969
+ for (var key in value) {
970
+ if (hasOwnProperty.call(value, key)) {
971
+ return false;
972
+ }
973
+ }
974
+ return true;
975
+ }
976
+
977
+ var isEmpty_1 = isEmpty;
978
+
979
+ const defaults$1 = {
980
+ correct: { type: 'default', default: 'Correct', custom: 'Correct' },
981
+ incorrect: { type: 'default', default: 'Incorrect', custom: 'Incorrect' },
982
+ partial: { type: 'default', default: 'Nearly', custom: 'Nearly' },
983
+ unanswered: {
984
+ type: 'default',
985
+ default: 'You have not entered a response',
986
+ custom: 'You have not entered a response',
987
+ },
988
+ };
989
+
990
+ // TODO: should replace getFeedbackForCorrectness
991
+ /**
992
+ * Get feedback for correctness
993
+ * @param {'correct'|'incorrect'|'partial'} correctness
994
+ * @param {Feedback} feedback
995
+ */
996
+ const getActualFeedbackForCorrectness = (correctness, feedback) => {
997
+ feedback = { ...defaults$1, ...feedback };
998
+
999
+ // normalize correctness
1000
+ correctness = correctness === 'partially-correct' ? 'partial' : correctness;
1001
+
1002
+ const defaultFeedback = defaults$1[correctness] || {};
1003
+ const fb = feedback[correctness] || defaultFeedback;
1004
+
1005
+ return getActualFeedback(fb, defaultFeedback[fb.type || 'default']);
1006
+ };
1007
+
1008
+ // TODO: should replace getFeedback
1009
+ /**
1010
+ * Get the feedback from a {FeedbackConfig}
1011
+ * @param {FeedbackConfig} feedback
1012
+ * @param {string} fallback
1013
+ */
1014
+ const getActualFeedback = (feedback, fallback) => {
1015
+ if (!feedback || feedback.type === 'none') {
1016
+ return undefined;
1017
+ }
1018
+
1019
+ return feedback[feedback.type] || fallback;
1020
+ };
1021
+
1022
+ const ResponseTypes = {
1023
+ advanced: 'Advanced Multi',
1024
+ simple: 'Simple',
1025
+ };
1026
+
1027
+ const isString = obj => typeof obj === 'string';
1028
+ const defer = () => {
1029
+ let res;
1030
+ let rej;
1031
+ const promise = new Promise((resolve, reject) => {
1032
+ res = resolve;
1033
+ rej = reject;
1034
+ });
1035
+ promise.resolve = res;
1036
+ promise.reject = rej;
1037
+ return promise;
1038
+ };
1039
+ const makeString = object => {
1040
+ if (object == null) return '';
1041
+ return '' + object;
1042
+ };
1043
+ const copy = (a, s, t) => {
1044
+ a.forEach(m => {
1045
+ if (s[m]) t[m] = s[m];
1046
+ });
1047
+ };
1048
+ const lastOfPathSeparatorRegExp = /###/g;
1049
+ const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
1050
+ const canNotTraverseDeeper = object => !object || isString(object);
1051
+ const getLastOfPath = (object, path, Empty) => {
1052
+ const stack = !isString(path) ? path : path.split('.');
1053
+ let stackIndex = 0;
1054
+ while (stackIndex < stack.length - 1) {
1055
+ if (canNotTraverseDeeper(object)) return {};
1056
+ const key = cleanKey(stack[stackIndex]);
1057
+ if (!object[key] && Empty) object[key] = new Empty();
1058
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
1059
+ object = object[key];
1060
+ } else {
1061
+ object = {};
1062
+ }
1063
+ ++stackIndex;
1064
+ }
1065
+ if (canNotTraverseDeeper(object)) return {};
1066
+ return {
1067
+ obj: object,
1068
+ k: cleanKey(stack[stackIndex])
1069
+ };
1070
+ };
1071
+ const setPath = (object, path, newValue) => {
1072
+ const {
1073
+ obj,
1074
+ k
1075
+ } = getLastOfPath(object, path, Object);
1076
+ if (obj !== undefined || path.length === 1) {
1077
+ obj[k] = newValue;
1078
+ return;
1079
+ }
1080
+ let e = path[path.length - 1];
1081
+ let p = path.slice(0, path.length - 1);
1082
+ let last = getLastOfPath(object, p, Object);
1083
+ while (last.obj === undefined && p.length) {
1084
+ e = `${p[p.length - 1]}.${e}`;
1085
+ p = p.slice(0, p.length - 1);
1086
+ last = getLastOfPath(object, p, Object);
1087
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
1088
+ last.obj = undefined;
1089
+ }
1090
+ }
1091
+ last.obj[`${last.k}.${e}`] = newValue;
1092
+ };
1093
+ const pushPath = (object, path, newValue, concat) => {
1094
+ const {
1095
+ obj,
1096
+ k
1097
+ } = getLastOfPath(object, path, Object);
1098
+ obj[k] = obj[k] || [];
1099
+ obj[k].push(newValue);
1100
+ };
1101
+ const getPath = (object, path) => {
1102
+ const {
1103
+ obj,
1104
+ k
1105
+ } = getLastOfPath(object, path);
1106
+ if (!obj) return undefined;
1107
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
1108
+ return obj[k];
1109
+ };
1110
+ const getPathWithDefaults = (data, defaultData, key) => {
1111
+ const value = getPath(data, key);
1112
+ if (value !== undefined) {
1113
+ return value;
1114
+ }
1115
+ return getPath(defaultData, key);
1116
+ };
1117
+ const deepExtend = (target, source, overwrite) => {
1118
+ for (const prop in source) {
1119
+ if (prop !== '__proto__' && prop !== 'constructor') {
1120
+ if (prop in target) {
1121
+ if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
1122
+ if (overwrite) target[prop] = source[prop];
1123
+ } else {
1124
+ deepExtend(target[prop], source[prop], overwrite);
1125
+ }
1126
+ } else {
1127
+ target[prop] = source[prop];
1128
+ }
1129
+ }
1130
+ }
1131
+ return target;
1132
+ };
1133
+ const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
1134
+ var _entityMap = {
1135
+ '&': '&amp;',
1136
+ '<': '&lt;',
1137
+ '>': '&gt;',
1138
+ '"': '&quot;',
1139
+ "'": '&#39;',
1140
+ '/': '&#x2F;'
1141
+ };
1142
+ const escape$1 = data => {
1143
+ if (isString(data)) {
1144
+ return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
1145
+ }
1146
+ return data;
1147
+ };
1148
+ class RegExpCache {
1149
+ constructor(capacity) {
1150
+ this.capacity = capacity;
1151
+ this.regExpMap = new Map();
1152
+ this.regExpQueue = [];
1153
+ }
1154
+ getRegExp(pattern) {
1155
+ const regExpFromCache = this.regExpMap.get(pattern);
1156
+ if (regExpFromCache !== undefined) {
1157
+ return regExpFromCache;
1158
+ }
1159
+ const regExpNew = new RegExp(pattern);
1160
+ if (this.regExpQueue.length === this.capacity) {
1161
+ this.regExpMap.delete(this.regExpQueue.shift());
1162
+ }
1163
+ this.regExpMap.set(pattern, regExpNew);
1164
+ this.regExpQueue.push(pattern);
1165
+ return regExpNew;
1166
+ }
1167
+ }
1168
+ const chars = [' ', ',', '?', '!', ';'];
1169
+ const looksLikeObjectPathRegExpCache = new RegExpCache(20);
1170
+ const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
1171
+ nsSeparator = nsSeparator || '';
1172
+ keySeparator = keySeparator || '';
1173
+ const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
1174
+ if (possibleChars.length === 0) return true;
1175
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
1176
+ let matched = !r.test(key);
1177
+ if (!matched) {
1178
+ const ki = key.indexOf(keySeparator);
1179
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
1180
+ matched = true;
1181
+ }
1182
+ }
1183
+ return matched;
1184
+ };
1185
+ const deepFind = (obj, path, keySeparator = '.') => {
1186
+ if (!obj) return undefined;
1187
+ if (obj[path]) {
1188
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
1189
+ return obj[path];
1190
+ }
1191
+ const tokens = path.split(keySeparator);
1192
+ let current = obj;
1193
+ for (let i = 0; i < tokens.length;) {
1194
+ if (!current || typeof current !== 'object') {
1195
+ return undefined;
1196
+ }
1197
+ let next;
1198
+ let nextPath = '';
1199
+ for (let j = i; j < tokens.length; ++j) {
1200
+ if (j !== i) {
1201
+ nextPath += keySeparator;
1202
+ }
1203
+ nextPath += tokens[j];
1204
+ next = current[nextPath];
1205
+ if (next !== undefined) {
1206
+ if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
1207
+ continue;
1208
+ }
1209
+ i += j - i + 1;
1210
+ break;
1211
+ }
1212
+ }
1213
+ current = next;
1214
+ }
1215
+ return current;
1216
+ };
1217
+ const getCleanedCode = code => code?.replace('_', '-');
1218
+
1219
+ const consoleLogger = {
1220
+ type: 'logger',
1221
+ log(args) {
1222
+ this.output('log', args);
1223
+ },
1224
+ warn(args) {
1225
+ this.output('warn', args);
1226
+ },
1227
+ error(args) {
1228
+ this.output('error', args);
1229
+ },
1230
+ output(type, args) {
1231
+ console?.[type]?.apply?.(console, args);
1232
+ }
1233
+ };
1234
+ class Logger {
1235
+ constructor(concreteLogger, options = {}) {
1236
+ this.init(concreteLogger, options);
1237
+ }
1238
+ init(concreteLogger, options = {}) {
1239
+ this.prefix = options.prefix || 'i18next:';
1240
+ this.logger = concreteLogger || consoleLogger;
1241
+ this.options = options;
1242
+ this.debug = options.debug;
1243
+ }
1244
+ log(...args) {
1245
+ return this.forward(args, 'log', '', true);
1246
+ }
1247
+ warn(...args) {
1248
+ return this.forward(args, 'warn', '', true);
1249
+ }
1250
+ error(...args) {
1251
+ return this.forward(args, 'error', '');
1252
+ }
1253
+ deprecate(...args) {
1254
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
1255
+ }
1256
+ forward(args, lvl, prefix, debugOnly) {
1257
+ if (debugOnly && !this.debug) return null;
1258
+ if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
1259
+ return this.logger[lvl](args);
1260
+ }
1261
+ create(moduleName) {
1262
+ return new Logger(this.logger, {
1263
+ ...{
1264
+ prefix: `${this.prefix}:${moduleName}:`
1265
+ },
1266
+ ...this.options
1267
+ });
1268
+ }
1269
+ clone(options) {
1270
+ options = options || this.options;
1271
+ options.prefix = options.prefix || this.prefix;
1272
+ return new Logger(this.logger, options);
1273
+ }
1274
+ }
1275
+ var baseLogger = new Logger();
1276
+
1277
+ class EventEmitter {
1278
+ constructor() {
1279
+ this.observers = {};
1280
+ }
1281
+ on(events, listener) {
1282
+ events.split(' ').forEach(event => {
1283
+ if (!this.observers[event]) this.observers[event] = new Map();
1284
+ const numListeners = this.observers[event].get(listener) || 0;
1285
+ this.observers[event].set(listener, numListeners + 1);
1286
+ });
1287
+ return this;
1288
+ }
1289
+ off(event, listener) {
1290
+ if (!this.observers[event]) return;
1291
+ if (!listener) {
1292
+ delete this.observers[event];
1293
+ return;
1294
+ }
1295
+ this.observers[event].delete(listener);
1296
+ }
1297
+ emit(event, ...args) {
1298
+ if (this.observers[event]) {
1299
+ const cloned = Array.from(this.observers[event].entries());
1300
+ cloned.forEach(([observer, numTimesAdded]) => {
1301
+ for (let i = 0; i < numTimesAdded; i++) {
1302
+ observer(...args);
1303
+ }
1304
+ });
1305
+ }
1306
+ if (this.observers['*']) {
1307
+ const cloned = Array.from(this.observers['*'].entries());
1308
+ cloned.forEach(([observer, numTimesAdded]) => {
1309
+ for (let i = 0; i < numTimesAdded; i++) {
1310
+ observer.apply(observer, [event, ...args]);
1311
+ }
1312
+ });
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ class ResourceStore extends EventEmitter {
1318
+ constructor(data, options = {
1319
+ ns: ['translation'],
1320
+ defaultNS: 'translation'
1321
+ }) {
1322
+ super();
1323
+ this.data = data || {};
1324
+ this.options = options;
1325
+ if (this.options.keySeparator === undefined) {
1326
+ this.options.keySeparator = '.';
1327
+ }
1328
+ if (this.options.ignoreJSONStructure === undefined) {
1329
+ this.options.ignoreJSONStructure = true;
1330
+ }
1331
+ }
1332
+ addNamespaces(ns) {
1333
+ if (this.options.ns.indexOf(ns) < 0) {
1334
+ this.options.ns.push(ns);
1335
+ }
1336
+ }
1337
+ removeNamespaces(ns) {
1338
+ const index = this.options.ns.indexOf(ns);
1339
+ if (index > -1) {
1340
+ this.options.ns.splice(index, 1);
1341
+ }
1342
+ }
1343
+ getResource(lng, ns, key, options = {}) {
1344
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1345
+ const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
1346
+ let path;
1347
+ if (lng.indexOf('.') > -1) {
1348
+ path = lng.split('.');
1349
+ } else {
1350
+ path = [lng, ns];
1351
+ if (key) {
1352
+ if (Array.isArray(key)) {
1353
+ path.push(...key);
1354
+ } else if (isString(key) && keySeparator) {
1355
+ path.push(...key.split(keySeparator));
1356
+ } else {
1357
+ path.push(key);
1358
+ }
1359
+ }
1360
+ }
1361
+ const result = getPath(this.data, path);
1362
+ if (!result && !ns && !key && lng.indexOf('.') > -1) {
1363
+ lng = path[0];
1364
+ ns = path[1];
1365
+ key = path.slice(2).join('.');
1366
+ }
1367
+ if (result || !ignoreJSONStructure || !isString(key)) return result;
1368
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
1369
+ }
1370
+ addResource(lng, ns, key, value, options = {
1371
+ silent: false
1372
+ }) {
1373
+ const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1374
+ let path = [lng, ns];
1375
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
1376
+ if (lng.indexOf('.') > -1) {
1377
+ path = lng.split('.');
1378
+ value = ns;
1379
+ ns = path[1];
1380
+ }
1381
+ this.addNamespaces(ns);
1382
+ setPath(this.data, path, value);
1383
+ if (!options.silent) this.emit('added', lng, ns, key, value);
1384
+ }
1385
+ addResources(lng, ns, resources, options = {
1386
+ silent: false
1387
+ }) {
1388
+ for (const m in resources) {
1389
+ if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
1390
+ silent: true
1391
+ });
1392
+ }
1393
+ if (!options.silent) this.emit('added', lng, ns, resources);
1394
+ }
1395
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
1396
+ silent: false,
1397
+ skipCopy: false
1398
+ }) {
1399
+ let path = [lng, ns];
1400
+ if (lng.indexOf('.') > -1) {
1401
+ path = lng.split('.');
1402
+ deep = resources;
1403
+ resources = ns;
1404
+ ns = path[1];
1405
+ }
1406
+ this.addNamespaces(ns);
1407
+ let pack = getPath(this.data, path) || {};
1408
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
1409
+ if (deep) {
1410
+ deepExtend(pack, resources, overwrite);
1411
+ } else {
1412
+ pack = {
1413
+ ...pack,
1414
+ ...resources
1415
+ };
1416
+ }
1417
+ setPath(this.data, path, pack);
1418
+ if (!options.silent) this.emit('added', lng, ns, resources);
1419
+ }
1420
+ removeResourceBundle(lng, ns) {
1421
+ if (this.hasResourceBundle(lng, ns)) {
1422
+ delete this.data[lng][ns];
1423
+ }
1424
+ this.removeNamespaces(ns);
1425
+ this.emit('removed', lng, ns);
1426
+ }
1427
+ hasResourceBundle(lng, ns) {
1428
+ return this.getResource(lng, ns) !== undefined;
1429
+ }
1430
+ getResourceBundle(lng, ns) {
1431
+ if (!ns) ns = this.options.defaultNS;
1432
+ return this.getResource(lng, ns);
1433
+ }
1434
+ getDataByLanguage(lng) {
1435
+ return this.data[lng];
1436
+ }
1437
+ hasLanguageSomeTranslations(lng) {
1438
+ const data = this.getDataByLanguage(lng);
1439
+ const n = data && Object.keys(data) || [];
1440
+ return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
1441
+ }
1442
+ toJSON() {
1443
+ return this.data;
1444
+ }
1445
+ }
1446
+
1447
+ var postProcessor = {
1448
+ processors: {},
1449
+ addPostProcessor(module) {
1450
+ this.processors[module.name] = module;
1451
+ },
1452
+ handle(processors, value, key, options, translator) {
1453
+ processors.forEach(processor => {
1454
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
1455
+ });
1456
+ return value;
1457
+ }
1458
+ };
1459
+
1460
+ const PATH_KEY = Symbol('i18next/PATH_KEY');
1461
+ function createProxy() {
1462
+ const state = [];
1463
+ const handler = Object.create(null);
1464
+ let proxy;
1465
+ handler.get = (target, key) => {
1466
+ proxy?.revoke?.();
1467
+ if (key === PATH_KEY) return state;
1468
+ state.push(key);
1469
+ proxy = Proxy.revocable(target, handler);
1470
+ return proxy.proxy;
1471
+ };
1472
+ return Proxy.revocable(Object.create(null), handler).proxy;
1473
+ }
1474
+ function keysFromSelector(selector, opts) {
1475
+ const {
1476
+ [PATH_KEY]: path
1477
+ } = selector(createProxy());
1478
+ return path.join(opts?.keySeparator ?? '.');
1479
+ }
1480
+
1481
+ const checkedLoadedFor = {};
1482
+ const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
1483
+ class Translator$1 extends EventEmitter {
1484
+ constructor(services, options = {}) {
1485
+ super();
1486
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
1487
+ this.options = options;
1488
+ if (this.options.keySeparator === undefined) {
1489
+ this.options.keySeparator = '.';
1490
+ }
1491
+ this.logger = baseLogger.create('translator');
1492
+ }
1493
+ changeLanguage(lng) {
1494
+ if (lng) this.language = lng;
1495
+ }
1496
+ exists(key, o = {
1497
+ interpolation: {}
1498
+ }) {
1499
+ const opt = {
1500
+ ...o
1501
+ };
1502
+ if (key == null) return false;
1503
+ const resolved = this.resolve(key, opt);
1504
+ if (resolved?.res === undefined) return false;
1505
+ const isObject = shouldHandleAsObject(resolved.res);
1506
+ if (opt.returnObjects === false && isObject) {
1507
+ return false;
1508
+ }
1509
+ return true;
1510
+ }
1511
+ extractFromKey(key, opt) {
1512
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
1513
+ if (nsSeparator === undefined) nsSeparator = ':';
1514
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
1515
+ let namespaces = opt.ns || this.options.defaultNS || [];
1516
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
1517
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
1518
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
1519
+ const m = key.match(this.interpolator.nestingRegexp);
1520
+ if (m && m.length > 0) {
1521
+ return {
1522
+ key,
1523
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
1524
+ };
1525
+ }
1526
+ const parts = key.split(nsSeparator);
1527
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
1528
+ key = parts.join(keySeparator);
1529
+ }
1530
+ return {
1531
+ key,
1532
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
1533
+ };
1534
+ }
1535
+ translate(keys, o, lastKey) {
1536
+ let opt = typeof o === 'object' ? {
1537
+ ...o
1538
+ } : o;
1539
+ if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
1540
+ opt = this.options.overloadTranslationOptionHandler(arguments);
1541
+ }
1542
+ if (typeof opt === 'object') opt = {
1543
+ ...opt
1544
+ };
1545
+ if (!opt) opt = {};
1546
+ if (keys == null) return '';
1547
+ if (typeof keys === 'function') keys = keysFromSelector(keys, {
1548
+ ...this.options,
1549
+ ...opt
1550
+ });
1551
+ if (!Array.isArray(keys)) keys = [String(keys)];
1552
+ const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
1553
+ const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
1554
+ const {
1555
+ key,
1556
+ namespaces
1557
+ } = this.extractFromKey(keys[keys.length - 1], opt);
1558
+ const namespace = namespaces[namespaces.length - 1];
1559
+ let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
1560
+ if (nsSeparator === undefined) nsSeparator = ':';
1561
+ const lng = opt.lng || this.language;
1562
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
1563
+ if (lng?.toLowerCase() === 'cimode') {
1564
+ if (appendNamespaceToCIMode) {
1565
+ if (returnDetails) {
1566
+ return {
1567
+ res: `${namespace}${nsSeparator}${key}`,
1568
+ usedKey: key,
1569
+ exactUsedKey: key,
1570
+ usedLng: lng,
1571
+ usedNS: namespace,
1572
+ usedParams: this.getUsedParamsDetails(opt)
1573
+ };
1574
+ }
1575
+ return `${namespace}${nsSeparator}${key}`;
1576
+ }
1577
+ if (returnDetails) {
1578
+ return {
1579
+ res: key,
1580
+ usedKey: key,
1581
+ exactUsedKey: key,
1582
+ usedLng: lng,
1583
+ usedNS: namespace,
1584
+ usedParams: this.getUsedParamsDetails(opt)
1585
+ };
1586
+ }
1587
+ return key;
1588
+ }
1589
+ const resolved = this.resolve(keys, opt);
1590
+ let res = resolved?.res;
1591
+ const resUsedKey = resolved?.usedKey || key;
1592
+ const resExactUsedKey = resolved?.exactUsedKey || key;
1593
+ const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
1594
+ const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
1595
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
1596
+ const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
1597
+ const hasDefaultValue = Translator$1.hasDefaultValue(opt);
1598
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
1599
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
1600
+ ordinal: false
1601
+ }) : '';
1602
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
1603
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
1604
+ let resForObjHndl = res;
1605
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
1606
+ resForObjHndl = defaultValue;
1607
+ }
1608
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
1609
+ const resType = Object.prototype.toString.apply(resForObjHndl);
1610
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
1611
+ if (!opt.returnObjects && !this.options.returnObjects) {
1612
+ if (!this.options.returnedObjectHandler) {
1613
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
1614
+ }
1615
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
1616
+ ...opt,
1617
+ ns: namespaces
1618
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
1619
+ if (returnDetails) {
1620
+ resolved.res = r;
1621
+ resolved.usedParams = this.getUsedParamsDetails(opt);
1622
+ return resolved;
1623
+ }
1624
+ return r;
1625
+ }
1626
+ if (keySeparator) {
1627
+ const resTypeIsArray = Array.isArray(resForObjHndl);
1628
+ const copy = resTypeIsArray ? [] : {};
1629
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
1630
+ for (const m in resForObjHndl) {
1631
+ if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
1632
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
1633
+ if (hasDefaultValue && !res) {
1634
+ copy[m] = this.translate(deepKey, {
1635
+ ...opt,
1636
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
1637
+ ...{
1638
+ joinArrays: false,
1639
+ ns: namespaces
1640
+ }
1641
+ });
1642
+ } else {
1643
+ copy[m] = this.translate(deepKey, {
1644
+ ...opt,
1645
+ ...{
1646
+ joinArrays: false,
1647
+ ns: namespaces
1648
+ }
1649
+ });
1650
+ }
1651
+ if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
1652
+ }
1653
+ }
1654
+ res = copy;
1655
+ }
1656
+ } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
1657
+ res = res.join(joinArrays);
1658
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
1659
+ } else {
1660
+ let usedDefault = false;
1661
+ let usedKey = false;
1662
+ if (!this.isValidLookup(res) && hasDefaultValue) {
1663
+ usedDefault = true;
1664
+ res = defaultValue;
1665
+ }
1666
+ if (!this.isValidLookup(res)) {
1667
+ usedKey = true;
1668
+ res = key;
1669
+ }
1670
+ const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
1671
+ const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
1672
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
1673
+ if (usedKey || usedDefault || updateMissing) {
1674
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
1675
+ if (keySeparator) {
1676
+ const fk = this.resolve(key, {
1677
+ ...opt,
1678
+ keySeparator: false
1679
+ });
1680
+ 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.');
1681
+ }
1682
+ let lngs = [];
1683
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
1684
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
1685
+ for (let i = 0; i < fallbackLngs.length; i++) {
1686
+ lngs.push(fallbackLngs[i]);
1687
+ }
1688
+ } else if (this.options.saveMissingTo === 'all') {
1689
+ lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
1690
+ } else {
1691
+ lngs.push(opt.lng || this.language);
1692
+ }
1693
+ const send = (l, k, specificDefaultValue) => {
1694
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
1695
+ if (this.options.missingKeyHandler) {
1696
+ this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
1697
+ } else if (this.backendConnector?.saveMissing) {
1698
+ this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
1699
+ }
1700
+ this.emit('missingKey', l, namespace, k, res);
1701
+ };
1702
+ if (this.options.saveMissing) {
1703
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
1704
+ lngs.forEach(language => {
1705
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
1706
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
1707
+ suffixes.push(`${this.options.pluralSeparator}zero`);
1708
+ }
1709
+ suffixes.forEach(suffix => {
1710
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
1711
+ });
1712
+ });
1713
+ } else {
1714
+ send(lngs, key, defaultValue);
1715
+ }
1716
+ }
1717
+ }
1718
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
1719
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
1720
+ res = `${namespace}${nsSeparator}${key}`;
1721
+ }
1722
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
1723
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
1724
+ }
1725
+ }
1726
+ if (returnDetails) {
1727
+ resolved.res = res;
1728
+ resolved.usedParams = this.getUsedParamsDetails(opt);
1729
+ return resolved;
1730
+ }
1731
+ return res;
1732
+ }
1733
+ extendTranslation(res, key, opt, resolved, lastKey) {
1734
+ if (this.i18nFormat?.parse) {
1735
+ res = this.i18nFormat.parse(res, {
1736
+ ...this.options.interpolation.defaultVariables,
1737
+ ...opt
1738
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
1739
+ resolved
1740
+ });
1741
+ } else if (!opt.skipInterpolation) {
1742
+ if (opt.interpolation) this.interpolator.init({
1743
+ ...opt,
1744
+ ...{
1745
+ interpolation: {
1746
+ ...this.options.interpolation,
1747
+ ...opt.interpolation
1748
+ }
1749
+ }
1750
+ });
1751
+ const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
1752
+ let nestBef;
1753
+ if (skipOnVariables) {
1754
+ const nb = res.match(this.interpolator.nestingRegexp);
1755
+ nestBef = nb && nb.length;
1756
+ }
1757
+ let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
1758
+ if (this.options.interpolation.defaultVariables) data = {
1759
+ ...this.options.interpolation.defaultVariables,
1760
+ ...data
1761
+ };
1762
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
1763
+ if (skipOnVariables) {
1764
+ const na = res.match(this.interpolator.nestingRegexp);
1765
+ const nestAft = na && na.length;
1766
+ if (nestBef < nestAft) opt.nest = false;
1767
+ }
1768
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
1769
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
1770
+ if (lastKey?.[0] === args[0] && !opt.context) {
1771
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
1772
+ return null;
1773
+ }
1774
+ return this.translate(...args, key);
1775
+ }, opt);
1776
+ if (opt.interpolation) this.interpolator.reset();
1777
+ }
1778
+ const postProcess = opt.postProcess || this.options.postProcess;
1779
+ const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
1780
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
1781
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
1782
+ i18nResolved: {
1783
+ ...resolved,
1784
+ usedParams: this.getUsedParamsDetails(opt)
1785
+ },
1786
+ ...opt
1787
+ } : opt, this);
1788
+ }
1789
+ return res;
1790
+ }
1791
+ resolve(keys, opt = {}) {
1792
+ let found;
1793
+ let usedKey;
1794
+ let exactUsedKey;
1795
+ let usedLng;
1796
+ let usedNS;
1797
+ if (isString(keys)) keys = [keys];
1798
+ keys.forEach(k => {
1799
+ if (this.isValidLookup(found)) return;
1800
+ const extracted = this.extractFromKey(k, opt);
1801
+ const key = extracted.key;
1802
+ usedKey = key;
1803
+ let namespaces = extracted.namespaces;
1804
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
1805
+ const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
1806
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
1807
+ const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
1808
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
1809
+ namespaces.forEach(ns => {
1810
+ if (this.isValidLookup(found)) return;
1811
+ usedNS = ns;
1812
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
1813
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
1814
+ 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!!!');
1815
+ }
1816
+ codes.forEach(code => {
1817
+ if (this.isValidLookup(found)) return;
1818
+ usedLng = code;
1819
+ const finalKeys = [key];
1820
+ if (this.i18nFormat?.addLookupKeys) {
1821
+ this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
1822
+ } else {
1823
+ let pluralSuffix;
1824
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
1825
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
1826
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
1827
+ if (needsPluralHandling) {
1828
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1829
+ finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1830
+ }
1831
+ finalKeys.push(key + pluralSuffix);
1832
+ if (needsZeroSuffixLookup) {
1833
+ finalKeys.push(key + zeroSuffix);
1834
+ }
1835
+ }
1836
+ if (needsContextHandling) {
1837
+ const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
1838
+ finalKeys.push(contextKey);
1839
+ if (needsPluralHandling) {
1840
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
1841
+ finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1842
+ }
1843
+ finalKeys.push(contextKey + pluralSuffix);
1844
+ if (needsZeroSuffixLookup) {
1845
+ finalKeys.push(contextKey + zeroSuffix);
1846
+ }
1847
+ }
1848
+ }
1849
+ }
1850
+ let possibleKey;
1851
+ while (possibleKey = finalKeys.pop()) {
1852
+ if (!this.isValidLookup(found)) {
1853
+ exactUsedKey = possibleKey;
1854
+ found = this.getResource(code, ns, possibleKey, opt);
1855
+ }
1856
+ }
1857
+ });
1858
+ });
1859
+ });
1860
+ return {
1861
+ res: found,
1862
+ usedKey,
1863
+ exactUsedKey,
1864
+ usedLng,
1865
+ usedNS
1866
+ };
1867
+ }
1868
+ isValidLookup(res) {
1869
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
1870
+ }
1871
+ getResource(code, ns, key, options = {}) {
1872
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1873
+ return this.resourceStore.getResource(code, ns, key, options);
1874
+ }
1875
+ getUsedParamsDetails(options = {}) {
1876
+ const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
1877
+ const useOptionsReplaceForData = options.replace && !isString(options.replace);
1878
+ let data = useOptionsReplaceForData ? options.replace : options;
1879
+ if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
1880
+ data.count = options.count;
1881
+ }
1882
+ if (this.options.interpolation.defaultVariables) {
1883
+ data = {
1884
+ ...this.options.interpolation.defaultVariables,
1885
+ ...data
1886
+ };
1887
+ }
1888
+ if (!useOptionsReplaceForData) {
1889
+ data = {
1890
+ ...data
1891
+ };
1892
+ for (const key of optionsKeys) {
1893
+ delete data[key];
1894
+ }
1895
+ }
1896
+ return data;
1897
+ }
1898
+ static hasDefaultValue(options) {
1899
+ const prefix = 'defaultValue';
1900
+ for (const option in options) {
1901
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1902
+ return true;
1903
+ }
1904
+ }
1905
+ return false;
1906
+ }
1907
+ }
1908
+
1909
+ class LanguageUtil {
1910
+ constructor(options) {
1911
+ this.options = options;
1912
+ this.supportedLngs = this.options.supportedLngs || false;
1913
+ this.logger = baseLogger.create('languageUtils');
1914
+ }
1915
+ getScriptPartFromCode(code) {
1916
+ code = getCleanedCode(code);
1917
+ if (!code || code.indexOf('-') < 0) return null;
1918
+ const p = code.split('-');
1919
+ if (p.length === 2) return null;
1920
+ p.pop();
1921
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
1922
+ return this.formatLanguageCode(p.join('-'));
1923
+ }
1924
+ getLanguagePartFromCode(code) {
1925
+ code = getCleanedCode(code);
1926
+ if (!code || code.indexOf('-') < 0) return code;
1927
+ const p = code.split('-');
1928
+ return this.formatLanguageCode(p[0]);
1929
+ }
1930
+ formatLanguageCode(code) {
1931
+ if (isString(code) && code.indexOf('-') > -1) {
1932
+ let formattedCode;
1933
+ try {
1934
+ formattedCode = Intl.getCanonicalLocales(code)[0];
1935
+ } catch (e) {}
1936
+ if (formattedCode && this.options.lowerCaseLng) {
1937
+ formattedCode = formattedCode.toLowerCase();
1938
+ }
1939
+ if (formattedCode) return formattedCode;
1940
+ if (this.options.lowerCaseLng) {
1941
+ return code.toLowerCase();
1942
+ }
1943
+ return code;
1944
+ }
1945
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1946
+ }
1947
+ isSupportedCode(code) {
1948
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1949
+ code = this.getLanguagePartFromCode(code);
1950
+ }
1951
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1952
+ }
1953
+ getBestMatchFromCodes(codes) {
1954
+ if (!codes) return null;
1955
+ let found;
1956
+ codes.forEach(code => {
1957
+ if (found) return;
1958
+ const cleanedLng = this.formatLanguageCode(code);
1959
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1960
+ });
1961
+ if (!found && this.options.supportedLngs) {
1962
+ codes.forEach(code => {
1963
+ if (found) return;
1964
+ const lngScOnly = this.getScriptPartFromCode(code);
1965
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1966
+ const lngOnly = this.getLanguagePartFromCode(code);
1967
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1968
+ found = this.options.supportedLngs.find(supportedLng => {
1969
+ if (supportedLng === lngOnly) return supportedLng;
1970
+ if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1971
+ if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
1972
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1973
+ });
1974
+ });
1975
+ }
1976
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1977
+ return found;
1978
+ }
1979
+ getFallbackCodes(fallbacks, code) {
1980
+ if (!fallbacks) return [];
1981
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1982
+ if (isString(fallbacks)) fallbacks = [fallbacks];
1983
+ if (Array.isArray(fallbacks)) return fallbacks;
1984
+ if (!code) return fallbacks.default || [];
1985
+ let found = fallbacks[code];
1986
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1987
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1988
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1989
+ if (!found) found = fallbacks.default;
1990
+ return found || [];
1991
+ }
1992
+ toResolveHierarchy(code, fallbackCode) {
1993
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1994
+ const codes = [];
1995
+ const addCode = c => {
1996
+ if (!c) return;
1997
+ if (this.isSupportedCode(c)) {
1998
+ codes.push(c);
1999
+ } else {
2000
+ this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
2001
+ }
2002
+ };
2003
+ if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
2004
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
2005
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
2006
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
2007
+ } else if (isString(code)) {
2008
+ addCode(this.formatLanguageCode(code));
2009
+ }
2010
+ fallbackCodes.forEach(fc => {
2011
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
2012
+ });
2013
+ return codes;
2014
+ }
2015
+ }
2016
+
2017
+ const suffixesOrder = {
2018
+ zero: 0,
2019
+ one: 1,
2020
+ two: 2,
2021
+ few: 3,
2022
+ many: 4,
2023
+ other: 5
2024
+ };
2025
+ const dummyRule = {
2026
+ select: count => count === 1 ? 'one' : 'other',
2027
+ resolvedOptions: () => ({
2028
+ pluralCategories: ['one', 'other']
2029
+ })
2030
+ };
2031
+ class PluralResolver {
2032
+ constructor(languageUtils, options = {}) {
2033
+ this.languageUtils = languageUtils;
2034
+ this.options = options;
2035
+ this.logger = baseLogger.create('pluralResolver');
2036
+ this.pluralRulesCache = {};
2037
+ }
2038
+ clearCache() {
2039
+ this.pluralRulesCache = {};
2040
+ }
2041
+ getRule(code, options = {}) {
2042
+ const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
2043
+ const type = options.ordinal ? 'ordinal' : 'cardinal';
2044
+ const cacheKey = JSON.stringify({
2045
+ cleanedCode,
2046
+ type
2047
+ });
2048
+ if (cacheKey in this.pluralRulesCache) {
2049
+ return this.pluralRulesCache[cacheKey];
2050
+ }
2051
+ let rule;
2052
+ try {
2053
+ rule = new Intl.PluralRules(cleanedCode, {
2054
+ type
2055
+ });
2056
+ } catch (err) {
2057
+ if (!Intl) {
2058
+ this.logger.error('No Intl support, please use an Intl polyfill!');
2059
+ return dummyRule;
2060
+ }
2061
+ if (!code.match(/-|_/)) return dummyRule;
2062
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
2063
+ rule = this.getRule(lngPart, options);
2064
+ }
2065
+ this.pluralRulesCache[cacheKey] = rule;
2066
+ return rule;
2067
+ }
2068
+ needsPlural(code, options = {}) {
2069
+ let rule = this.getRule(code, options);
2070
+ if (!rule) rule = this.getRule('dev', options);
2071
+ return rule?.resolvedOptions().pluralCategories.length > 1;
2072
+ }
2073
+ getPluralFormsOfKey(code, key, options = {}) {
2074
+ return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
2075
+ }
2076
+ getSuffixes(code, options = {}) {
2077
+ let rule = this.getRule(code, options);
2078
+ if (!rule) rule = this.getRule('dev', options);
2079
+ if (!rule) return [];
2080
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
2081
+ }
2082
+ getSuffix(code, count, options = {}) {
2083
+ const rule = this.getRule(code, options);
2084
+ if (rule) {
2085
+ return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
2086
+ }
2087
+ this.logger.warn(`no plural rule found for: ${code}`);
2088
+ return this.getSuffix('dev', count, options);
2089
+ }
2090
+ }
2091
+
2092
+ const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
2093
+ let path = getPathWithDefaults(data, defaultData, key);
2094
+ if (!path && ignoreJSONStructure && isString(key)) {
2095
+ path = deepFind(data, key, keySeparator);
2096
+ if (path === undefined) path = deepFind(defaultData, key, keySeparator);
2097
+ }
2098
+ return path;
2099
+ };
2100
+ const regexSafe = val => val.replace(/\$/g, '$$$$');
2101
+ class Interpolator {
2102
+ constructor(options = {}) {
2103
+ this.logger = baseLogger.create('interpolator');
2104
+ this.options = options;
2105
+ this.format = options?.interpolation?.format || (value => value);
2106
+ this.init(options);
2107
+ }
2108
+ init(options = {}) {
2109
+ if (!options.interpolation) options.interpolation = {
2110
+ escapeValue: true
2111
+ };
2112
+ const {
2113
+ escape: escape$1$1,
2114
+ escapeValue,
2115
+ useRawValueToEscape,
2116
+ prefix,
2117
+ prefixEscaped,
2118
+ suffix,
2119
+ suffixEscaped,
2120
+ formatSeparator,
2121
+ unescapeSuffix,
2122
+ unescapePrefix,
2123
+ nestingPrefix,
2124
+ nestingPrefixEscaped,
2125
+ nestingSuffix,
2126
+ nestingSuffixEscaped,
2127
+ nestingOptionsSeparator,
2128
+ maxReplaces,
2129
+ alwaysFormat
2130
+ } = options.interpolation;
2131
+ this.escape = escape$1$1 !== undefined ? escape$1$1 : escape$1;
2132
+ this.escapeValue = escapeValue !== undefined ? escapeValue : true;
2133
+ this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
2134
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
2135
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
2136
+ this.formatSeparator = formatSeparator || ',';
2137
+ this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
2138
+ this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
2139
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
2140
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
2141
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
2142
+ this.maxReplaces = maxReplaces || 1000;
2143
+ this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
2144
+ this.resetRegExp();
2145
+ }
2146
+ reset() {
2147
+ if (this.options) this.init(this.options);
2148
+ }
2149
+ resetRegExp() {
2150
+ const getOrResetRegExp = (existingRegExp, pattern) => {
2151
+ if (existingRegExp?.source === pattern) {
2152
+ existingRegExp.lastIndex = 0;
2153
+ return existingRegExp;
2154
+ }
2155
+ return new RegExp(pattern, 'g');
2156
+ };
2157
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
2158
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
2159
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
2160
+ }
2161
+ interpolate(str, data, lng, options) {
2162
+ let match;
2163
+ let value;
2164
+ let replaces;
2165
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
2166
+ const handleFormat = key => {
2167
+ if (key.indexOf(this.formatSeparator) < 0) {
2168
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
2169
+ return this.alwaysFormat ? this.format(path, undefined, lng, {
2170
+ ...options,
2171
+ ...data,
2172
+ interpolationkey: key
2173
+ }) : path;
2174
+ }
2175
+ const p = key.split(this.formatSeparator);
2176
+ const k = p.shift().trim();
2177
+ const f = p.join(this.formatSeparator).trim();
2178
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
2179
+ ...options,
2180
+ ...data,
2181
+ interpolationkey: k
2182
+ });
2183
+ };
2184
+ this.resetRegExp();
2185
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
2186
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
2187
+ const todos = [{
2188
+ regex: this.regexpUnescape,
2189
+ safeValue: val => regexSafe(val)
2190
+ }, {
2191
+ regex: this.regexp,
2192
+ safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
2193
+ }];
2194
+ todos.forEach(todo => {
2195
+ replaces = 0;
2196
+ while (match = todo.regex.exec(str)) {
2197
+ const matchedVar = match[1].trim();
2198
+ value = handleFormat(matchedVar);
2199
+ if (value === undefined) {
2200
+ if (typeof missingInterpolationHandler === 'function') {
2201
+ const temp = missingInterpolationHandler(str, match, options);
2202
+ value = isString(temp) ? temp : '';
2203
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
2204
+ value = '';
2205
+ } else if (skipOnVariables) {
2206
+ value = match[0];
2207
+ continue;
2208
+ } else {
2209
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
2210
+ value = '';
2211
+ }
2212
+ } else if (!isString(value) && !this.useRawValueToEscape) {
2213
+ value = makeString(value);
2214
+ }
2215
+ const safeValue = todo.safeValue(value);
2216
+ str = str.replace(match[0], safeValue);
2217
+ if (skipOnVariables) {
2218
+ todo.regex.lastIndex += value.length;
2219
+ todo.regex.lastIndex -= match[0].length;
2220
+ } else {
2221
+ todo.regex.lastIndex = 0;
2222
+ }
2223
+ replaces++;
2224
+ if (replaces >= this.maxReplaces) {
2225
+ break;
2226
+ }
2227
+ }
2228
+ });
2229
+ return str;
2230
+ }
2231
+ nest(str, fc, options = {}) {
2232
+ let match;
2233
+ let value;
2234
+ let clonedOptions;
2235
+ const handleHasOptions = (key, inheritedOptions) => {
2236
+ const sep = this.nestingOptionsSeparator;
2237
+ if (key.indexOf(sep) < 0) return key;
2238
+ const c = key.split(new RegExp(`${sep}[ ]*{`));
2239
+ let optionsString = `{${c[1]}`;
2240
+ key = c[0];
2241
+ optionsString = this.interpolate(optionsString, clonedOptions);
2242
+ const matchedSingleQuotes = optionsString.match(/'/g);
2243
+ const matchedDoubleQuotes = optionsString.match(/"/g);
2244
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
2245
+ optionsString = optionsString.replace(/'/g, '"');
2246
+ }
2247
+ try {
2248
+ clonedOptions = JSON.parse(optionsString);
2249
+ if (inheritedOptions) clonedOptions = {
2250
+ ...inheritedOptions,
2251
+ ...clonedOptions
2252
+ };
2253
+ } catch (e) {
2254
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
2255
+ return `${key}${sep}${optionsString}`;
2256
+ }
2257
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
2258
+ return key;
2259
+ };
2260
+ while (match = this.nestingRegexp.exec(str)) {
2261
+ let formatters = [];
2262
+ clonedOptions = {
2263
+ ...options
2264
+ };
2265
+ clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
2266
+ clonedOptions.applyPostProcessor = false;
2267
+ delete clonedOptions.defaultValue;
2268
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
2269
+ if (keyEndIndex !== -1) {
2270
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
2271
+ match[1] = match[1].slice(0, keyEndIndex);
2272
+ }
2273
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
2274
+ if (value && match[0] === str && !isString(value)) return value;
2275
+ if (!isString(value)) value = makeString(value);
2276
+ if (!value) {
2277
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
2278
+ value = '';
2279
+ }
2280
+ if (formatters.length) {
2281
+ value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
2282
+ ...options,
2283
+ interpolationkey: match[1].trim()
2284
+ }), value.trim());
2285
+ }
2286
+ str = str.replace(match[0], value);
2287
+ this.regexp.lastIndex = 0;
2288
+ }
2289
+ return str;
2290
+ }
2291
+ }
2292
+
2293
+ const parseFormatStr = formatStr => {
2294
+ let formatName = formatStr.toLowerCase().trim();
2295
+ const formatOptions = {};
2296
+ if (formatStr.indexOf('(') > -1) {
2297
+ const p = formatStr.split('(');
2298
+ formatName = p[0].toLowerCase().trim();
2299
+ const optStr = p[1].substring(0, p[1].length - 1);
2300
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
2301
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
2302
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
2303
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
2304
+ } else {
2305
+ const opts = optStr.split(';');
2306
+ opts.forEach(opt => {
2307
+ if (opt) {
2308
+ const [key, ...rest] = opt.split(':');
2309
+ const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
2310
+ const trimmedKey = key.trim();
2311
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
2312
+ if (val === 'false') formatOptions[trimmedKey] = false;
2313
+ if (val === 'true') formatOptions[trimmedKey] = true;
2314
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
2315
+ }
2316
+ });
2317
+ }
2318
+ }
2319
+ return {
2320
+ formatName,
2321
+ formatOptions
2322
+ };
2323
+ };
2324
+ const createCachedFormatter = fn => {
2325
+ const cache = {};
2326
+ return (v, l, o) => {
2327
+ let optForCache = o;
2328
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
2329
+ optForCache = {
2330
+ ...optForCache,
2331
+ [o.interpolationkey]: undefined
2332
+ };
2333
+ }
2334
+ const key = l + JSON.stringify(optForCache);
2335
+ let frm = cache[key];
2336
+ if (!frm) {
2337
+ frm = fn(getCleanedCode(l), o);
2338
+ cache[key] = frm;
2339
+ }
2340
+ return frm(v);
2341
+ };
2342
+ };
2343
+ const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
2344
+ class Formatter {
2345
+ constructor(options = {}) {
2346
+ this.logger = baseLogger.create('formatter');
2347
+ this.options = options;
2348
+ this.init(options);
2349
+ }
2350
+ init(services, options = {
2351
+ interpolation: {}
2352
+ }) {
2353
+ this.formatSeparator = options.interpolation.formatSeparator || ',';
2354
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
2355
+ this.formats = {
2356
+ number: cf((lng, opt) => {
2357
+ const formatter = new Intl.NumberFormat(lng, {
2358
+ ...opt
2359
+ });
2360
+ return val => formatter.format(val);
2361
+ }),
2362
+ currency: cf((lng, opt) => {
2363
+ const formatter = new Intl.NumberFormat(lng, {
2364
+ ...opt,
2365
+ style: 'currency'
2366
+ });
2367
+ return val => formatter.format(val);
2368
+ }),
2369
+ datetime: cf((lng, opt) => {
2370
+ const formatter = new Intl.DateTimeFormat(lng, {
2371
+ ...opt
2372
+ });
2373
+ return val => formatter.format(val);
2374
+ }),
2375
+ relativetime: cf((lng, opt) => {
2376
+ const formatter = new Intl.RelativeTimeFormat(lng, {
2377
+ ...opt
2378
+ });
2379
+ return val => formatter.format(val, opt.range || 'day');
2380
+ }),
2381
+ list: cf((lng, opt) => {
2382
+ const formatter = new Intl.ListFormat(lng, {
2383
+ ...opt
2384
+ });
2385
+ return val => formatter.format(val);
2386
+ })
2387
+ };
2388
+ }
2389
+ add(name, fc) {
2390
+ this.formats[name.toLowerCase().trim()] = fc;
2391
+ }
2392
+ addCached(name, fc) {
2393
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
2394
+ }
2395
+ format(value, format, lng, options = {}) {
2396
+ const formats = format.split(this.formatSeparator);
2397
+ if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
2398
+ const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
2399
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
2400
+ }
2401
+ const result = formats.reduce((mem, f) => {
2402
+ const {
2403
+ formatName,
2404
+ formatOptions
2405
+ } = parseFormatStr(f);
2406
+ if (this.formats[formatName]) {
2407
+ let formatted = mem;
2408
+ try {
2409
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
2410
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
2411
+ formatted = this.formats[formatName](mem, l, {
2412
+ ...formatOptions,
2413
+ ...options,
2414
+ ...valOptions
2415
+ });
2416
+ } catch (error) {
2417
+ this.logger.warn(error);
2418
+ }
2419
+ return formatted;
2420
+ } else {
2421
+ this.logger.warn(`there was no format function for ${formatName}`);
2422
+ }
2423
+ return mem;
2424
+ }, value);
2425
+ return result;
2426
+ }
2427
+ }
2428
+
2429
+ const removePending = (q, name) => {
2430
+ if (q.pending[name] !== undefined) {
2431
+ delete q.pending[name];
2432
+ q.pendingCount--;
2433
+ }
2434
+ };
2435
+ class Connector extends EventEmitter {
2436
+ constructor(backend, store, services, options = {}) {
2437
+ super();
2438
+ this.backend = backend;
2439
+ this.store = store;
2440
+ this.services = services;
2441
+ this.languageUtils = services.languageUtils;
2442
+ this.options = options;
2443
+ this.logger = baseLogger.create('backendConnector');
2444
+ this.waitingReads = [];
2445
+ this.maxParallelReads = options.maxParallelReads || 10;
2446
+ this.readingCalls = 0;
2447
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
2448
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
2449
+ this.state = {};
2450
+ this.queue = [];
2451
+ this.backend?.init?.(services, options.backend, options);
2452
+ }
2453
+ queueLoad(languages, namespaces, options, callback) {
2454
+ const toLoad = {};
2455
+ const pending = {};
2456
+ const toLoadLanguages = {};
2457
+ const toLoadNamespaces = {};
2458
+ languages.forEach(lng => {
2459
+ let hasAllNamespaces = true;
2460
+ namespaces.forEach(ns => {
2461
+ const name = `${lng}|${ns}`;
2462
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
2463
+ this.state[name] = 2;
2464
+ } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
2465
+ if (pending[name] === undefined) pending[name] = true;
2466
+ } else {
2467
+ this.state[name] = 1;
2468
+ hasAllNamespaces = false;
2469
+ if (pending[name] === undefined) pending[name] = true;
2470
+ if (toLoad[name] === undefined) toLoad[name] = true;
2471
+ if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
2472
+ }
2473
+ });
2474
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
2475
+ });
2476
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
2477
+ this.queue.push({
2478
+ pending,
2479
+ pendingCount: Object.keys(pending).length,
2480
+ loaded: {},
2481
+ errors: [],
2482
+ callback
2483
+ });
2484
+ }
2485
+ return {
2486
+ toLoad: Object.keys(toLoad),
2487
+ pending: Object.keys(pending),
2488
+ toLoadLanguages: Object.keys(toLoadLanguages),
2489
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
2490
+ };
2491
+ }
2492
+ loaded(name, err, data) {
2493
+ const s = name.split('|');
2494
+ const lng = s[0];
2495
+ const ns = s[1];
2496
+ if (err) this.emit('failedLoading', lng, ns, err);
2497
+ if (!err && data) {
2498
+ this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
2499
+ skipCopy: true
2500
+ });
2501
+ }
2502
+ this.state[name] = err ? -1 : 2;
2503
+ if (err && data) this.state[name] = 0;
2504
+ const loaded = {};
2505
+ this.queue.forEach(q => {
2506
+ pushPath(q.loaded, [lng], ns);
2507
+ removePending(q, name);
2508
+ if (err) q.errors.push(err);
2509
+ if (q.pendingCount === 0 && !q.done) {
2510
+ Object.keys(q.loaded).forEach(l => {
2511
+ if (!loaded[l]) loaded[l] = {};
2512
+ const loadedKeys = q.loaded[l];
2513
+ if (loadedKeys.length) {
2514
+ loadedKeys.forEach(n => {
2515
+ if (loaded[l][n] === undefined) loaded[l][n] = true;
2516
+ });
2517
+ }
2518
+ });
2519
+ q.done = true;
2520
+ if (q.errors.length) {
2521
+ q.callback(q.errors);
2522
+ } else {
2523
+ q.callback();
2524
+ }
2525
+ }
2526
+ });
2527
+ this.emit('loaded', loaded);
2528
+ this.queue = this.queue.filter(q => !q.done);
2529
+ }
2530
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
2531
+ if (!lng.length) return callback(null, {});
2532
+ if (this.readingCalls >= this.maxParallelReads) {
2533
+ this.waitingReads.push({
2534
+ lng,
2535
+ ns,
2536
+ fcName,
2537
+ tried,
2538
+ wait,
2539
+ callback
2540
+ });
2541
+ return;
2542
+ }
2543
+ this.readingCalls++;
2544
+ const resolver = (err, data) => {
2545
+ this.readingCalls--;
2546
+ if (this.waitingReads.length > 0) {
2547
+ const next = this.waitingReads.shift();
2548
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
2549
+ }
2550
+ if (err && data && tried < this.maxRetries) {
2551
+ setTimeout(() => {
2552
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
2553
+ }, wait);
2554
+ return;
2555
+ }
2556
+ callback(err, data);
2557
+ };
2558
+ const fc = this.backend[fcName].bind(this.backend);
2559
+ if (fc.length === 2) {
2560
+ try {
2561
+ const r = fc(lng, ns);
2562
+ if (r && typeof r.then === 'function') {
2563
+ r.then(data => resolver(null, data)).catch(resolver);
2564
+ } else {
2565
+ resolver(null, r);
2566
+ }
2567
+ } catch (err) {
2568
+ resolver(err);
2569
+ }
2570
+ return;
2571
+ }
2572
+ return fc(lng, ns, resolver);
2573
+ }
2574
+ prepareLoading(languages, namespaces, options = {}, callback) {
2575
+ if (!this.backend) {
2576
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
2577
+ return callback && callback();
2578
+ }
2579
+ if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
2580
+ if (isString(namespaces)) namespaces = [namespaces];
2581
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
2582
+ if (!toLoad.toLoad.length) {
2583
+ if (!toLoad.pending.length) callback();
2584
+ return null;
2585
+ }
2586
+ toLoad.toLoad.forEach(name => {
2587
+ this.loadOne(name);
2588
+ });
2589
+ }
2590
+ load(languages, namespaces, callback) {
2591
+ this.prepareLoading(languages, namespaces, {}, callback);
2592
+ }
2593
+ reload(languages, namespaces, callback) {
2594
+ this.prepareLoading(languages, namespaces, {
2595
+ reload: true
2596
+ }, callback);
2597
+ }
2598
+ loadOne(name, prefix = '') {
2599
+ const s = name.split('|');
2600
+ const lng = s[0];
2601
+ const ns = s[1];
2602
+ this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
2603
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
2604
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
2605
+ this.loaded(name, err, data);
2606
+ });
2607
+ }
2608
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
2609
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
2610
+ 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!!!');
2611
+ return;
2612
+ }
2613
+ if (key === undefined || key === null || key === '') return;
2614
+ if (this.backend?.create) {
2615
+ const opts = {
2616
+ ...options,
2617
+ isUpdate
2618
+ };
2619
+ const fc = this.backend.create.bind(this.backend);
2620
+ if (fc.length < 6) {
2621
+ try {
2622
+ let r;
2623
+ if (fc.length === 5) {
2624
+ r = fc(languages, namespace, key, fallbackValue, opts);
2625
+ } else {
2626
+ r = fc(languages, namespace, key, fallbackValue);
2627
+ }
2628
+ if (r && typeof r.then === 'function') {
2629
+ r.then(data => clb(null, data)).catch(clb);
2630
+ } else {
2631
+ clb(null, r);
2632
+ }
2633
+ } catch (err) {
2634
+ clb(err);
2635
+ }
2636
+ } else {
2637
+ fc(languages, namespace, key, fallbackValue, clb, opts);
2638
+ }
2639
+ }
2640
+ if (!languages || !languages[0]) return;
2641
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
2642
+ }
2643
+ }
2644
+
2645
+ const get = () => ({
2646
+ debug: false,
2647
+ initAsync: true,
2648
+ ns: ['translation'],
2649
+ defaultNS: ['translation'],
2650
+ fallbackLng: ['dev'],
2651
+ fallbackNS: false,
2652
+ supportedLngs: false,
2653
+ nonExplicitSupportedLngs: false,
2654
+ load: 'all',
2655
+ preload: false,
2656
+ simplifyPluralSuffix: true,
2657
+ keySeparator: '.',
2658
+ nsSeparator: ':',
2659
+ pluralSeparator: '_',
2660
+ contextSeparator: '_',
2661
+ partialBundledLanguages: false,
2662
+ saveMissing: false,
2663
+ updateMissing: false,
2664
+ saveMissingTo: 'fallback',
2665
+ saveMissingPlurals: true,
2666
+ missingKeyHandler: false,
2667
+ missingInterpolationHandler: false,
2668
+ postProcess: false,
2669
+ postProcessPassResolved: false,
2670
+ returnNull: false,
2671
+ returnEmptyString: true,
2672
+ returnObjects: false,
2673
+ joinArrays: false,
2674
+ returnedObjectHandler: false,
2675
+ parseMissingKeyHandler: false,
2676
+ appendNamespaceToMissingKey: false,
2677
+ appendNamespaceToCIMode: false,
2678
+ overloadTranslationOptionHandler: args => {
2679
+ let ret = {};
2680
+ if (typeof args[1] === 'object') ret = args[1];
2681
+ if (isString(args[1])) ret.defaultValue = args[1];
2682
+ if (isString(args[2])) ret.tDescription = args[2];
2683
+ if (typeof args[2] === 'object' || typeof args[3] === 'object') {
2684
+ const options = args[3] || args[2];
2685
+ Object.keys(options).forEach(key => {
2686
+ ret[key] = options[key];
2687
+ });
2688
+ }
2689
+ return ret;
2690
+ },
2691
+ interpolation: {
2692
+ escapeValue: true,
2693
+ format: value => value,
2694
+ prefix: '{{',
2695
+ suffix: '}}',
2696
+ formatSeparator: ',',
2697
+ unescapePrefix: '-',
2698
+ nestingPrefix: '$t(',
2699
+ nestingSuffix: ')',
2700
+ nestingOptionsSeparator: ',',
2701
+ maxReplaces: 1000,
2702
+ skipOnVariables: true
2703
+ },
2704
+ cacheInBuiltFormats: true
2705
+ });
2706
+ const transformOptions = options => {
2707
+ if (isString(options.ns)) options.ns = [options.ns];
2708
+ if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
2709
+ if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
2710
+ if (options.supportedLngs?.indexOf?.('cimode') < 0) {
2711
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
2712
+ }
2713
+ if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
2714
+ return options;
2715
+ };
2716
+
2717
+ const noop = () => {};
2718
+ const bindMemberFunctions = inst => {
2719
+ const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
2720
+ mems.forEach(mem => {
2721
+ if (typeof inst[mem] === 'function') {
2722
+ inst[mem] = inst[mem].bind(inst);
2723
+ }
2724
+ });
2725
+ };
2726
+ const usesLocize = inst => {
2727
+ if (inst?.modules?.backend?.name?.indexOf('Locize') > 0) return true;
2728
+ if (inst?.modules?.backend?.constructor?.name?.indexOf('Locize') > 0) return true;
2729
+ if (inst?.options?.backend?.backends) {
2730
+ if (inst.options.backend.backends.some(b => b?.name.indexOf('Locize') > 0 || b?.constructor?.name.indexOf('Locize') > 0)) return true;
2731
+ }
2732
+ return false;
2733
+ };
2734
+ class I18n extends EventEmitter {
2735
+ constructor(options = {}, callback) {
2736
+ super();
2737
+ this.options = transformOptions(options);
2738
+ this.services = {};
2739
+ this.logger = baseLogger;
2740
+ this.modules = {
2741
+ external: []
2742
+ };
2743
+ bindMemberFunctions(this);
2744
+ if (callback && !this.isInitialized && !options.isClone) {
2745
+ if (!this.options.initAsync) {
2746
+ this.init(options, callback);
2747
+ return this;
2748
+ }
2749
+ setTimeout(() => {
2750
+ this.init(options, callback);
2751
+ }, 0);
2752
+ }
2753
+ }
2754
+ init(options = {}, callback) {
2755
+ this.isInitializing = true;
2756
+ if (typeof options === 'function') {
2757
+ callback = options;
2758
+ options = {};
2759
+ }
2760
+ if (options.defaultNS == null && options.ns) {
2761
+ if (isString(options.ns)) {
2762
+ options.defaultNS = options.ns;
2763
+ } else if (options.ns.indexOf('translation') < 0) {
2764
+ options.defaultNS = options.ns[0];
2765
+ }
2766
+ }
2767
+ const defOpts = get();
2768
+ this.options = {
2769
+ ...defOpts,
2770
+ ...this.options,
2771
+ ...transformOptions(options)
2772
+ };
2773
+ this.options.interpolation = {
2774
+ ...defOpts.interpolation,
2775
+ ...this.options.interpolation
2776
+ };
2777
+ if (options.keySeparator !== undefined) {
2778
+ this.options.userDefinedKeySeparator = options.keySeparator;
2779
+ }
2780
+ if (options.nsSeparator !== undefined) {
2781
+ this.options.userDefinedNsSeparator = options.nsSeparator;
2782
+ }
2783
+ if (typeof this.options.overloadTranslationOptionHandler !== 'function') {
2784
+ this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
2785
+ }
2786
+ if (this.options.showSupportNotice !== false && !usesLocize(this)) {
2787
+ if (typeof console !== 'undefined' && typeof console.info !== 'undefined') console.info('🌐 i18next is maintained with support from locize.com — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙');
2788
+ }
2789
+ const createClassOnDemand = ClassOrObject => {
2790
+ if (!ClassOrObject) return null;
2791
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
2792
+ return ClassOrObject;
2793
+ };
2794
+ if (!this.options.isClone) {
2795
+ if (this.modules.logger) {
2796
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2797
+ } else {
2798
+ baseLogger.init(null, this.options);
2799
+ }
2800
+ let formatter;
2801
+ if (this.modules.formatter) {
2802
+ formatter = this.modules.formatter;
2803
+ } else {
2804
+ formatter = Formatter;
2805
+ }
2806
+ const lu = new LanguageUtil(this.options);
2807
+ this.store = new ResourceStore(this.options.resources, this.options);
2808
+ const s = this.services;
2809
+ s.logger = baseLogger;
2810
+ s.resourceStore = this.store;
2811
+ s.languageUtils = lu;
2812
+ s.pluralResolver = new PluralResolver(lu, {
2813
+ prepend: this.options.pluralSeparator,
2814
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
2815
+ });
2816
+ const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
2817
+ if (usingLegacyFormatFunction) {
2818
+ this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
2819
+ }
2820
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2821
+ s.formatter = createClassOnDemand(formatter);
2822
+ if (s.formatter.init) s.formatter.init(s, this.options);
2823
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2824
+ }
2825
+ s.interpolator = new Interpolator(this.options);
2826
+ s.utils = {
2827
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2828
+ };
2829
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2830
+ s.backendConnector.on('*', (event, ...args) => {
2831
+ this.emit(event, ...args);
2832
+ });
2833
+ if (this.modules.languageDetector) {
2834
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2835
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2836
+ }
2837
+ if (this.modules.i18nFormat) {
2838
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2839
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
2840
+ }
2841
+ this.translator = new Translator$1(this.services, this.options);
2842
+ this.translator.on('*', (event, ...args) => {
2843
+ this.emit(event, ...args);
2844
+ });
2845
+ this.modules.external.forEach(m => {
2846
+ if (m.init) m.init(this);
2847
+ });
2848
+ }
2849
+ this.format = this.options.interpolation.format;
2850
+ if (!callback) callback = noop;
2851
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2852
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2853
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2854
+ }
2855
+ if (!this.services.languageDetector && !this.options.lng) {
2856
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
2857
+ }
2858
+ const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2859
+ storeApi.forEach(fcName => {
2860
+ this[fcName] = (...args) => this.store[fcName](...args);
2861
+ });
2862
+ const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2863
+ storeApiChained.forEach(fcName => {
2864
+ this[fcName] = (...args) => {
2865
+ this.store[fcName](...args);
2866
+ return this;
2867
+ };
2868
+ });
2869
+ const deferred = defer();
2870
+ const load = () => {
2871
+ const finish = (err, t) => {
2872
+ this.isInitializing = false;
2873
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
2874
+ this.isInitialized = true;
2875
+ if (!this.options.isClone) this.logger.log('initialized', this.options);
2876
+ this.emit('initialized', this.options);
2877
+ deferred.resolve(t);
2878
+ callback(err, t);
2879
+ };
2880
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
2881
+ this.changeLanguage(this.options.lng, finish);
2882
+ };
2883
+ if (this.options.resources || !this.options.initAsync) {
2884
+ load();
2885
+ } else {
2886
+ setTimeout(load, 0);
2887
+ }
2888
+ return deferred;
2889
+ }
2890
+ loadResources(language, callback = noop) {
2891
+ let usedCallback = callback;
2892
+ const usedLng = isString(language) ? language : this.language;
2893
+ if (typeof language === 'function') usedCallback = language;
2894
+ if (!this.options.resources || this.options.partialBundledLanguages) {
2895
+ if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
2896
+ const toLoad = [];
2897
+ const append = lng => {
2898
+ if (!lng) return;
2899
+ if (lng === 'cimode') return;
2900
+ const lngs = this.services.languageUtils.toResolveHierarchy(lng);
2901
+ lngs.forEach(l => {
2902
+ if (l === 'cimode') return;
2903
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
2904
+ });
2905
+ };
2906
+ if (!usedLng) {
2907
+ const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2908
+ fallbacks.forEach(l => append(l));
2909
+ } else {
2910
+ append(usedLng);
2911
+ }
2912
+ this.options.preload?.forEach?.(l => append(l));
2913
+ this.services.backendConnector.load(toLoad, this.options.ns, e => {
2914
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
2915
+ usedCallback(e);
2916
+ });
2917
+ } else {
2918
+ usedCallback(null);
2919
+ }
2920
+ }
2921
+ reloadResources(lngs, ns, callback) {
2922
+ const deferred = defer();
2923
+ if (typeof lngs === 'function') {
2924
+ callback = lngs;
2925
+ lngs = undefined;
2926
+ }
2927
+ if (typeof ns === 'function') {
2928
+ callback = ns;
2929
+ ns = undefined;
2930
+ }
2931
+ if (!lngs) lngs = this.languages;
2932
+ if (!ns) ns = this.options.ns;
2933
+ if (!callback) callback = noop;
2934
+ this.services.backendConnector.reload(lngs, ns, err => {
2935
+ deferred.resolve();
2936
+ callback(err);
2937
+ });
2938
+ return deferred;
2939
+ }
2940
+ use(module) {
2941
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2942
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2943
+ if (module.type === 'backend') {
2944
+ this.modules.backend = module;
2945
+ }
2946
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
2947
+ this.modules.logger = module;
2948
+ }
2949
+ if (module.type === 'languageDetector') {
2950
+ this.modules.languageDetector = module;
2951
+ }
2952
+ if (module.type === 'i18nFormat') {
2953
+ this.modules.i18nFormat = module;
2954
+ }
2955
+ if (module.type === 'postProcessor') {
2956
+ postProcessor.addPostProcessor(module);
2957
+ }
2958
+ if (module.type === 'formatter') {
2959
+ this.modules.formatter = module;
2960
+ }
2961
+ if (module.type === '3rdParty') {
2962
+ this.modules.external.push(module);
2963
+ }
2964
+ return this;
2965
+ }
2966
+ setResolvedLanguage(l) {
2967
+ if (!l || !this.languages) return;
2968
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
2969
+ for (let li = 0; li < this.languages.length; li++) {
2970
+ const lngInLngs = this.languages[li];
2971
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2972
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2973
+ this.resolvedLanguage = lngInLngs;
2974
+ break;
2975
+ }
2976
+ }
2977
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2978
+ this.resolvedLanguage = l;
2979
+ this.languages.unshift(l);
2980
+ }
2981
+ }
2982
+ changeLanguage(lng, callback) {
2983
+ this.isLanguageChangingTo = lng;
2984
+ const deferred = defer();
2985
+ this.emit('languageChanging', lng);
2986
+ const setLngProps = l => {
2987
+ this.language = l;
2988
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2989
+ this.resolvedLanguage = undefined;
2990
+ this.setResolvedLanguage(l);
2991
+ };
2992
+ const done = (err, l) => {
2993
+ if (l) {
2994
+ if (this.isLanguageChangingTo === lng) {
2995
+ setLngProps(l);
2996
+ this.translator.changeLanguage(l);
2997
+ this.isLanguageChangingTo = undefined;
2998
+ this.emit('languageChanged', l);
2999
+ this.logger.log('languageChanged', l);
3000
+ }
3001
+ } else {
3002
+ this.isLanguageChangingTo = undefined;
3003
+ }
3004
+ deferred.resolve((...args) => this.t(...args));
3005
+ if (callback) callback(err, (...args) => this.t(...args));
3006
+ };
3007
+ const setLng = lngs => {
3008
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
3009
+ const fl = isString(lngs) ? lngs : lngs && lngs[0];
3010
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
3011
+ if (l) {
3012
+ if (!this.language) {
3013
+ setLngProps(l);
3014
+ }
3015
+ if (!this.translator.language) this.translator.changeLanguage(l);
3016
+ this.services.languageDetector?.cacheUserLanguage?.(l);
3017
+ }
3018
+ this.loadResources(l, err => {
3019
+ done(err, l);
3020
+ });
3021
+ };
3022
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
3023
+ setLng(this.services.languageDetector.detect());
3024
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
3025
+ if (this.services.languageDetector.detect.length === 0) {
3026
+ this.services.languageDetector.detect().then(setLng);
3027
+ } else {
3028
+ this.services.languageDetector.detect(setLng);
3029
+ }
3030
+ } else {
3031
+ setLng(lng);
3032
+ }
3033
+ return deferred;
3034
+ }
3035
+ getFixedT(lng, ns, keyPrefix) {
3036
+ const fixedT = (key, opts, ...rest) => {
3037
+ let o;
3038
+ if (typeof opts !== 'object') {
3039
+ o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
3040
+ } else {
3041
+ o = {
3042
+ ...opts
3043
+ };
3044
+ }
3045
+ o.lng = o.lng || fixedT.lng;
3046
+ o.lngs = o.lngs || fixedT.lngs;
3047
+ o.ns = o.ns || fixedT.ns;
3048
+ if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
3049
+ const keySeparator = this.options.keySeparator || '.';
3050
+ let resultKey;
3051
+ if (o.keyPrefix && Array.isArray(key)) {
3052
+ resultKey = key.map(k => {
3053
+ if (typeof k === 'function') k = keysFromSelector(k, {
3054
+ ...this.options,
3055
+ ...opts
3056
+ });
3057
+ return `${o.keyPrefix}${keySeparator}${k}`;
3058
+ });
3059
+ } else {
3060
+ if (typeof key === 'function') key = keysFromSelector(key, {
3061
+ ...this.options,
3062
+ ...opts
3063
+ });
3064
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
3065
+ }
3066
+ return this.t(resultKey, o);
3067
+ };
3068
+ if (isString(lng)) {
3069
+ fixedT.lng = lng;
3070
+ } else {
3071
+ fixedT.lngs = lng;
3072
+ }
3073
+ fixedT.ns = ns;
3074
+ fixedT.keyPrefix = keyPrefix;
3075
+ return fixedT;
3076
+ }
3077
+ t(...args) {
3078
+ return this.translator?.translate(...args);
3079
+ }
3080
+ exists(...args) {
3081
+ return this.translator?.exists(...args);
3082
+ }
3083
+ setDefaultNamespace(ns) {
3084
+ this.options.defaultNS = ns;
3085
+ }
3086
+ hasLoadedNamespace(ns, options = {}) {
3087
+ if (!this.isInitialized) {
3088
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
3089
+ return false;
3090
+ }
3091
+ if (!this.languages || !this.languages.length) {
3092
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
3093
+ return false;
3094
+ }
3095
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
3096
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
3097
+ const lastLng = this.languages[this.languages.length - 1];
3098
+ if (lng.toLowerCase() === 'cimode') return true;
3099
+ const loadNotPending = (l, n) => {
3100
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
3101
+ return loadState === -1 || loadState === 0 || loadState === 2;
3102
+ };
3103
+ if (options.precheck) {
3104
+ const preResult = options.precheck(this, loadNotPending);
3105
+ if (preResult !== undefined) return preResult;
3106
+ }
3107
+ if (this.hasResourceBundle(lng, ns)) return true;
3108
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
3109
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
3110
+ return false;
3111
+ }
3112
+ loadNamespaces(ns, callback) {
3113
+ const deferred = defer();
3114
+ if (!this.options.ns) {
3115
+ if (callback) callback();
3116
+ return Promise.resolve();
3117
+ }
3118
+ if (isString(ns)) ns = [ns];
3119
+ ns.forEach(n => {
3120
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
3121
+ });
3122
+ this.loadResources(err => {
3123
+ deferred.resolve();
3124
+ if (callback) callback(err);
3125
+ });
3126
+ return deferred;
3127
+ }
3128
+ loadLanguages(lngs, callback) {
3129
+ const deferred = defer();
3130
+ if (isString(lngs)) lngs = [lngs];
3131
+ const preloaded = this.options.preload || [];
3132
+ const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
3133
+ if (!newLngs.length) {
3134
+ if (callback) callback();
3135
+ return Promise.resolve();
3136
+ }
3137
+ this.options.preload = preloaded.concat(newLngs);
3138
+ this.loadResources(err => {
3139
+ deferred.resolve();
3140
+ if (callback) callback(err);
3141
+ });
3142
+ return deferred;
3143
+ }
3144
+ dir(lng) {
3145
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
3146
+ if (!lng) return 'rtl';
3147
+ try {
3148
+ const l = new Intl.Locale(lng);
3149
+ if (l && l.getTextInfo) {
3150
+ const ti = l.getTextInfo();
3151
+ if (ti && ti.direction) return ti.direction;
3152
+ }
3153
+ } catch (e) {}
3154
+ 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'];
3155
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
3156
+ if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
3157
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
3158
+ }
3159
+ static createInstance(options = {}, callback) {
3160
+ const instance = new I18n(options, callback);
3161
+ instance.createInstance = I18n.createInstance;
3162
+ return instance;
3163
+ }
3164
+ cloneInstance(options = {}, callback = noop) {
3165
+ const forkResourceStore = options.forkResourceStore;
3166
+ if (forkResourceStore) delete options.forkResourceStore;
3167
+ const mergedOptions = {
3168
+ ...this.options,
3169
+ ...options,
3170
+ ...{
3171
+ isClone: true
3172
+ }
3173
+ };
3174
+ const clone = new I18n(mergedOptions);
3175
+ if (options.debug !== undefined || options.prefix !== undefined) {
3176
+ clone.logger = clone.logger.clone(options);
3177
+ }
3178
+ const membersToCopy = ['store', 'services', 'language'];
3179
+ membersToCopy.forEach(m => {
3180
+ clone[m] = this[m];
3181
+ });
3182
+ clone.services = {
3183
+ ...this.services
3184
+ };
3185
+ clone.services.utils = {
3186
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3187
+ };
3188
+ if (forkResourceStore) {
3189
+ const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
3190
+ prev[l] = {
3191
+ ...this.store.data[l]
3192
+ };
3193
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
3194
+ acc[n] = {
3195
+ ...prev[l][n]
3196
+ };
3197
+ return acc;
3198
+ }, prev[l]);
3199
+ return prev;
3200
+ }, {});
3201
+ clone.store = new ResourceStore(clonedData, mergedOptions);
3202
+ clone.services.resourceStore = clone.store;
3203
+ }
3204
+ if (options.interpolation) {
3205
+ const defOpts = get();
3206
+ const mergedInterpolation = {
3207
+ ...defOpts.interpolation,
3208
+ ...this.options.interpolation,
3209
+ ...options.interpolation
3210
+ };
3211
+ const mergedForInterpolator = {
3212
+ ...mergedOptions,
3213
+ interpolation: mergedInterpolation
3214
+ };
3215
+ clone.services.interpolator = new Interpolator(mergedForInterpolator);
3216
+ }
3217
+ clone.translator = new Translator$1(clone.services, mergedOptions);
3218
+ clone.translator.on('*', (event, ...args) => {
3219
+ clone.emit(event, ...args);
3220
+ });
3221
+ clone.init(mergedOptions, callback);
3222
+ clone.translator.options = mergedOptions;
3223
+ clone.translator.backendConnector.services.utils = {
3224
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3225
+ };
3226
+ return clone;
3227
+ }
3228
+ toJSON() {
3229
+ return {
3230
+ options: this.options,
3231
+ store: this.store,
3232
+ language: this.language,
3233
+ languages: this.languages,
3234
+ resolvedLanguage: this.resolvedLanguage
3235
+ };
3236
+ }
3237
+ }
3238
+ const instance = I18n.createInstance();
3239
+
3240
+ instance.createInstance;
3241
+ instance.dir;
3242
+ instance.init;
3243
+ instance.loadResources;
3244
+ instance.reloadResources;
3245
+ instance.use;
3246
+ instance.changeLanguage;
3247
+ instance.getFixedT;
3248
+ instance.t;
3249
+ instance.exists;
3250
+ instance.setDefaultNamespace;
3251
+ instance.hasLoadedNamespace;
3252
+ instance.loadNamespaces;
3253
+ instance.loadLanguages;
3254
+
3255
+ var en = {
3256
+ translation: {
3257
+ categorize: {
3258
+ limitMaxChoicesPerCategory:
3259
+ 'You\'ve reached the limit of {{maxChoicesPerCategory}} responses per area. To add another response, one must first be removed.',
3260
+ maxChoicesPerCategoryRestriction:
3261
+ 'To change this value to {{maxChoicesPerCategory}}, each category must have {{maxChoicesPerCategory}} or fewer answer choice[s].',
3262
+ },
3263
+ ebsr: {
3264
+ part: 'Part {{index}}',
3265
+ },
3266
+ numberLine: {
3267
+ addElementLimit_one: 'You can only add {{count}} element',
3268
+ addElementLimit_other: 'You can only add {{count}} elements',
3269
+ clearAll: 'Clear all',
3270
+ },
3271
+ imageClozeAssociation: {
3272
+ reachedLimit_one:
3273
+ 'You’ve reached the limit of {{count}} response per area. To add another response, one must first be removed.',
3274
+ reachedLimit_other: 'Full',
3275
+ },
3276
+ drawingResponse: {
3277
+ fillColor: 'Fill color',
3278
+ outlineColor: 'Outline color',
3279
+ noFill: 'No fill',
3280
+ lightblue: 'Light blue',
3281
+ lightyellow: 'Light yellow',
3282
+ red: 'Red',
3283
+ orange: 'Orange',
3284
+ yellow: 'Yellow',
3285
+ violet: 'Violet',
3286
+ blue: 'Blue',
3287
+ green: 'Green',
3288
+ white: 'White',
3289
+ black: 'Black',
3290
+ onDoubleClick: 'Double click to edit this text. Press Enter to submit.',
3291
+ },
3292
+ charting: {
3293
+ addCategory: 'Add category',
3294
+ actions: 'Actions',
3295
+ add: 'Add',
3296
+ delete: 'Delete',
3297
+ newLabel: 'New label',
3298
+ reachedLimit_other: "There can't be more than {{count}} categories.",
3299
+ keyLegend: {
3300
+ incorrectAnswer: 'Student incorrect answer',
3301
+ correctAnswer: 'Student correct answer',
3302
+ correctKeyAnswer: 'Answer key correct',
3303
+ },
3304
+ },
3305
+ graphing: {
3306
+ point: 'Point',
3307
+ circle: 'Circle',
3308
+ line: 'Line',
3309
+ parabola: 'Parabola',
3310
+ absolute: 'Absolute Value',
3311
+ exponential: 'Exponential',
3312
+ polygon: 'Polygon',
3313
+ ray: 'Ray',
3314
+ segment: 'Segment',
3315
+ sine: 'Sine',
3316
+ vector: 'Vector',
3317
+ label: 'Label',
3318
+ redo: 'Redo',
3319
+ reset: 'Reset',
3320
+ },
3321
+ mathInline: {
3322
+ primaryCorrectWithAlternates:
3323
+ 'Note: The answer shown above is the primary correct answer specified by the author for this item, but other answers may also be recognized as correct.',
3324
+ },
3325
+ multipleChoice: {
3326
+ minSelections: 'Select at least {{minSelections}}.',
3327
+ maxSelections_one: 'Only {{maxSelections}} answer is allowed.',
3328
+ maxSelections_other: 'Only {{maxSelections}} answers are allowed.',
3329
+ minmaxSelections_equal: 'Select {{minSelections}}.',
3330
+ minmaxSelections_range: 'Select between {{minSelections}} and {{maxSelections}}.',
3331
+ },
3332
+ selectText: {
3333
+ correctAnswerSelected: 'Correct',
3334
+ correctAnswerNotSelected: 'Correct Answer Not Selected',
3335
+ incorrectSelection: 'Incorrect Selection',
3336
+ key: 'Key',
3337
+ },
3338
+ },
3339
+ common: {
3340
+ undo: 'Undo',
3341
+ clearAll: 'Clear all',
3342
+ correct: 'Correct',
3343
+ incorrect: 'Incorrect',
3344
+ showCorrectAnswer: 'Show correct answer',
3345
+ hideCorrectAnswer: 'Hide correct answer',
3346
+ commonCorrectAnswerWithAlternates:
3347
+ 'Note: The answer shown above is the most common correct answer for this item. One or more additional correct answers are also defined, and will also be recognized as correct.',
3348
+ warning: 'Warning',
3349
+ showNote: 'Show Note',
3350
+ hideNote: 'Hide Note',
3351
+ cancel: 'Cancel',
3352
+ },
3353
+ };
3354
+
3355
+ var es = {
3356
+ translation: {
3357
+ categorize: {
3358
+ limitMaxChoicesPerCategory:
3359
+ 'Has alcanzado el límite de {{maxChoicesPerCategory}} respuestas por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
3360
+ maxChoicesPerCategoryRestriction:
3361
+ 'Para cambiar este valor a {{maxChoicesPerCategory}}, cada categoría debe tener {{maxChoicesPerCategory}} o menos opciones de respuesta',
3362
+ },
3363
+ ebsr: {
3364
+ part: 'Parte {{index}}',
3365
+ },
3366
+ numberLine: {
3367
+ addElementLimit_one: 'Solo puedes agregar {{count}} elemento',
3368
+ addElementLimit_other: 'Solo puedes agregar {{count}} elementos',
3369
+ clearAll: 'Borrar todo',
3370
+ },
3371
+ imageClozeAssociation: {
3372
+ reachedLimit_one:
3373
+ 'Has alcanzado el límite de {{count}} respuesta por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.',
3374
+ reachedLimit_other: 'Lleno',
3375
+ },
3376
+ drawingResponse: {
3377
+ fillColor: 'Color de relleno',
3378
+ outlineColor: 'Color del contorno',
3379
+ noFill: 'Sin relleno',
3380
+ lightblue: 'Azul claro',
3381
+ lightyellow: 'Amarillo claro',
3382
+ red: 'Rojo',
3383
+ orange: 'Naranja',
3384
+ yellow: 'Amarillo',
3385
+ violet: 'Violeta',
3386
+ blue: 'Azul',
3387
+ green: 'Verde',
3388
+ white: 'Blanco',
3389
+ black: 'Negro',
3390
+ onDoubleClick: 'Haz doble clic para revisar este texto. Presiona el botón de ingreso para enviar',
3391
+ },
3392
+ charting: {
3393
+ addCategory: 'Añadir categoría',
3394
+ actions: 'Acciones',
3395
+ add: 'Añadir',
3396
+ delete: 'Eliminar',
3397
+ newLabel: 'Nueva etiqueta',
3398
+ reachedLimit_other: 'No puede haber más de {{count}} categorías.',
3399
+ keyLegend: {
3400
+ incorrectAnswer: 'Respuesta incorrecta del estudiante',
3401
+ correctAnswer: 'Respuesta correcta del estudiante',
3402
+ correctKeyAnswer: 'Clave de respuesta correcta',
3403
+ },
3404
+ },
3405
+ graphing: {
3406
+ point: 'Punto',
3407
+ circle: 'Circulo',
3408
+ line: 'Línea',
3409
+ parabola: 'Parábola',
3410
+ absolute: 'Valor absoluto',
3411
+ exponential: 'Exponencial',
3412
+ polygon: 'Polígono',
3413
+ ray: 'Semirrecta',
3414
+ segment: 'Segmento ',
3415
+ sine: 'Seno',
3416
+ vector: 'Vector',
3417
+ label: 'Etiqueta',
3418
+ redo: 'Rehacer',
3419
+ reset: 'Reiniciar',
3420
+ },
3421
+ mathInline: {
3422
+ primaryCorrectWithAlternates:
3423
+ 'Nota: La respuesta que se muestra arriba es la respuesta correcta principal especificada por el autor para esta pregunta, pero también se pueden reconocer otras respuestas como correctas.',
3424
+ },
3425
+ multipleChoice: {
3426
+ minSelections: 'Seleccione al menos {{minSelections}}.',
3427
+ maxSelections_one: 'Sólo se permite {{maxSelections}} respuesta.',
3428
+ maxSelections_other: 'Sólo se permiten {{maxSelections}} respuestas.',
3429
+ minmaxSelections_equal: 'Seleccione {{minSelections}}.',
3430
+ minmaxSelections_range: 'Seleccione entre {{minSelections}} y {{maxSelections}}.',
3431
+ },
3432
+ selectText: {
3433
+ correctAnswerSelected: 'Respuesta Correcta',
3434
+ correctAnswerNotSelected: 'Respuesta Correcta No Seleccionada',
3435
+ incorrectSelection: 'Selección Incorrecta',
3436
+ key: 'Clave',
3437
+ },
3438
+ },
3439
+ common: {
3440
+ undo: 'Deshacer',
3441
+ clearAll: 'Borrar todo',
3442
+ correct: 'Correct',
3443
+ incorrect: 'Incorrect',
3444
+ showCorrectAnswer: 'Mostrar respuesta correcta',
3445
+ hideCorrectAnswer: 'Ocultar respuesta correcta',
3446
+ commonCorrectAnswerWithAlternates:
3447
+ 'Nota: La respuesta que se muestra arriba es la respuesta correcta más común para esta pregunta. También se definen una o más respuestas correctas adicionales, y también se reconocerán como correctas.',
3448
+ warning: 'Advertencia',
3449
+ showNote: 'Mostrar Nota',
3450
+ hideNote: 'Ocultar Nota',
3451
+ cancel: 'Cancelar',
3452
+ },
3453
+ };
3454
+
3455
+ instance.init({
3456
+ fallbackLng: 'en',
3457
+ lng: 'en',
3458
+ debug: true,
3459
+ resources: {
3460
+ en: en,
3461
+ es: es,
3462
+ },
3463
+ });
3464
+
3465
+ var Translator = {
3466
+ translator: {
3467
+ ...instance,
3468
+ t: (key, options) => {
3469
+ const { lng } = options;
3470
+
3471
+ switch (lng) {
3472
+ // these keys don't work with plurals, don't know why, so I added a workaround to convert them to the correct lng
3473
+ case 'en_US':
3474
+ case 'en-US':
3475
+ options.lng = 'en';
3476
+ break;
3477
+ case 'es_ES':
3478
+ case 'es-ES':
3479
+ case 'es_MX':
3480
+ case 'es-MX':
3481
+ options.lng = 'es';
3482
+ break;
3483
+ }
3484
+ return instance.t(key, { lng, ...options });
3485
+ },
3486
+ },
3487
+ languageOptions: [
3488
+ { value: 'en_US', label: 'English (US)' },
3489
+ { value: 'es_ES', label: 'Spanish' },
3490
+ ],
3491
+ };
3492
+
3493
+ var defaults = {
3494
+ allowTrailingZerosDefault: false,
3495
+ customKeys: [],
3496
+ equationEditor: '8',
3497
+ expression: '',
3498
+ feedback: {
3499
+ correct: { default: 'Correct', type: 'none' },
3500
+ incorrect: { default: 'Incorrect', type: 'none' },
3501
+ partial: { default: 'Nearly', type: 'none' },
3502
+ },
3503
+ feedbackEnabled: false,
3504
+ ignoreOrderDefault: false,
3505
+ partialScoring: true,
3506
+ prompt: '',
3507
+ promptEnabled: true,
3508
+ rationale: '',
3509
+ rationaleEnabled: true,
3510
+ responseType: ResponseTypes.advanced,
3511
+ responses: [],
3512
+ scoringType: 'auto',
3513
+ studentInstructionsEnabled: true,
3514
+ teacherInstructions: '',
3515
+ teacherInstructionsEnabled: true,
3516
+ toolbarEditorPosition: 'bottom',
3517
+ validationDefault: 'literal',
3518
+ };
3519
+
3520
+ const { translator } = Translator;
3521
+
3522
+ const log = debug();
3523
+
3524
+ const getResponseCorrectness = (model, answerItem, isOutcome) => {
3525
+ const correctResponses = model.responses;
3526
+ const isAdvanced = model.responseType === ResponseTypes.advanced;
3527
+
3528
+ if (!answerItem) {
3529
+ return {
3530
+ correctness: 'unanswered',
3531
+ score: isOutcome ? 0 : '0%',
3532
+ correct: false,
3533
+ };
3534
+ }
3535
+
3536
+ const isAnswerCorrect = getIsAnswerCorrect(isAdvanced ? correctResponses : correctResponses.slice(0, 1), answerItem);
3537
+
3538
+ const correctnessObject = {
3539
+ correctness: 'incorrect',
3540
+ score: isOutcome ? 0 : '0%',
3541
+ correct: false,
3542
+ };
3543
+
3544
+ if (isAnswerCorrect) {
3545
+ correctnessObject.correctness = 'correct';
3546
+ correctnessObject.score = isOutcome ? 1 : '100%';
3547
+ correctnessObject.correct = true;
3548
+ }
3549
+
3550
+ return correctnessObject;
3551
+ };
3552
+
3553
+ function getIsAnswerCorrect(correctResponseItems, answerItem) {
3554
+ let answerCorrect = false;
3555
+
3556
+ (correctResponseItems || []).forEach((correctResponse) => {
3557
+ if (answerCorrect) return;
3558
+
3559
+ const opts = {
3560
+ mode: correctResponse.validation || defaults.validationDefault,
3561
+ };
3562
+
3563
+ if (opts.mode === 'literal') {
3564
+ opts.literal = {
3565
+ allowTrailingZeros: correctResponse.allowTrailingZeros || false,
3566
+ ignoreOrder: correctResponse.ignoreOrder || false,
3567
+ };
3568
+ }
3569
+
3570
+ const acceptedValues = [correctResponse.answer].concat(
3571
+ Object.keys(correctResponse.alternates || {}).map((alternateId) => correctResponse.alternates[alternateId]),
3572
+ );
3573
+
3574
+ for (let i = 0; i < acceptedValues.length; i++) {
3575
+ try {
3576
+ if (mv.latexEqual(answerItem, acceptedValues[i], opts)) {
3577
+ answerCorrect = true;
3578
+ break;
3579
+ }
3580
+ } catch (e) {
3581
+ log('Parse failure when evaluating math', acceptedValues[i], answerItem, e);
3582
+ continue;
3583
+ }
3584
+ }
3585
+ });
3586
+
3587
+ return answerCorrect;
3588
+ }
3589
+
3590
+ const getCorrectness = (question, env, session, isOutcome) => {
3591
+ if (env.mode === 'evaluate') {
3592
+ return getResponseCorrectness(
3593
+ question,
3594
+ question.responseType === ResponseTypes.advanced
3595
+ ? (session && session.completeAnswer) || ''
3596
+ : session && session.response,
3597
+ isOutcome,
3598
+ );
3599
+ }
3600
+
3601
+ return undefined;
3602
+ };
3603
+
3604
+ function createDefaultModel(model = {}) {
3605
+ return new Promise((resolve) => {
3606
+ resolve({
3607
+ config: {
3608
+ ...defaults,
3609
+ ...model,
3610
+ },
3611
+ });
3612
+ });
3613
+ }
3614
+
3615
+ const outcome = (question, session, env) => {
3616
+ return new Promise((resolve) => {
3617
+ if (env.mode !== 'evaluate') {
3618
+ resolve({ score: undefined, completed: undefined });
3619
+ } else {
3620
+ if (!session || isEmpty_1(session)) {
3621
+ resolve({ score: 0, empty: true });
3622
+ } else {
3623
+ const correctness = getCorrectness(question, env, session, true);
3624
+
3625
+ resolve({ score: correctness.score });
3626
+ }
3627
+ }
3628
+ });
3629
+ };
3630
+
3631
+ const normalize = (question) => {
3632
+ // making sure that defaults are set
3633
+ if (!isEmpty_1(question.responses)) {
3634
+ question.responses = question.responses.map((correctResponse) => ({
3635
+ ...correctResponse,
3636
+ validation: correctResponse.validation || question.validationDefault,
3637
+ allowTrailingZeros: correctResponse.allowTrailingZeros || question.allowTrailingZerosDefault,
3638
+ ignoreOrder: correctResponse.ignoreOrder || question.ignoreOrderDefault,
3639
+ }));
3640
+ }
3641
+
3642
+ return { ...defaults, ...question };
3643
+ };
3644
+
3645
+ const model = (question, session, env) =>
3646
+ new Promise((resolve) => {
3647
+ const normalizedQuestion = normalize(question);
3648
+ const correctness = getCorrectness(normalizedQuestion, env, session);
3649
+ const { extraCSSRules, responses, language, ...config } = normalizedQuestion;
3650
+
3651
+ config.responses = config.responseType === ResponseTypes.simple ? responses.slice(0, 1) : responses;
3652
+
3653
+ const feedback =
3654
+ env.mode === 'evaluate' && normalizedQuestion.feedbackEnabled
3655
+ ? getActualFeedbackForCorrectness(correctness?.correctness, normalizedQuestion.feedback)
3656
+ : undefined;
3657
+
3658
+ const out = {
3659
+ extraCSSRules,
3660
+ config,
3661
+ correctness,
3662
+ feedback,
3663
+ disabled: env.mode !== 'gather',
3664
+ view: env.mode === 'view',
3665
+ };
3666
+
3667
+ const note = normalizedQuestion.note || translator.t('mathInline.primaryCorrectWithAlternates', { lng: language });
3668
+ const showNote =
3669
+ config?.responses?.length > 1 ||
3670
+ (config?.responses || []).some(
3671
+ (response) => response.validation === 'symbolic' || Object.keys(response.alternates || {}).length > 0,
3672
+ );
3673
+
3674
+ if (env.mode === 'evaluate') {
3675
+ out.correctResponse = {};
3676
+ out.config.showNote = showNote;
3677
+ out.config.note = note;
3678
+ } else {
3679
+ out.config.responses = [];
3680
+ out.config.showNote = false;
3681
+ }
3682
+
3683
+ if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {
3684
+ out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;
3685
+ out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled
3686
+ ? normalizedQuestion.teacherInstructions
3687
+ : null;
3688
+ } else {
3689
+ out.rationale = null;
3690
+ out.teacherInstructions = null;
3691
+ out.config.rationale = null;
3692
+ out.config.teacherInstructions = null;
3693
+ }
3694
+
3695
+ out.config.env = env;
3696
+ out.config.prompt = normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null;
3697
+ out.language = language;
3698
+ resolve(out);
3699
+ });
3700
+
3701
+ const escape = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
3702
+
3703
+ const simpleSessionResponse = (question) =>
3704
+ new Promise((resolve) => {
3705
+ const { responses, id } = question;
3706
+ const { answer } = responses && responses.length ? responses[0] : {};
3707
+
3708
+ resolve({
3709
+ id,
3710
+ response: answer || '',
3711
+ completeAnswer: answer || '',
3712
+ });
3713
+ });
3714
+
3715
+ // use this for items like E672793
3716
+ const removeTrailingEscape = (str) => (str.endsWith('\\') ? str.slice(0, -1) : str);
3717
+
3718
+ const advancedSessionResponse = (question) =>
3719
+ new Promise((resolve) => {
3720
+ const { responses, id } = question;
3721
+ const { answer } = responses && responses.length ? responses[0] : {};
3722
+
3723
+ if (!answer) {
3724
+ resolve({
3725
+ id,
3726
+ answers: {},
3727
+ completeAnswer: '',
3728
+ });
3729
+
3730
+ return;
3731
+ }
3732
+
3733
+ try {
3734
+ const e = question.expression;
3735
+ const RESPONSE_TOKEN = /\\{\\{\s*response\s*\\}\\}/g;
3736
+
3737
+ const o = escape(e).split(RESPONSE_TOKEN);
3738
+ const to = o.map((t) => (t === '' ? t : t.replace(/\s+/g, () => '\\s*')));
3739
+ const tt = to.join('(.*)');
3740
+
3741
+ const m = answer.match(new RegExp(tt));
3742
+
3743
+ const count = o.length - 1;
3744
+
3745
+ if (!m) {
3746
+ resolve({
3747
+ id,
3748
+ answers: {},
3749
+ completeAnswer: answer,
3750
+ });
3751
+
3752
+ // eslint-disable-next-line no-console
3753
+ console.log(`can not find match: ${o} in ${answer}`);
3754
+
3755
+ return;
3756
+ }
3757
+
3758
+ m.shift();
3759
+
3760
+ const answers = {};
3761
+
3762
+ for (var i = 0; i < count; i++) {
3763
+ answers[`r${i + 1}`] = { value: removeTrailingEscape(m[i].trim()) };
3764
+ }
3765
+
3766
+ resolve({
3767
+ id,
3768
+ answers,
3769
+ completeAnswer: answer,
3770
+ });
3771
+ } catch (e) {
3772
+ resolve({
3773
+ id,
3774
+ answers: {},
3775
+ completeAnswer: answer,
3776
+ });
3777
+ // eslint-disable-next-line no-console
3778
+ console.error(e.toString());
3779
+ }
3780
+ });
3781
+
3782
+ const createCorrectResponseSession = (question, env) => {
3783
+ if (env.mode === 'evaluate' || env.role !== 'instructor') {
3784
+ // eslint-disable-next-line no-console
3785
+ console.error('can not create correct response session if mode is evaluate or role is not instructor');
3786
+
3787
+ return Promise.resolve(null);
3788
+ }
3789
+
3790
+ if ((question.responseType || '').toLowerCase() === 'simple') {
3791
+ return simpleSessionResponse(question);
3792
+ } else {
3793
+ return advancedSessionResponse(question);
3794
+ }
3795
+ };
3796
+
3797
+ // remove all html tags except img, iframe and source tag for audio
3798
+ const getContent = (html) => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');
3799
+
3800
+ const validate = (model = {}, config = {}) => {
3801
+ const { expression = '', responses, responseType } = model;
3802
+ const { maxResponseAreas } = config;
3803
+ const responsesErrors = {};
3804
+ const errors = {};
3805
+
3806
+ ['teacherInstructions', 'prompt', 'rationale'].forEach((field) => {
3807
+ if (config[field]?.required && !getContent(model[field])) {
3808
+ errors[field] = 'This field is required.';
3809
+ }
3810
+ });
3811
+
3812
+ (responses || []).forEach((response, index) => {
3813
+ const { answer } = response;
3814
+ const reversedAlternates = [...Object.entries(response.alternates || {})].reverse();
3815
+ const alternatesErrors = {};
3816
+ const responseError = {};
3817
+
3818
+ if (answer === '') {
3819
+ responseError.answer = 'Content should not be empty.';
3820
+ }
3821
+
3822
+ reversedAlternates.forEach(([key, value], index) => {
3823
+ if (value === '') {
3824
+ alternatesErrors[key] = 'Content should not be empty.';
3825
+ } else {
3826
+ const identicalAnswer =
3827
+ answer === value || reversedAlternates.slice(index + 1).some(([, val]) => val === value);
3828
+
3829
+ if (identicalAnswer) {
3830
+ alternatesErrors[key] = 'Content should be unique.';
3831
+ }
3832
+ }
3833
+ });
3834
+
3835
+ if (!isEmpty_1(responseError) || !isEmpty_1(alternatesErrors)) {
3836
+ responsesErrors[index] = { ...responseError, ...alternatesErrors };
3837
+ }
3838
+ });
3839
+
3840
+ if (responseType === 'Advanced Multi') {
3841
+ const nbOfResponseAreas = (expression.match(/\{\{response\}\}/g) || []).length;
3842
+
3843
+ if (nbOfResponseAreas > maxResponseAreas) {
3844
+ errors.responseAreasError = `No more than ${maxResponseAreas} response areas should be defined.`;
3845
+ } else if (nbOfResponseAreas < 1) {
3846
+ errors.responseAreasError = 'There should be at least 1 response area defined.';
3847
+ }
3848
+ }
3849
+
3850
+ if (!isEmpty_1(responsesErrors)) {
3851
+ errors.responsesErrors = responsesErrors;
3852
+ }
3853
+
3854
+ return errors;
3855
+ };
3856
+
3857
+ export { createCorrectResponseSession, createDefaultModel, model, normalize, outcome, validate };