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