@pie-element/math-inline 11.1.0-next.0 → 11.1.2-next.2

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