hrm_ui_lib 2.0.0-alpha.12 → 2.0.0-alpha.13

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.
Files changed (117) hide show
  1. package/components/Alert/Alert.js +1 -1
  2. package/components/Alert/index.js +1 -1
  3. package/components/Avatar/Avatar.js +1 -1
  4. package/components/Avatar/AvatarGroup.js +1 -1
  5. package/components/Avatar/index.js +1 -1
  6. package/components/Button/Button.js +1 -1
  7. package/components/Button/index.js +1 -1
  8. package/components/Card/Card.js +1 -1
  9. package/components/Card/CardComponent/CardHead.js +1 -1
  10. package/components/Card/index.js +1 -1
  11. package/components/Checkbox/Checkbox.js +1 -1
  12. package/components/Checkbox/index.js +1 -1
  13. package/components/Copy/Copy.js +1 -1
  14. package/components/Copy/index.js +1 -1
  15. package/components/Counter/Counter.js +1 -1
  16. package/components/Counter/index.js +1 -1
  17. package/components/DatePicker/CustomHeader/CustomHeader.js +1 -1
  18. package/components/DatePicker/RangeDatePicker/RangeDatePicker.js +1 -1
  19. package/components/DatePicker/RangeDatePicker/RangeDatePickerDesktop.js +1 -1
  20. package/components/DatePicker/RangeDatePicker/RangeDatePickerMobile.js +1 -1
  21. package/components/DatePicker/RangeDatePicker/index.js +1 -1
  22. package/components/DatePicker/SimpleDatePicker/SimpleDatePicker.js +1 -1
  23. package/components/DatePicker/SimpleDatePicker/SimpleDatePickerDesktop.js +1 -1
  24. package/components/DatePicker/SimpleDatePicker/SimpleDatePickerMobile.js +1 -1
  25. package/components/DatePicker/SimpleDatePicker/index.js +1 -1
  26. package/components/DatePicker/TimePicker/MobileModalContent.js +1 -1
  27. package/components/DatePicker/TimePicker/TimePicker.js +1 -1
  28. package/components/DatePicker/TimePicker/TimePickerDesktop.js +1 -1
  29. package/components/DatePicker/TimePicker/TimePickerMobile.js +1 -1
  30. package/components/DatePicker/TimePicker/index.js +1 -1
  31. package/components/DatePicker/index.js +1 -1
  32. package/components/Empty/Empty.js +1 -1
  33. package/components/Empty/index.js +1 -1
  34. package/components/FileUpload/DropzoneFileUpload/DropzoneFileUpload.js +1 -1
  35. package/components/FileUpload/DropzoneFileUpload/ErrorItem.js +1 -1
  36. package/components/FileUpload/DropzoneFileUpload/PreviewItem.js +1 -1
  37. package/components/FileUpload/DropzoneFileUpload/helpers.js +1 -1
  38. package/components/FileUpload/DropzoneFileUpload/index.js +1 -1
  39. package/components/FileUpload/FileUpload.js +1 -1
  40. package/components/FileUpload/UploadItems.js +1 -1
  41. package/components/FileUpload/index.js +1 -1
  42. package/components/FormContainer/FormContainer.js +3 -16
  43. package/components/FormContainer/index.js +1 -4
  44. package/components/FormField/FormField.js +1 -1
  45. package/components/FormField/index.js +1 -1
  46. package/components/Input/Input.js +1 -1
  47. package/components/Input/index.js +1 -1
  48. package/components/Menu/Menu.js +1 -1
  49. package/components/Menu/NestedMenu.js +1 -1
  50. package/components/Menu/index.js +1 -1
  51. package/components/Modal/Modal.js +1 -1
  52. package/components/Modal/ModalConfirmation.js +1 -1
  53. package/components/Modal/ModalContent.js +1 -1
  54. package/components/Modal/index.js +1 -1
  55. package/components/More/More.js +1 -1
  56. package/components/More/index.js +1 -1
  57. package/components/Popover/Popover.js +1 -1
  58. package/components/Popover/PopoverMobile.js +1 -1
  59. package/components/Popover/index.js +1 -1
  60. package/components/Radio/RadioGroup.js +1 -1
  61. package/components/Radio/index.js +1 -1
  62. package/components/Select/ButtonSelect/ButtonSelect.js +1 -1
  63. package/components/Select/FilterSelect/FilterDropdown.js +1 -1
  64. package/components/Select/FilterSelect/FilterGroupDropdown.js +1 -1
  65. package/components/Select/FilterSelect/FilterSelect.js +1 -1
  66. package/components/Select/MultiSelect/MobileWrapper.js +1 -1
  67. package/components/Select/MultiSelect/MultiBase/MultiBase.js +1 -1
  68. package/components/Select/MultiSelect/MultiSelect.js +1 -1
  69. package/components/Select/MultiSelect/MultiSelectGrouped/MultiSelectGrouped.js +1 -1
  70. package/components/Select/MultiSelect/MultiSelectWithTabs/MultiSelectWithTabs.js +1 -1
  71. package/components/Select/MultiSelect/OptionsWrapper.js +1 -1
  72. package/components/Select/NestedSelect/NestedSelect.js +1 -1
  73. package/components/Select/Select/Select.js +1 -1
  74. package/components/Select/Select/SelectDesktop/index.js +1 -1
  75. package/components/Select/Select/SelectMobile/MobileTopContent.js +1 -1
  76. package/components/Select/Select/SelectMobile/index.js +1 -1
  77. package/components/Select/SharedComponents/Actions.js +1 -1
  78. package/components/Select/SharedComponents/ButtonSelectWrapper/ButtonSelectWrapper.js +1 -1
  79. package/components/Select/SharedComponents/ContentTop.js +1 -1
  80. package/components/Select/SharedComponents/Footer.js +1 -1
  81. package/components/Select/SharedComponents/InputSelectWrapper/InputSelectWrapper.js +1 -1
  82. package/components/Select/SharedComponents/index.js +1 -1
  83. package/components/Select/index.js +1 -1
  84. package/components/SideSheet/Footer/Footer.js +1 -1
  85. package/components/SideSheet/SideSheet.js +1 -1
  86. package/components/SideSheet/index.js +1 -1
  87. package/components/Snackbar/Snackbar.js +2 -5
  88. package/components/Snackbar/index.js +1 -1
  89. package/components/Switcher/Switcher.js +1 -1
  90. package/components/Switcher/index.js +1 -1
  91. package/components/Table/Header.js +1 -1
  92. package/components/Table/IndeterminateCheckbox.js +1 -1
  93. package/components/Table/Row.js +1 -1
  94. package/components/Table/Table.js +1 -1
  95. package/components/Table/index.js +1 -1
  96. package/components/Table/utils.js +1 -1
  97. package/components/TableV2/AdvancedPagination.js +1 -1
  98. package/components/TableV2/ColumnSettings.js +1 -1
  99. package/components/TableV2/IndeterminateCheckbox.js +1 -1
  100. package/components/TableV2/Table.js +1 -1
  101. package/components/TableV2/hooks/useTableControl.js +1 -1
  102. package/components/TableV2/index.js +1 -1
  103. package/components/Textarea/Textarea.js +1 -1
  104. package/components/Textarea/index.js +1 -1
  105. package/helperComponents/GoToWebPage/GoToWebPage.js +1 -1
  106. package/helperComponents/OptionItem/OptionItem.js +1 -1
  107. package/helperComponents/OptionItem/index.js +1 -1
  108. package/helperComponents/index.js +1 -1
  109. package/helpers/check-authorization.js +1 -1
  110. package/helpers/index.js +1 -1
  111. package/index.d.ts +0 -1
  112. package/index.js +6 -7
  113. package/package.json +1 -1
  114. package/i18n.d.ts +0 -4
  115. package/i18n.js +0 -2676
  116. package/node-ponyfill-CCC52WRr.js +0 -81701
  117. /package/{Alert--0rz5XL1.js → Alert-Ocpfzvmz.js} +0 -0
package/i18n.js DELETED
@@ -1,2676 +0,0 @@
1
- import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
2
- import _regeneratorRuntime from '@babel/runtime/regenerator';
3
- import { getTranslationLocale } from './helpers/locale.js';
4
- import './type/locale.js';
5
- import './helpers/storage.js';
6
-
7
- const isString = obj => typeof obj === 'string';
8
- const defer = () => {
9
- let res;
10
- let rej;
11
- const promise = new Promise((resolve, reject) => {
12
- res = resolve;
13
- rej = reject;
14
- });
15
- promise.resolve = res;
16
- promise.reject = rej;
17
- return promise;
18
- };
19
- const makeString = object => {
20
- if (object == null) return '';
21
- return '' + object;
22
- };
23
- const copy = (a, s, t) => {
24
- a.forEach(m => {
25
- if (s[m]) t[m] = s[m];
26
- });
27
- };
28
- const lastOfPathSeparatorRegExp = /###/g;
29
- const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
30
- const canNotTraverseDeeper = object => !object || isString(object);
31
- const getLastOfPath = (object, path, Empty) => {
32
- const stack = !isString(path) ? path : path.split('.');
33
- let stackIndex = 0;
34
- while (stackIndex < stack.length - 1) {
35
- if (canNotTraverseDeeper(object)) return {};
36
- const key = cleanKey(stack[stackIndex]);
37
- if (!object[key] && Empty) object[key] = new Empty();
38
- if (Object.prototype.hasOwnProperty.call(object, key)) {
39
- object = object[key];
40
- } else {
41
- object = {};
42
- }
43
- ++stackIndex;
44
- }
45
- if (canNotTraverseDeeper(object)) return {};
46
- return {
47
- obj: object,
48
- k: cleanKey(stack[stackIndex])
49
- };
50
- };
51
- const setPath = (object, path, newValue) => {
52
- const {
53
- obj,
54
- k
55
- } = getLastOfPath(object, path, Object);
56
- if (obj !== undefined || path.length === 1) {
57
- obj[k] = newValue;
58
- return;
59
- }
60
- let e = path[path.length - 1];
61
- let p = path.slice(0, path.length - 1);
62
- let last = getLastOfPath(object, p, Object);
63
- while (last.obj === undefined && p.length) {
64
- e = `${p[p.length - 1]}.${e}`;
65
- p = p.slice(0, p.length - 1);
66
- last = getLastOfPath(object, p, Object);
67
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
68
- last.obj = undefined;
69
- }
70
- }
71
- last.obj[`${last.k}.${e}`] = newValue;
72
- };
73
- const pushPath = (object, path, newValue, concat) => {
74
- const {
75
- obj,
76
- k
77
- } = getLastOfPath(object, path, Object);
78
- obj[k] = obj[k] || [];
79
- obj[k].push(newValue);
80
- };
81
- const getPath = (object, path) => {
82
- const {
83
- obj,
84
- k
85
- } = getLastOfPath(object, path);
86
- if (!obj) return undefined;
87
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
88
- return obj[k];
89
- };
90
- const getPathWithDefaults = (data, defaultData, key) => {
91
- const value = getPath(data, key);
92
- if (value !== undefined) {
93
- return value;
94
- }
95
- return getPath(defaultData, key);
96
- };
97
- const deepExtend = (target, source, overwrite) => {
98
- for (const prop in source) {
99
- if (prop !== '__proto__' && prop !== 'constructor') {
100
- if (prop in target) {
101
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
102
- if (overwrite) target[prop] = source[prop];
103
- } else {
104
- deepExtend(target[prop], source[prop], overwrite);
105
- }
106
- } else {
107
- target[prop] = source[prop];
108
- }
109
- }
110
- }
111
- return target;
112
- };
113
- const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
114
- var _entityMap = {
115
- '&': '&amp;',
116
- '<': '&lt;',
117
- '>': '&gt;',
118
- '"': '&quot;',
119
- "'": '&#39;',
120
- '/': '&#x2F;'
121
- };
122
- const escape = data => {
123
- if (isString(data)) {
124
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
125
- }
126
- return data;
127
- };
128
- class RegExpCache {
129
- constructor(capacity) {
130
- this.capacity = capacity;
131
- this.regExpMap = new Map();
132
- this.regExpQueue = [];
133
- }
134
- getRegExp(pattern) {
135
- const regExpFromCache = this.regExpMap.get(pattern);
136
- if (regExpFromCache !== undefined) {
137
- return regExpFromCache;
138
- }
139
- const regExpNew = new RegExp(pattern);
140
- if (this.regExpQueue.length === this.capacity) {
141
- this.regExpMap.delete(this.regExpQueue.shift());
142
- }
143
- this.regExpMap.set(pattern, regExpNew);
144
- this.regExpQueue.push(pattern);
145
- return regExpNew;
146
- }
147
- }
148
- const chars = [' ', ',', '?', '!', ';'];
149
- const looksLikeObjectPathRegExpCache = new RegExpCache(20);
150
- const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
151
- nsSeparator = nsSeparator || '';
152
- keySeparator = keySeparator || '';
153
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
154
- if (possibleChars.length === 0) return true;
155
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
156
- let matched = !r.test(key);
157
- if (!matched) {
158
- const ki = key.indexOf(keySeparator);
159
- if (ki > 0 && !r.test(key.substring(0, ki))) {
160
- matched = true;
161
- }
162
- }
163
- return matched;
164
- };
165
- const deepFind = (obj, path, keySeparator = '.') => {
166
- if (!obj) return undefined;
167
- if (obj[path]) {
168
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
169
- return obj[path];
170
- }
171
- const tokens = path.split(keySeparator);
172
- let current = obj;
173
- for (let i = 0; i < tokens.length;) {
174
- if (!current || typeof current !== 'object') {
175
- return undefined;
176
- }
177
- let next;
178
- let nextPath = '';
179
- for (let j = i; j < tokens.length; ++j) {
180
- if (j !== i) {
181
- nextPath += keySeparator;
182
- }
183
- nextPath += tokens[j];
184
- next = current[nextPath];
185
- if (next !== undefined) {
186
- if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
187
- continue;
188
- }
189
- i += j - i + 1;
190
- break;
191
- }
192
- }
193
- current = next;
194
- }
195
- return current;
196
- };
197
- const getCleanedCode = code => code?.replace('_', '-');
198
-
199
- const consoleLogger = {
200
- type: 'logger',
201
- log(args) {
202
- this.output('log', args);
203
- },
204
- warn(args) {
205
- this.output('warn', args);
206
- },
207
- error(args) {
208
- this.output('error', args);
209
- },
210
- output(type, args) {
211
- console?.[type]?.apply?.(console, args);
212
- }
213
- };
214
- class Logger {
215
- constructor(concreteLogger, options = {}) {
216
- this.init(concreteLogger, options);
217
- }
218
- init(concreteLogger, options = {}) {
219
- this.prefix = options.prefix || 'i18next:';
220
- this.logger = concreteLogger || consoleLogger;
221
- this.options = options;
222
- this.debug = options.debug;
223
- }
224
- log(...args) {
225
- return this.forward(args, 'log', '', true);
226
- }
227
- warn(...args) {
228
- return this.forward(args, 'warn', '', true);
229
- }
230
- error(...args) {
231
- return this.forward(args, 'error', '');
232
- }
233
- deprecate(...args) {
234
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
235
- }
236
- forward(args, lvl, prefix, debugOnly) {
237
- if (debugOnly && !this.debug) return null;
238
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
239
- return this.logger[lvl](args);
240
- }
241
- create(moduleName) {
242
- return new Logger(this.logger, {
243
- ...{
244
- prefix: `${this.prefix}:${moduleName}:`
245
- },
246
- ...this.options
247
- });
248
- }
249
- clone(options) {
250
- options = options || this.options;
251
- options.prefix = options.prefix || this.prefix;
252
- return new Logger(this.logger, options);
253
- }
254
- }
255
- var baseLogger = new Logger();
256
-
257
- class EventEmitter {
258
- constructor() {
259
- this.observers = {};
260
- }
261
- on(events, listener) {
262
- events.split(' ').forEach(event => {
263
- if (!this.observers[event]) this.observers[event] = new Map();
264
- const numListeners = this.observers[event].get(listener) || 0;
265
- this.observers[event].set(listener, numListeners + 1);
266
- });
267
- return this;
268
- }
269
- off(event, listener) {
270
- if (!this.observers[event]) return;
271
- if (!listener) {
272
- delete this.observers[event];
273
- return;
274
- }
275
- this.observers[event].delete(listener);
276
- }
277
- emit(event, ...args) {
278
- if (this.observers[event]) {
279
- const cloned = Array.from(this.observers[event].entries());
280
- cloned.forEach(([observer, numTimesAdded]) => {
281
- for (let i = 0; i < numTimesAdded; i++) {
282
- observer(...args);
283
- }
284
- });
285
- }
286
- if (this.observers['*']) {
287
- const cloned = Array.from(this.observers['*'].entries());
288
- cloned.forEach(([observer, numTimesAdded]) => {
289
- for (let i = 0; i < numTimesAdded; i++) {
290
- observer.apply(observer, [event, ...args]);
291
- }
292
- });
293
- }
294
- }
295
- }
296
-
297
- class ResourceStore extends EventEmitter {
298
- constructor(data, options = {
299
- ns: ['translation'],
300
- defaultNS: 'translation'
301
- }) {
302
- super();
303
- this.data = data || {};
304
- this.options = options;
305
- if (this.options.keySeparator === undefined) {
306
- this.options.keySeparator = '.';
307
- }
308
- if (this.options.ignoreJSONStructure === undefined) {
309
- this.options.ignoreJSONStructure = true;
310
- }
311
- }
312
- addNamespaces(ns) {
313
- if (this.options.ns.indexOf(ns) < 0) {
314
- this.options.ns.push(ns);
315
- }
316
- }
317
- removeNamespaces(ns) {
318
- const index = this.options.ns.indexOf(ns);
319
- if (index > -1) {
320
- this.options.ns.splice(index, 1);
321
- }
322
- }
323
- getResource(lng, ns, key, options = {}) {
324
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
325
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
326
- let path;
327
- if (lng.indexOf('.') > -1) {
328
- path = lng.split('.');
329
- } else {
330
- path = [lng, ns];
331
- if (key) {
332
- if (Array.isArray(key)) {
333
- path.push(...key);
334
- } else if (isString(key) && keySeparator) {
335
- path.push(...key.split(keySeparator));
336
- } else {
337
- path.push(key);
338
- }
339
- }
340
- }
341
- const result = getPath(this.data, path);
342
- if (!result && !ns && !key && lng.indexOf('.') > -1) {
343
- lng = path[0];
344
- ns = path[1];
345
- key = path.slice(2).join('.');
346
- }
347
- if (result || !ignoreJSONStructure || !isString(key)) return result;
348
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
349
- }
350
- addResource(lng, ns, key, value, options = {
351
- silent: false
352
- }) {
353
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
354
- let path = [lng, ns];
355
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
356
- if (lng.indexOf('.') > -1) {
357
- path = lng.split('.');
358
- value = ns;
359
- ns = path[1];
360
- }
361
- this.addNamespaces(ns);
362
- setPath(this.data, path, value);
363
- if (!options.silent) this.emit('added', lng, ns, key, value);
364
- }
365
- addResources(lng, ns, resources, options = {
366
- silent: false
367
- }) {
368
- for (const m in resources) {
369
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
370
- silent: true
371
- });
372
- }
373
- if (!options.silent) this.emit('added', lng, ns, resources);
374
- }
375
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
376
- silent: false,
377
- skipCopy: false
378
- }) {
379
- let path = [lng, ns];
380
- if (lng.indexOf('.') > -1) {
381
- path = lng.split('.');
382
- deep = resources;
383
- resources = ns;
384
- ns = path[1];
385
- }
386
- this.addNamespaces(ns);
387
- let pack = getPath(this.data, path) || {};
388
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
389
- if (deep) {
390
- deepExtend(pack, resources, overwrite);
391
- } else {
392
- pack = {
393
- ...pack,
394
- ...resources
395
- };
396
- }
397
- setPath(this.data, path, pack);
398
- if (!options.silent) this.emit('added', lng, ns, resources);
399
- }
400
- removeResourceBundle(lng, ns) {
401
- if (this.hasResourceBundle(lng, ns)) {
402
- delete this.data[lng][ns];
403
- }
404
- this.removeNamespaces(ns);
405
- this.emit('removed', lng, ns);
406
- }
407
- hasResourceBundle(lng, ns) {
408
- return this.getResource(lng, ns) !== undefined;
409
- }
410
- getResourceBundle(lng, ns) {
411
- if (!ns) ns = this.options.defaultNS;
412
- return this.getResource(lng, ns);
413
- }
414
- getDataByLanguage(lng) {
415
- return this.data[lng];
416
- }
417
- hasLanguageSomeTranslations(lng) {
418
- const data = this.getDataByLanguage(lng);
419
- const n = data && Object.keys(data) || [];
420
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
421
- }
422
- toJSON() {
423
- return this.data;
424
- }
425
- }
426
-
427
- var postProcessor = {
428
- processors: {},
429
- addPostProcessor(module) {
430
- this.processors[module.name] = module;
431
- },
432
- handle(processors, value, key, options, translator) {
433
- processors.forEach(processor => {
434
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
435
- });
436
- return value;
437
- }
438
- };
439
-
440
- const PATH_KEY = Symbol('i18next/PATH_KEY');
441
- function createProxy() {
442
- const state = [];
443
- const handler = Object.create(null);
444
- let proxy;
445
- handler.get = (target, key) => {
446
- proxy?.revoke?.();
447
- if (key === PATH_KEY) return state;
448
- state.push(key);
449
- proxy = Proxy.revocable(target, handler);
450
- return proxy.proxy;
451
- };
452
- return Proxy.revocable(Object.create(null), handler).proxy;
453
- }
454
- function keysFromSelector(selector, opts) {
455
- const {
456
- [PATH_KEY]: path
457
- } = selector(createProxy());
458
- return path.join(opts?.keySeparator ?? '.');
459
- }
460
-
461
- const checkedLoadedFor = {};
462
- const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
463
- class Translator extends EventEmitter {
464
- constructor(services, options = {}) {
465
- super();
466
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
467
- this.options = options;
468
- if (this.options.keySeparator === undefined) {
469
- this.options.keySeparator = '.';
470
- }
471
- this.logger = baseLogger.create('translator');
472
- }
473
- changeLanguage(lng) {
474
- if (lng) this.language = lng;
475
- }
476
- exists(key, o = {
477
- interpolation: {}
478
- }) {
479
- const opt = {
480
- ...o
481
- };
482
- if (key == null) return false;
483
- const resolved = this.resolve(key, opt);
484
- if (resolved?.res === undefined) return false;
485
- const isObject = shouldHandleAsObject(resolved.res);
486
- if (opt.returnObjects === false && isObject) {
487
- return false;
488
- }
489
- return true;
490
- }
491
- extractFromKey(key, opt) {
492
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
493
- if (nsSeparator === undefined) nsSeparator = ':';
494
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
495
- let namespaces = opt.ns || this.options.defaultNS || [];
496
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
497
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
498
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
499
- const m = key.match(this.interpolator.nestingRegexp);
500
- if (m && m.length > 0) {
501
- return {
502
- key,
503
- namespaces: isString(namespaces) ? [namespaces] : namespaces
504
- };
505
- }
506
- const parts = key.split(nsSeparator);
507
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
508
- key = parts.join(keySeparator);
509
- }
510
- return {
511
- key,
512
- namespaces: isString(namespaces) ? [namespaces] : namespaces
513
- };
514
- }
515
- translate(keys, o, lastKey) {
516
- let opt = typeof o === 'object' ? {
517
- ...o
518
- } : o;
519
- if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
520
- opt = this.options.overloadTranslationOptionHandler(arguments);
521
- }
522
- if (typeof opt === 'object') opt = {
523
- ...opt
524
- };
525
- if (!opt) opt = {};
526
- if (keys == null) return '';
527
- if (typeof keys === 'function') keys = keysFromSelector(keys, {
528
- ...this.options,
529
- ...opt
530
- });
531
- if (!Array.isArray(keys)) keys = [String(keys)];
532
- const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
533
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
534
- const {
535
- key,
536
- namespaces
537
- } = this.extractFromKey(keys[keys.length - 1], opt);
538
- const namespace = namespaces[namespaces.length - 1];
539
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
540
- if (nsSeparator === undefined) nsSeparator = ':';
541
- const lng = opt.lng || this.language;
542
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
543
- if (lng?.toLowerCase() === 'cimode') {
544
- if (appendNamespaceToCIMode) {
545
- if (returnDetails) {
546
- return {
547
- res: `${namespace}${nsSeparator}${key}`,
548
- usedKey: key,
549
- exactUsedKey: key,
550
- usedLng: lng,
551
- usedNS: namespace,
552
- usedParams: this.getUsedParamsDetails(opt)
553
- };
554
- }
555
- return `${namespace}${nsSeparator}${key}`;
556
- }
557
- if (returnDetails) {
558
- return {
559
- res: key,
560
- usedKey: key,
561
- exactUsedKey: key,
562
- usedLng: lng,
563
- usedNS: namespace,
564
- usedParams: this.getUsedParamsDetails(opt)
565
- };
566
- }
567
- return key;
568
- }
569
- const resolved = this.resolve(keys, opt);
570
- let res = resolved?.res;
571
- const resUsedKey = resolved?.usedKey || key;
572
- const resExactUsedKey = resolved?.exactUsedKey || key;
573
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
574
- const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
575
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
576
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
577
- const hasDefaultValue = Translator.hasDefaultValue(opt);
578
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
579
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
580
- ordinal: false
581
- }) : '';
582
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
583
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
584
- let resForObjHndl = res;
585
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
586
- resForObjHndl = defaultValue;
587
- }
588
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
589
- const resType = Object.prototype.toString.apply(resForObjHndl);
590
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
591
- if (!opt.returnObjects && !this.options.returnObjects) {
592
- if (!this.options.returnedObjectHandler) {
593
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
594
- }
595
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
596
- ...opt,
597
- ns: namespaces
598
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
599
- if (returnDetails) {
600
- resolved.res = r;
601
- resolved.usedParams = this.getUsedParamsDetails(opt);
602
- return resolved;
603
- }
604
- return r;
605
- }
606
- if (keySeparator) {
607
- const resTypeIsArray = Array.isArray(resForObjHndl);
608
- const copy = resTypeIsArray ? [] : {};
609
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
610
- for (const m in resForObjHndl) {
611
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
612
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
613
- if (hasDefaultValue && !res) {
614
- copy[m] = this.translate(deepKey, {
615
- ...opt,
616
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
617
- ...{
618
- joinArrays: false,
619
- ns: namespaces
620
- }
621
- });
622
- } else {
623
- copy[m] = this.translate(deepKey, {
624
- ...opt,
625
- ...{
626
- joinArrays: false,
627
- ns: namespaces
628
- }
629
- });
630
- }
631
- if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
632
- }
633
- }
634
- res = copy;
635
- }
636
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
637
- res = res.join(joinArrays);
638
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
639
- } else {
640
- let usedDefault = false;
641
- let usedKey = false;
642
- if (!this.isValidLookup(res) && hasDefaultValue) {
643
- usedDefault = true;
644
- res = defaultValue;
645
- }
646
- if (!this.isValidLookup(res)) {
647
- usedKey = true;
648
- res = key;
649
- }
650
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
651
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
652
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
653
- if (usedKey || usedDefault || updateMissing) {
654
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
655
- if (keySeparator) {
656
- const fk = this.resolve(key, {
657
- ...opt,
658
- keySeparator: false
659
- });
660
- 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.');
661
- }
662
- let lngs = [];
663
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
664
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
665
- for (let i = 0; i < fallbackLngs.length; i++) {
666
- lngs.push(fallbackLngs[i]);
667
- }
668
- } else if (this.options.saveMissingTo === 'all') {
669
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
670
- } else {
671
- lngs.push(opt.lng || this.language);
672
- }
673
- const send = (l, k, specificDefaultValue) => {
674
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
675
- if (this.options.missingKeyHandler) {
676
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
677
- } else if (this.backendConnector?.saveMissing) {
678
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
679
- }
680
- this.emit('missingKey', l, namespace, k, res);
681
- };
682
- if (this.options.saveMissing) {
683
- if (this.options.saveMissingPlurals && needsPluralHandling) {
684
- lngs.forEach(language => {
685
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
686
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
687
- suffixes.push(`${this.options.pluralSeparator}zero`);
688
- }
689
- suffixes.forEach(suffix => {
690
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
691
- });
692
- });
693
- } else {
694
- send(lngs, key, defaultValue);
695
- }
696
- }
697
- }
698
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
699
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
700
- res = `${namespace}${nsSeparator}${key}`;
701
- }
702
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
703
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
704
- }
705
- }
706
- if (returnDetails) {
707
- resolved.res = res;
708
- resolved.usedParams = this.getUsedParamsDetails(opt);
709
- return resolved;
710
- }
711
- return res;
712
- }
713
- extendTranslation(res, key, opt, resolved, lastKey) {
714
- if (this.i18nFormat?.parse) {
715
- res = this.i18nFormat.parse(res, {
716
- ...this.options.interpolation.defaultVariables,
717
- ...opt
718
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
719
- resolved
720
- });
721
- } else if (!opt.skipInterpolation) {
722
- if (opt.interpolation) this.interpolator.init({
723
- ...opt,
724
- ...{
725
- interpolation: {
726
- ...this.options.interpolation,
727
- ...opt.interpolation
728
- }
729
- }
730
- });
731
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
732
- let nestBef;
733
- if (skipOnVariables) {
734
- const nb = res.match(this.interpolator.nestingRegexp);
735
- nestBef = nb && nb.length;
736
- }
737
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
738
- if (this.options.interpolation.defaultVariables) data = {
739
- ...this.options.interpolation.defaultVariables,
740
- ...data
741
- };
742
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
743
- if (skipOnVariables) {
744
- const na = res.match(this.interpolator.nestingRegexp);
745
- const nestAft = na && na.length;
746
- if (nestBef < nestAft) opt.nest = false;
747
- }
748
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
749
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
750
- if (lastKey?.[0] === args[0] && !opt.context) {
751
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
752
- return null;
753
- }
754
- return this.translate(...args, key);
755
- }, opt);
756
- if (opt.interpolation) this.interpolator.reset();
757
- }
758
- const postProcess = opt.postProcess || this.options.postProcess;
759
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
760
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
761
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
762
- i18nResolved: {
763
- ...resolved,
764
- usedParams: this.getUsedParamsDetails(opt)
765
- },
766
- ...opt
767
- } : opt, this);
768
- }
769
- return res;
770
- }
771
- resolve(keys, opt = {}) {
772
- let found;
773
- let usedKey;
774
- let exactUsedKey;
775
- let usedLng;
776
- let usedNS;
777
- if (isString(keys)) keys = [keys];
778
- keys.forEach(k => {
779
- if (this.isValidLookup(found)) return;
780
- const extracted = this.extractFromKey(k, opt);
781
- const key = extracted.key;
782
- usedKey = key;
783
- let namespaces = extracted.namespaces;
784
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
785
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
786
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
787
- const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
788
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
789
- namespaces.forEach(ns => {
790
- if (this.isValidLookup(found)) return;
791
- usedNS = ns;
792
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
793
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
794
- 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!!!');
795
- }
796
- codes.forEach(code => {
797
- if (this.isValidLookup(found)) return;
798
- usedLng = code;
799
- const finalKeys = [key];
800
- if (this.i18nFormat?.addLookupKeys) {
801
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
802
- } else {
803
- let pluralSuffix;
804
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
805
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
806
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
807
- if (needsPluralHandling) {
808
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
809
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
810
- }
811
- finalKeys.push(key + pluralSuffix);
812
- if (needsZeroSuffixLookup) {
813
- finalKeys.push(key + zeroSuffix);
814
- }
815
- }
816
- if (needsContextHandling) {
817
- const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
818
- finalKeys.push(contextKey);
819
- if (needsPluralHandling) {
820
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
821
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
822
- }
823
- finalKeys.push(contextKey + pluralSuffix);
824
- if (needsZeroSuffixLookup) {
825
- finalKeys.push(contextKey + zeroSuffix);
826
- }
827
- }
828
- }
829
- }
830
- let possibleKey;
831
- while (possibleKey = finalKeys.pop()) {
832
- if (!this.isValidLookup(found)) {
833
- exactUsedKey = possibleKey;
834
- found = this.getResource(code, ns, possibleKey, opt);
835
- }
836
- }
837
- });
838
- });
839
- });
840
- return {
841
- res: found,
842
- usedKey,
843
- exactUsedKey,
844
- usedLng,
845
- usedNS
846
- };
847
- }
848
- isValidLookup(res) {
849
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
850
- }
851
- getResource(code, ns, key, options = {}) {
852
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
853
- return this.resourceStore.getResource(code, ns, key, options);
854
- }
855
- getUsedParamsDetails(options = {}) {
856
- const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
857
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
858
- let data = useOptionsReplaceForData ? options.replace : options;
859
- if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
860
- data.count = options.count;
861
- }
862
- if (this.options.interpolation.defaultVariables) {
863
- data = {
864
- ...this.options.interpolation.defaultVariables,
865
- ...data
866
- };
867
- }
868
- if (!useOptionsReplaceForData) {
869
- data = {
870
- ...data
871
- };
872
- for (const key of optionsKeys) {
873
- delete data[key];
874
- }
875
- }
876
- return data;
877
- }
878
- static hasDefaultValue(options) {
879
- const prefix = 'defaultValue';
880
- for (const option in options) {
881
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
882
- return true;
883
- }
884
- }
885
- return false;
886
- }
887
- }
888
-
889
- class LanguageUtil {
890
- constructor(options) {
891
- this.options = options;
892
- this.supportedLngs = this.options.supportedLngs || false;
893
- this.logger = baseLogger.create('languageUtils');
894
- }
895
- getScriptPartFromCode(code) {
896
- code = getCleanedCode(code);
897
- if (!code || code.indexOf('-') < 0) return null;
898
- const p = code.split('-');
899
- if (p.length === 2) return null;
900
- p.pop();
901
- if (p[p.length - 1].toLowerCase() === 'x') return null;
902
- return this.formatLanguageCode(p.join('-'));
903
- }
904
- getLanguagePartFromCode(code) {
905
- code = getCleanedCode(code);
906
- if (!code || code.indexOf('-') < 0) return code;
907
- const p = code.split('-');
908
- return this.formatLanguageCode(p[0]);
909
- }
910
- formatLanguageCode(code) {
911
- if (isString(code) && code.indexOf('-') > -1) {
912
- let formattedCode;
913
- try {
914
- formattedCode = Intl.getCanonicalLocales(code)[0];
915
- } catch (e) {}
916
- if (formattedCode && this.options.lowerCaseLng) {
917
- formattedCode = formattedCode.toLowerCase();
918
- }
919
- if (formattedCode) return formattedCode;
920
- if (this.options.lowerCaseLng) {
921
- return code.toLowerCase();
922
- }
923
- return code;
924
- }
925
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
926
- }
927
- isSupportedCode(code) {
928
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
929
- code = this.getLanguagePartFromCode(code);
930
- }
931
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
932
- }
933
- getBestMatchFromCodes(codes) {
934
- if (!codes) return null;
935
- let found;
936
- codes.forEach(code => {
937
- if (found) return;
938
- const cleanedLng = this.formatLanguageCode(code);
939
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
940
- });
941
- if (!found && this.options.supportedLngs) {
942
- codes.forEach(code => {
943
- if (found) return;
944
- const lngScOnly = this.getScriptPartFromCode(code);
945
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
946
- const lngOnly = this.getLanguagePartFromCode(code);
947
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
948
- found = this.options.supportedLngs.find(supportedLng => {
949
- if (supportedLng === lngOnly) return supportedLng;
950
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
951
- if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
952
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
953
- });
954
- });
955
- }
956
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
957
- return found;
958
- }
959
- getFallbackCodes(fallbacks, code) {
960
- if (!fallbacks) return [];
961
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
962
- if (isString(fallbacks)) fallbacks = [fallbacks];
963
- if (Array.isArray(fallbacks)) return fallbacks;
964
- if (!code) return fallbacks.default || [];
965
- let found = fallbacks[code];
966
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
967
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
968
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
969
- if (!found) found = fallbacks.default;
970
- return found || [];
971
- }
972
- toResolveHierarchy(code, fallbackCode) {
973
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
974
- const codes = [];
975
- const addCode = c => {
976
- if (!c) return;
977
- if (this.isSupportedCode(c)) {
978
- codes.push(c);
979
- } else {
980
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
981
- }
982
- };
983
- if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
984
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
985
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
986
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
987
- } else if (isString(code)) {
988
- addCode(this.formatLanguageCode(code));
989
- }
990
- fallbackCodes.forEach(fc => {
991
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
992
- });
993
- return codes;
994
- }
995
- }
996
-
997
- const suffixesOrder = {
998
- zero: 0,
999
- one: 1,
1000
- two: 2,
1001
- few: 3,
1002
- many: 4,
1003
- other: 5
1004
- };
1005
- const dummyRule = {
1006
- select: count => count === 1 ? 'one' : 'other',
1007
- resolvedOptions: () => ({
1008
- pluralCategories: ['one', 'other']
1009
- })
1010
- };
1011
- class PluralResolver {
1012
- constructor(languageUtils, options = {}) {
1013
- this.languageUtils = languageUtils;
1014
- this.options = options;
1015
- this.logger = baseLogger.create('pluralResolver');
1016
- this.pluralRulesCache = {};
1017
- }
1018
- addRule(lng, obj) {
1019
- this.rules[lng] = obj;
1020
- }
1021
- clearCache() {
1022
- this.pluralRulesCache = {};
1023
- }
1024
- getRule(code, options = {}) {
1025
- const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1026
- const type = options.ordinal ? 'ordinal' : 'cardinal';
1027
- const cacheKey = JSON.stringify({
1028
- cleanedCode,
1029
- type
1030
- });
1031
- if (cacheKey in this.pluralRulesCache) {
1032
- return this.pluralRulesCache[cacheKey];
1033
- }
1034
- let rule;
1035
- try {
1036
- rule = new Intl.PluralRules(cleanedCode, {
1037
- type
1038
- });
1039
- } catch (err) {
1040
- if (!Intl) {
1041
- this.logger.error('No Intl support, please use an Intl polyfill!');
1042
- return dummyRule;
1043
- }
1044
- if (!code.match(/-|_/)) return dummyRule;
1045
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1046
- rule = this.getRule(lngPart, options);
1047
- }
1048
- this.pluralRulesCache[cacheKey] = rule;
1049
- return rule;
1050
- }
1051
- needsPlural(code, options = {}) {
1052
- let rule = this.getRule(code, options);
1053
- if (!rule) rule = this.getRule('dev', options);
1054
- return rule?.resolvedOptions().pluralCategories.length > 1;
1055
- }
1056
- getPluralFormsOfKey(code, key, options = {}) {
1057
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1058
- }
1059
- getSuffixes(code, options = {}) {
1060
- let rule = this.getRule(code, options);
1061
- if (!rule) rule = this.getRule('dev', options);
1062
- if (!rule) return [];
1063
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1064
- }
1065
- getSuffix(code, count, options = {}) {
1066
- const rule = this.getRule(code, options);
1067
- if (rule) {
1068
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1069
- }
1070
- this.logger.warn(`no plural rule found for: ${code}`);
1071
- return this.getSuffix('dev', count, options);
1072
- }
1073
- }
1074
-
1075
- const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
1076
- let path = getPathWithDefaults(data, defaultData, key);
1077
- if (!path && ignoreJSONStructure && isString(key)) {
1078
- path = deepFind(data, key, keySeparator);
1079
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1080
- }
1081
- return path;
1082
- };
1083
- const regexSafe = val => val.replace(/\$/g, '$$$$');
1084
- class Interpolator {
1085
- constructor(options = {}) {
1086
- this.logger = baseLogger.create('interpolator');
1087
- this.options = options;
1088
- this.format = options?.interpolation?.format || (value => value);
1089
- this.init(options);
1090
- }
1091
- init(options = {}) {
1092
- if (!options.interpolation) options.interpolation = {
1093
- escapeValue: true
1094
- };
1095
- const {
1096
- escape: escape$1,
1097
- escapeValue,
1098
- useRawValueToEscape,
1099
- prefix,
1100
- prefixEscaped,
1101
- suffix,
1102
- suffixEscaped,
1103
- formatSeparator,
1104
- unescapeSuffix,
1105
- unescapePrefix,
1106
- nestingPrefix,
1107
- nestingPrefixEscaped,
1108
- nestingSuffix,
1109
- nestingSuffixEscaped,
1110
- nestingOptionsSeparator,
1111
- maxReplaces,
1112
- alwaysFormat
1113
- } = options.interpolation;
1114
- this.escape = escape$1 !== undefined ? escape$1 : escape;
1115
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
1116
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
1117
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
1118
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
1119
- this.formatSeparator = formatSeparator || ',';
1120
- this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
1121
- this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
1122
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
1123
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
1124
- this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
1125
- this.maxReplaces = maxReplaces || 1000;
1126
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
1127
- this.resetRegExp();
1128
- }
1129
- reset() {
1130
- if (this.options) this.init(this.options);
1131
- }
1132
- resetRegExp() {
1133
- const getOrResetRegExp = (existingRegExp, pattern) => {
1134
- if (existingRegExp?.source === pattern) {
1135
- existingRegExp.lastIndex = 0;
1136
- return existingRegExp;
1137
- }
1138
- return new RegExp(pattern, 'g');
1139
- };
1140
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1141
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1142
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1143
- }
1144
- interpolate(str, data, lng, options) {
1145
- let match;
1146
- let value;
1147
- let replaces;
1148
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1149
- const handleFormat = key => {
1150
- if (key.indexOf(this.formatSeparator) < 0) {
1151
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1152
- return this.alwaysFormat ? this.format(path, undefined, lng, {
1153
- ...options,
1154
- ...data,
1155
- interpolationkey: key
1156
- }) : path;
1157
- }
1158
- const p = key.split(this.formatSeparator);
1159
- const k = p.shift().trim();
1160
- const f = p.join(this.formatSeparator).trim();
1161
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1162
- ...options,
1163
- ...data,
1164
- interpolationkey: k
1165
- });
1166
- };
1167
- this.resetRegExp();
1168
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1169
- const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1170
- const todos = [{
1171
- regex: this.regexpUnescape,
1172
- safeValue: val => regexSafe(val)
1173
- }, {
1174
- regex: this.regexp,
1175
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1176
- }];
1177
- todos.forEach(todo => {
1178
- replaces = 0;
1179
- while (match = todo.regex.exec(str)) {
1180
- const matchedVar = match[1].trim();
1181
- value = handleFormat(matchedVar);
1182
- if (value === undefined) {
1183
- if (typeof missingInterpolationHandler === 'function') {
1184
- const temp = missingInterpolationHandler(str, match, options);
1185
- value = isString(temp) ? temp : '';
1186
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1187
- value = '';
1188
- } else if (skipOnVariables) {
1189
- value = match[0];
1190
- continue;
1191
- } else {
1192
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1193
- value = '';
1194
- }
1195
- } else if (!isString(value) && !this.useRawValueToEscape) {
1196
- value = makeString(value);
1197
- }
1198
- const safeValue = todo.safeValue(value);
1199
- str = str.replace(match[0], safeValue);
1200
- if (skipOnVariables) {
1201
- todo.regex.lastIndex += value.length;
1202
- todo.regex.lastIndex -= match[0].length;
1203
- } else {
1204
- todo.regex.lastIndex = 0;
1205
- }
1206
- replaces++;
1207
- if (replaces >= this.maxReplaces) {
1208
- break;
1209
- }
1210
- }
1211
- });
1212
- return str;
1213
- }
1214
- nest(str, fc, options = {}) {
1215
- let match;
1216
- let value;
1217
- let clonedOptions;
1218
- const handleHasOptions = (key, inheritedOptions) => {
1219
- const sep = this.nestingOptionsSeparator;
1220
- if (key.indexOf(sep) < 0) return key;
1221
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1222
- let optionsString = `{${c[1]}`;
1223
- key = c[0];
1224
- optionsString = this.interpolate(optionsString, clonedOptions);
1225
- const matchedSingleQuotes = optionsString.match(/'/g);
1226
- const matchedDoubleQuotes = optionsString.match(/"/g);
1227
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1228
- optionsString = optionsString.replace(/'/g, '"');
1229
- }
1230
- try {
1231
- clonedOptions = JSON.parse(optionsString);
1232
- if (inheritedOptions) clonedOptions = {
1233
- ...inheritedOptions,
1234
- ...clonedOptions
1235
- };
1236
- } catch (e) {
1237
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1238
- return `${key}${sep}${optionsString}`;
1239
- }
1240
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1241
- return key;
1242
- };
1243
- while (match = this.nestingRegexp.exec(str)) {
1244
- let formatters = [];
1245
- clonedOptions = {
1246
- ...options
1247
- };
1248
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1249
- clonedOptions.applyPostProcessor = false;
1250
- delete clonedOptions.defaultValue;
1251
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
1252
- if (keyEndIndex !== -1) {
1253
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
1254
- match[1] = match[1].slice(0, keyEndIndex);
1255
- }
1256
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1257
- if (value && match[0] === str && !isString(value)) return value;
1258
- if (!isString(value)) value = makeString(value);
1259
- if (!value) {
1260
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1261
- value = '';
1262
- }
1263
- if (formatters.length) {
1264
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1265
- ...options,
1266
- interpolationkey: match[1].trim()
1267
- }), value.trim());
1268
- }
1269
- str = str.replace(match[0], value);
1270
- this.regexp.lastIndex = 0;
1271
- }
1272
- return str;
1273
- }
1274
- }
1275
-
1276
- const parseFormatStr = formatStr => {
1277
- let formatName = formatStr.toLowerCase().trim();
1278
- const formatOptions = {};
1279
- if (formatStr.indexOf('(') > -1) {
1280
- const p = formatStr.split('(');
1281
- formatName = p[0].toLowerCase().trim();
1282
- const optStr = p[1].substring(0, p[1].length - 1);
1283
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1284
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1285
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1286
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1287
- } else {
1288
- const opts = optStr.split(';');
1289
- opts.forEach(opt => {
1290
- if (opt) {
1291
- const [key, ...rest] = opt.split(':');
1292
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1293
- const trimmedKey = key.trim();
1294
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1295
- if (val === 'false') formatOptions[trimmedKey] = false;
1296
- if (val === 'true') formatOptions[trimmedKey] = true;
1297
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1298
- }
1299
- });
1300
- }
1301
- }
1302
- return {
1303
- formatName,
1304
- formatOptions
1305
- };
1306
- };
1307
- const createCachedFormatter = fn => {
1308
- const cache = {};
1309
- return (v, l, o) => {
1310
- let optForCache = o;
1311
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1312
- optForCache = {
1313
- ...optForCache,
1314
- [o.interpolationkey]: undefined
1315
- };
1316
- }
1317
- const key = l + JSON.stringify(optForCache);
1318
- let frm = cache[key];
1319
- if (!frm) {
1320
- frm = fn(getCleanedCode(l), o);
1321
- cache[key] = frm;
1322
- }
1323
- return frm(v);
1324
- };
1325
- };
1326
- const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
1327
- class Formatter {
1328
- constructor(options = {}) {
1329
- this.logger = baseLogger.create('formatter');
1330
- this.options = options;
1331
- this.init(options);
1332
- }
1333
- init(services, options = {
1334
- interpolation: {}
1335
- }) {
1336
- this.formatSeparator = options.interpolation.formatSeparator || ',';
1337
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1338
- this.formats = {
1339
- number: cf((lng, opt) => {
1340
- const formatter = new Intl.NumberFormat(lng, {
1341
- ...opt
1342
- });
1343
- return val => formatter.format(val);
1344
- }),
1345
- currency: cf((lng, opt) => {
1346
- const formatter = new Intl.NumberFormat(lng, {
1347
- ...opt,
1348
- style: 'currency'
1349
- });
1350
- return val => formatter.format(val);
1351
- }),
1352
- datetime: cf((lng, opt) => {
1353
- const formatter = new Intl.DateTimeFormat(lng, {
1354
- ...opt
1355
- });
1356
- return val => formatter.format(val);
1357
- }),
1358
- relativetime: cf((lng, opt) => {
1359
- const formatter = new Intl.RelativeTimeFormat(lng, {
1360
- ...opt
1361
- });
1362
- return val => formatter.format(val, opt.range || 'day');
1363
- }),
1364
- list: cf((lng, opt) => {
1365
- const formatter = new Intl.ListFormat(lng, {
1366
- ...opt
1367
- });
1368
- return val => formatter.format(val);
1369
- })
1370
- };
1371
- }
1372
- add(name, fc) {
1373
- this.formats[name.toLowerCase().trim()] = fc;
1374
- }
1375
- addCached(name, fc) {
1376
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1377
- }
1378
- format(value, format, lng, options = {}) {
1379
- const formats = format.split(this.formatSeparator);
1380
- if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
1381
- const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
1382
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1383
- }
1384
- const result = formats.reduce((mem, f) => {
1385
- const {
1386
- formatName,
1387
- formatOptions
1388
- } = parseFormatStr(f);
1389
- if (this.formats[formatName]) {
1390
- let formatted = mem;
1391
- try {
1392
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1393
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1394
- formatted = this.formats[formatName](mem, l, {
1395
- ...formatOptions,
1396
- ...options,
1397
- ...valOptions
1398
- });
1399
- } catch (error) {
1400
- this.logger.warn(error);
1401
- }
1402
- return formatted;
1403
- } else {
1404
- this.logger.warn(`there was no format function for ${formatName}`);
1405
- }
1406
- return mem;
1407
- }, value);
1408
- return result;
1409
- }
1410
- }
1411
-
1412
- const removePending = (q, name) => {
1413
- if (q.pending[name] !== undefined) {
1414
- delete q.pending[name];
1415
- q.pendingCount--;
1416
- }
1417
- };
1418
- class Connector extends EventEmitter {
1419
- constructor(backend, store, services, options = {}) {
1420
- super();
1421
- this.backend = backend;
1422
- this.store = store;
1423
- this.services = services;
1424
- this.languageUtils = services.languageUtils;
1425
- this.options = options;
1426
- this.logger = baseLogger.create('backendConnector');
1427
- this.waitingReads = [];
1428
- this.maxParallelReads = options.maxParallelReads || 10;
1429
- this.readingCalls = 0;
1430
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1431
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1432
- this.state = {};
1433
- this.queue = [];
1434
- this.backend?.init?.(services, options.backend, options);
1435
- }
1436
- queueLoad(languages, namespaces, options, callback) {
1437
- const toLoad = {};
1438
- const pending = {};
1439
- const toLoadLanguages = {};
1440
- const toLoadNamespaces = {};
1441
- languages.forEach(lng => {
1442
- let hasAllNamespaces = true;
1443
- namespaces.forEach(ns => {
1444
- const name = `${lng}|${ns}`;
1445
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1446
- this.state[name] = 2;
1447
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1448
- if (pending[name] === undefined) pending[name] = true;
1449
- } else {
1450
- this.state[name] = 1;
1451
- hasAllNamespaces = false;
1452
- if (pending[name] === undefined) pending[name] = true;
1453
- if (toLoad[name] === undefined) toLoad[name] = true;
1454
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1455
- }
1456
- });
1457
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1458
- });
1459
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1460
- this.queue.push({
1461
- pending,
1462
- pendingCount: Object.keys(pending).length,
1463
- loaded: {},
1464
- errors: [],
1465
- callback
1466
- });
1467
- }
1468
- return {
1469
- toLoad: Object.keys(toLoad),
1470
- pending: Object.keys(pending),
1471
- toLoadLanguages: Object.keys(toLoadLanguages),
1472
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1473
- };
1474
- }
1475
- loaded(name, err, data) {
1476
- const s = name.split('|');
1477
- const lng = s[0];
1478
- const ns = s[1];
1479
- if (err) this.emit('failedLoading', lng, ns, err);
1480
- if (!err && data) {
1481
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
1482
- skipCopy: true
1483
- });
1484
- }
1485
- this.state[name] = err ? -1 : 2;
1486
- if (err && data) this.state[name] = 0;
1487
- const loaded = {};
1488
- this.queue.forEach(q => {
1489
- pushPath(q.loaded, [lng], ns);
1490
- removePending(q, name);
1491
- if (err) q.errors.push(err);
1492
- if (q.pendingCount === 0 && !q.done) {
1493
- Object.keys(q.loaded).forEach(l => {
1494
- if (!loaded[l]) loaded[l] = {};
1495
- const loadedKeys = q.loaded[l];
1496
- if (loadedKeys.length) {
1497
- loadedKeys.forEach(n => {
1498
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1499
- });
1500
- }
1501
- });
1502
- q.done = true;
1503
- if (q.errors.length) {
1504
- q.callback(q.errors);
1505
- } else {
1506
- q.callback();
1507
- }
1508
- }
1509
- });
1510
- this.emit('loaded', loaded);
1511
- this.queue = this.queue.filter(q => !q.done);
1512
- }
1513
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1514
- if (!lng.length) return callback(null, {});
1515
- if (this.readingCalls >= this.maxParallelReads) {
1516
- this.waitingReads.push({
1517
- lng,
1518
- ns,
1519
- fcName,
1520
- tried,
1521
- wait,
1522
- callback
1523
- });
1524
- return;
1525
- }
1526
- this.readingCalls++;
1527
- const resolver = (err, data) => {
1528
- this.readingCalls--;
1529
- if (this.waitingReads.length > 0) {
1530
- const next = this.waitingReads.shift();
1531
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1532
- }
1533
- if (err && data && tried < this.maxRetries) {
1534
- setTimeout(() => {
1535
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1536
- }, wait);
1537
- return;
1538
- }
1539
- callback(err, data);
1540
- };
1541
- const fc = this.backend[fcName].bind(this.backend);
1542
- if (fc.length === 2) {
1543
- try {
1544
- const r = fc(lng, ns);
1545
- if (r && typeof r.then === 'function') {
1546
- r.then(data => resolver(null, data)).catch(resolver);
1547
- } else {
1548
- resolver(null, r);
1549
- }
1550
- } catch (err) {
1551
- resolver(err);
1552
- }
1553
- return;
1554
- }
1555
- return fc(lng, ns, resolver);
1556
- }
1557
- prepareLoading(languages, namespaces, options = {}, callback) {
1558
- if (!this.backend) {
1559
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1560
- return callback && callback();
1561
- }
1562
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1563
- if (isString(namespaces)) namespaces = [namespaces];
1564
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1565
- if (!toLoad.toLoad.length) {
1566
- if (!toLoad.pending.length) callback();
1567
- return null;
1568
- }
1569
- toLoad.toLoad.forEach(name => {
1570
- this.loadOne(name);
1571
- });
1572
- }
1573
- load(languages, namespaces, callback) {
1574
- this.prepareLoading(languages, namespaces, {}, callback);
1575
- }
1576
- reload(languages, namespaces, callback) {
1577
- this.prepareLoading(languages, namespaces, {
1578
- reload: true
1579
- }, callback);
1580
- }
1581
- loadOne(name, prefix = '') {
1582
- const s = name.split('|');
1583
- const lng = s[0];
1584
- const ns = s[1];
1585
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1586
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1587
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1588
- this.loaded(name, err, data);
1589
- });
1590
- }
1591
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1592
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1593
- 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!!!');
1594
- return;
1595
- }
1596
- if (key === undefined || key === null || key === '') return;
1597
- if (this.backend?.create) {
1598
- const opts = {
1599
- ...options,
1600
- isUpdate
1601
- };
1602
- const fc = this.backend.create.bind(this.backend);
1603
- if (fc.length < 6) {
1604
- try {
1605
- let r;
1606
- if (fc.length === 5) {
1607
- r = fc(languages, namespace, key, fallbackValue, opts);
1608
- } else {
1609
- r = fc(languages, namespace, key, fallbackValue);
1610
- }
1611
- if (r && typeof r.then === 'function') {
1612
- r.then(data => clb(null, data)).catch(clb);
1613
- } else {
1614
- clb(null, r);
1615
- }
1616
- } catch (err) {
1617
- clb(err);
1618
- }
1619
- } else {
1620
- fc(languages, namespace, key, fallbackValue, clb, opts);
1621
- }
1622
- }
1623
- if (!languages || !languages[0]) return;
1624
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1625
- }
1626
- }
1627
-
1628
- const get = () => ({
1629
- debug: false,
1630
- initAsync: true,
1631
- ns: ['translation'],
1632
- defaultNS: ['translation'],
1633
- fallbackLng: ['dev'],
1634
- fallbackNS: false,
1635
- supportedLngs: false,
1636
- nonExplicitSupportedLngs: false,
1637
- load: 'all',
1638
- preload: false,
1639
- simplifyPluralSuffix: true,
1640
- keySeparator: '.',
1641
- nsSeparator: ':',
1642
- pluralSeparator: '_',
1643
- contextSeparator: '_',
1644
- partialBundledLanguages: false,
1645
- saveMissing: false,
1646
- updateMissing: false,
1647
- saveMissingTo: 'fallback',
1648
- saveMissingPlurals: true,
1649
- missingKeyHandler: false,
1650
- missingInterpolationHandler: false,
1651
- postProcess: false,
1652
- postProcessPassResolved: false,
1653
- returnNull: false,
1654
- returnEmptyString: true,
1655
- returnObjects: false,
1656
- joinArrays: false,
1657
- returnedObjectHandler: false,
1658
- parseMissingKeyHandler: false,
1659
- appendNamespaceToMissingKey: false,
1660
- appendNamespaceToCIMode: false,
1661
- overloadTranslationOptionHandler: args => {
1662
- let ret = {};
1663
- if (typeof args[1] === 'object') ret = args[1];
1664
- if (isString(args[1])) ret.defaultValue = args[1];
1665
- if (isString(args[2])) ret.tDescription = args[2];
1666
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1667
- const options = args[3] || args[2];
1668
- Object.keys(options).forEach(key => {
1669
- ret[key] = options[key];
1670
- });
1671
- }
1672
- return ret;
1673
- },
1674
- interpolation: {
1675
- escapeValue: true,
1676
- format: value => value,
1677
- prefix: '{{',
1678
- suffix: '}}',
1679
- formatSeparator: ',',
1680
- unescapePrefix: '-',
1681
- nestingPrefix: '$t(',
1682
- nestingSuffix: ')',
1683
- nestingOptionsSeparator: ',',
1684
- maxReplaces: 1000,
1685
- skipOnVariables: true
1686
- },
1687
- cacheInBuiltFormats: true
1688
- });
1689
- const transformOptions = options => {
1690
- if (isString(options.ns)) options.ns = [options.ns];
1691
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1692
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1693
- if (options.supportedLngs?.indexOf?.('cimode') < 0) {
1694
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
1695
- }
1696
- if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
1697
- return options;
1698
- };
1699
-
1700
- const noop = () => {};
1701
- const bindMemberFunctions = inst => {
1702
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1703
- mems.forEach(mem => {
1704
- if (typeof inst[mem] === 'function') {
1705
- inst[mem] = inst[mem].bind(inst);
1706
- }
1707
- });
1708
- };
1709
- class I18n extends EventEmitter {
1710
- constructor(options = {}, callback) {
1711
- super();
1712
- this.options = transformOptions(options);
1713
- this.services = {};
1714
- this.logger = baseLogger;
1715
- this.modules = {
1716
- external: []
1717
- };
1718
- bindMemberFunctions(this);
1719
- if (callback && !this.isInitialized && !options.isClone) {
1720
- if (!this.options.initAsync) {
1721
- this.init(options, callback);
1722
- return this;
1723
- }
1724
- setTimeout(() => {
1725
- this.init(options, callback);
1726
- }, 0);
1727
- }
1728
- }
1729
- init(options = {}, callback) {
1730
- this.isInitializing = true;
1731
- if (typeof options === 'function') {
1732
- callback = options;
1733
- options = {};
1734
- }
1735
- if (options.defaultNS == null && options.ns) {
1736
- if (isString(options.ns)) {
1737
- options.defaultNS = options.ns;
1738
- } else if (options.ns.indexOf('translation') < 0) {
1739
- options.defaultNS = options.ns[0];
1740
- }
1741
- }
1742
- const defOpts = get();
1743
- this.options = {
1744
- ...defOpts,
1745
- ...this.options,
1746
- ...transformOptions(options)
1747
- };
1748
- this.options.interpolation = {
1749
- ...defOpts.interpolation,
1750
- ...this.options.interpolation
1751
- };
1752
- if (options.keySeparator !== undefined) {
1753
- this.options.userDefinedKeySeparator = options.keySeparator;
1754
- }
1755
- if (options.nsSeparator !== undefined) {
1756
- this.options.userDefinedNsSeparator = options.nsSeparator;
1757
- }
1758
- const createClassOnDemand = ClassOrObject => {
1759
- if (!ClassOrObject) return null;
1760
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
1761
- return ClassOrObject;
1762
- };
1763
- if (!this.options.isClone) {
1764
- if (this.modules.logger) {
1765
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1766
- } else {
1767
- baseLogger.init(null, this.options);
1768
- }
1769
- let formatter;
1770
- if (this.modules.formatter) {
1771
- formatter = this.modules.formatter;
1772
- } else {
1773
- formatter = Formatter;
1774
- }
1775
- const lu = new LanguageUtil(this.options);
1776
- this.store = new ResourceStore(this.options.resources, this.options);
1777
- const s = this.services;
1778
- s.logger = baseLogger;
1779
- s.resourceStore = this.store;
1780
- s.languageUtils = lu;
1781
- s.pluralResolver = new PluralResolver(lu, {
1782
- prepend: this.options.pluralSeparator,
1783
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1784
- });
1785
- const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1786
- if (usingLegacyFormatFunction) {
1787
- this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1788
- }
1789
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1790
- s.formatter = createClassOnDemand(formatter);
1791
- if (s.formatter.init) s.formatter.init(s, this.options);
1792
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1793
- }
1794
- s.interpolator = new Interpolator(this.options);
1795
- s.utils = {
1796
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1797
- };
1798
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1799
- s.backendConnector.on('*', (event, ...args) => {
1800
- this.emit(event, ...args);
1801
- });
1802
- if (this.modules.languageDetector) {
1803
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1804
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1805
- }
1806
- if (this.modules.i18nFormat) {
1807
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1808
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1809
- }
1810
- this.translator = new Translator(this.services, this.options);
1811
- this.translator.on('*', (event, ...args) => {
1812
- this.emit(event, ...args);
1813
- });
1814
- this.modules.external.forEach(m => {
1815
- if (m.init) m.init(this);
1816
- });
1817
- }
1818
- this.format = this.options.interpolation.format;
1819
- if (!callback) callback = noop;
1820
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1821
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1822
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1823
- }
1824
- if (!this.services.languageDetector && !this.options.lng) {
1825
- this.logger.warn('init: no languageDetector is used and no lng is defined');
1826
- }
1827
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1828
- storeApi.forEach(fcName => {
1829
- this[fcName] = (...args) => this.store[fcName](...args);
1830
- });
1831
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1832
- storeApiChained.forEach(fcName => {
1833
- this[fcName] = (...args) => {
1834
- this.store[fcName](...args);
1835
- return this;
1836
- };
1837
- });
1838
- const deferred = defer();
1839
- const load = () => {
1840
- const finish = (err, t) => {
1841
- this.isInitializing = false;
1842
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1843
- this.isInitialized = true;
1844
- if (!this.options.isClone) this.logger.log('initialized', this.options);
1845
- this.emit('initialized', this.options);
1846
- deferred.resolve(t);
1847
- callback(err, t);
1848
- };
1849
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1850
- this.changeLanguage(this.options.lng, finish);
1851
- };
1852
- if (this.options.resources || !this.options.initAsync) {
1853
- load();
1854
- } else {
1855
- setTimeout(load, 0);
1856
- }
1857
- return deferred;
1858
- }
1859
- loadResources(language, callback = noop) {
1860
- let usedCallback = callback;
1861
- const usedLng = isString(language) ? language : this.language;
1862
- if (typeof language === 'function') usedCallback = language;
1863
- if (!this.options.resources || this.options.partialBundledLanguages) {
1864
- if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1865
- const toLoad = [];
1866
- const append = lng => {
1867
- if (!lng) return;
1868
- if (lng === 'cimode') return;
1869
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1870
- lngs.forEach(l => {
1871
- if (l === 'cimode') return;
1872
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1873
- });
1874
- };
1875
- if (!usedLng) {
1876
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1877
- fallbacks.forEach(l => append(l));
1878
- } else {
1879
- append(usedLng);
1880
- }
1881
- this.options.preload?.forEach?.(l => append(l));
1882
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
1883
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1884
- usedCallback(e);
1885
- });
1886
- } else {
1887
- usedCallback(null);
1888
- }
1889
- }
1890
- reloadResources(lngs, ns, callback) {
1891
- const deferred = defer();
1892
- if (typeof lngs === 'function') {
1893
- callback = lngs;
1894
- lngs = undefined;
1895
- }
1896
- if (typeof ns === 'function') {
1897
- callback = ns;
1898
- ns = undefined;
1899
- }
1900
- if (!lngs) lngs = this.languages;
1901
- if (!ns) ns = this.options.ns;
1902
- if (!callback) callback = noop;
1903
- this.services.backendConnector.reload(lngs, ns, err => {
1904
- deferred.resolve();
1905
- callback(err);
1906
- });
1907
- return deferred;
1908
- }
1909
- use(module) {
1910
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
1911
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
1912
- if (module.type === 'backend') {
1913
- this.modules.backend = module;
1914
- }
1915
- if (module.type === 'logger' || module.log && module.warn && module.error) {
1916
- this.modules.logger = module;
1917
- }
1918
- if (module.type === 'languageDetector') {
1919
- this.modules.languageDetector = module;
1920
- }
1921
- if (module.type === 'i18nFormat') {
1922
- this.modules.i18nFormat = module;
1923
- }
1924
- if (module.type === 'postProcessor') {
1925
- postProcessor.addPostProcessor(module);
1926
- }
1927
- if (module.type === 'formatter') {
1928
- this.modules.formatter = module;
1929
- }
1930
- if (module.type === '3rdParty') {
1931
- this.modules.external.push(module);
1932
- }
1933
- return this;
1934
- }
1935
- setResolvedLanguage(l) {
1936
- if (!l || !this.languages) return;
1937
- if (['cimode', 'dev'].indexOf(l) > -1) return;
1938
- for (let li = 0; li < this.languages.length; li++) {
1939
- const lngInLngs = this.languages[li];
1940
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
1941
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1942
- this.resolvedLanguage = lngInLngs;
1943
- break;
1944
- }
1945
- }
1946
- if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
1947
- this.resolvedLanguage = l;
1948
- this.languages.unshift(l);
1949
- }
1950
- }
1951
- changeLanguage(lng, callback) {
1952
- this.isLanguageChangingTo = lng;
1953
- const deferred = defer();
1954
- this.emit('languageChanging', lng);
1955
- const setLngProps = l => {
1956
- this.language = l;
1957
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
1958
- this.resolvedLanguage = undefined;
1959
- this.setResolvedLanguage(l);
1960
- };
1961
- const done = (err, l) => {
1962
- if (l) {
1963
- if (this.isLanguageChangingTo === lng) {
1964
- setLngProps(l);
1965
- this.translator.changeLanguage(l);
1966
- this.isLanguageChangingTo = undefined;
1967
- this.emit('languageChanged', l);
1968
- this.logger.log('languageChanged', l);
1969
- }
1970
- } else {
1971
- this.isLanguageChangingTo = undefined;
1972
- }
1973
- deferred.resolve((...args) => this.t(...args));
1974
- if (callback) callback(err, (...args) => this.t(...args));
1975
- };
1976
- const setLng = lngs => {
1977
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
1978
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
1979
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
1980
- if (l) {
1981
- if (!this.language) {
1982
- setLngProps(l);
1983
- }
1984
- if (!this.translator.language) this.translator.changeLanguage(l);
1985
- this.services.languageDetector?.cacheUserLanguage?.(l);
1986
- }
1987
- this.loadResources(l, err => {
1988
- done(err, l);
1989
- });
1990
- };
1991
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
1992
- setLng(this.services.languageDetector.detect());
1993
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
1994
- if (this.services.languageDetector.detect.length === 0) {
1995
- this.services.languageDetector.detect().then(setLng);
1996
- } else {
1997
- this.services.languageDetector.detect(setLng);
1998
- }
1999
- } else {
2000
- setLng(lng);
2001
- }
2002
- return deferred;
2003
- }
2004
- getFixedT(lng, ns, keyPrefix) {
2005
- const fixedT = (key, opts, ...rest) => {
2006
- let o;
2007
- if (typeof opts !== 'object') {
2008
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2009
- } else {
2010
- o = {
2011
- ...opts
2012
- };
2013
- }
2014
- o.lng = o.lng || fixedT.lng;
2015
- o.lngs = o.lngs || fixedT.lngs;
2016
- o.ns = o.ns || fixedT.ns;
2017
- if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2018
- const keySeparator = this.options.keySeparator || '.';
2019
- let resultKey;
2020
- if (o.keyPrefix && Array.isArray(key)) {
2021
- resultKey = key.map(k => {
2022
- if (typeof k === 'function') k = keysFromSelector(k, {
2023
- ...this.options,
2024
- ...opts
2025
- });
2026
- return `${o.keyPrefix}${keySeparator}${k}`;
2027
- });
2028
- } else {
2029
- if (typeof key === 'function') key = keysFromSelector(key, {
2030
- ...this.options,
2031
- ...opts
2032
- });
2033
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2034
- }
2035
- return this.t(resultKey, o);
2036
- };
2037
- if (isString(lng)) {
2038
- fixedT.lng = lng;
2039
- } else {
2040
- fixedT.lngs = lng;
2041
- }
2042
- fixedT.ns = ns;
2043
- fixedT.keyPrefix = keyPrefix;
2044
- return fixedT;
2045
- }
2046
- t(...args) {
2047
- return this.translator?.translate(...args);
2048
- }
2049
- exists(...args) {
2050
- return this.translator?.exists(...args);
2051
- }
2052
- setDefaultNamespace(ns) {
2053
- this.options.defaultNS = ns;
2054
- }
2055
- hasLoadedNamespace(ns, options = {}) {
2056
- if (!this.isInitialized) {
2057
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2058
- return false;
2059
- }
2060
- if (!this.languages || !this.languages.length) {
2061
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2062
- return false;
2063
- }
2064
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2065
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2066
- const lastLng = this.languages[this.languages.length - 1];
2067
- if (lng.toLowerCase() === 'cimode') return true;
2068
- const loadNotPending = (l, n) => {
2069
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2070
- return loadState === -1 || loadState === 0 || loadState === 2;
2071
- };
2072
- if (options.precheck) {
2073
- const preResult = options.precheck(this, loadNotPending);
2074
- if (preResult !== undefined) return preResult;
2075
- }
2076
- if (this.hasResourceBundle(lng, ns)) return true;
2077
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2078
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2079
- return false;
2080
- }
2081
- loadNamespaces(ns, callback) {
2082
- const deferred = defer();
2083
- if (!this.options.ns) {
2084
- if (callback) callback();
2085
- return Promise.resolve();
2086
- }
2087
- if (isString(ns)) ns = [ns];
2088
- ns.forEach(n => {
2089
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2090
- });
2091
- this.loadResources(err => {
2092
- deferred.resolve();
2093
- if (callback) callback(err);
2094
- });
2095
- return deferred;
2096
- }
2097
- loadLanguages(lngs, callback) {
2098
- const deferred = defer();
2099
- if (isString(lngs)) lngs = [lngs];
2100
- const preloaded = this.options.preload || [];
2101
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2102
- if (!newLngs.length) {
2103
- if (callback) callback();
2104
- return Promise.resolve();
2105
- }
2106
- this.options.preload = preloaded.concat(newLngs);
2107
- this.loadResources(err => {
2108
- deferred.resolve();
2109
- if (callback) callback(err);
2110
- });
2111
- return deferred;
2112
- }
2113
- dir(lng) {
2114
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2115
- if (!lng) return 'rtl';
2116
- try {
2117
- const l = new Intl.Locale(lng);
2118
- if (l && l.getTextInfo) {
2119
- const ti = l.getTextInfo();
2120
- if (ti && ti.direction) return ti.direction;
2121
- }
2122
- } catch (e) {}
2123
- 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'];
2124
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2125
- if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
2126
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2127
- }
2128
- static createInstance(options = {}, callback) {
2129
- const instance = new I18n(options, callback);
2130
- instance.createInstance = I18n.createInstance;
2131
- return instance;
2132
- }
2133
- cloneInstance(options = {}, callback = noop) {
2134
- const forkResourceStore = options.forkResourceStore;
2135
- if (forkResourceStore) delete options.forkResourceStore;
2136
- const mergedOptions = {
2137
- ...this.options,
2138
- ...options,
2139
- ...{
2140
- isClone: true
2141
- }
2142
- };
2143
- const clone = new I18n(mergedOptions);
2144
- if (options.debug !== undefined || options.prefix !== undefined) {
2145
- clone.logger = clone.logger.clone(options);
2146
- }
2147
- const membersToCopy = ['store', 'services', 'language'];
2148
- membersToCopy.forEach(m => {
2149
- clone[m] = this[m];
2150
- });
2151
- clone.services = {
2152
- ...this.services
2153
- };
2154
- clone.services.utils = {
2155
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2156
- };
2157
- if (forkResourceStore) {
2158
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2159
- prev[l] = {
2160
- ...this.store.data[l]
2161
- };
2162
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2163
- acc[n] = {
2164
- ...prev[l][n]
2165
- };
2166
- return acc;
2167
- }, prev[l]);
2168
- return prev;
2169
- }, {});
2170
- clone.store = new ResourceStore(clonedData, mergedOptions);
2171
- clone.services.resourceStore = clone.store;
2172
- }
2173
- clone.translator = new Translator(clone.services, mergedOptions);
2174
- clone.translator.on('*', (event, ...args) => {
2175
- clone.emit(event, ...args);
2176
- });
2177
- clone.init(mergedOptions, callback);
2178
- clone.translator.options = mergedOptions;
2179
- clone.translator.backendConnector.services.utils = {
2180
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2181
- };
2182
- return clone;
2183
- }
2184
- toJSON() {
2185
- return {
2186
- options: this.options,
2187
- store: this.store,
2188
- language: this.language,
2189
- languages: this.languages,
2190
- resolvedLanguage: this.resolvedLanguage
2191
- };
2192
- }
2193
- }
2194
- const instance = I18n.createInstance();
2195
-
2196
- instance.createInstance;
2197
- instance.dir;
2198
- instance.init;
2199
- instance.loadResources;
2200
- instance.reloadResources;
2201
- instance.use;
2202
- instance.changeLanguage;
2203
- instance.getFixedT;
2204
- instance.t;
2205
- instance.exists;
2206
- instance.setDefaultNamespace;
2207
- instance.hasLoadedNamespace;
2208
- instance.loadNamespaces;
2209
- instance.loadLanguages;
2210
-
2211
- function _typeof$2(o) { "@babel/helpers - typeof"; return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof$2(o); }
2212
- function hasXMLHttpRequest() {
2213
- return typeof XMLHttpRequest === 'function' || (typeof XMLHttpRequest === "undefined" ? "undefined" : _typeof$2(XMLHttpRequest)) === 'object';
2214
- }
2215
- function isPromise(maybePromise) {
2216
- return !!maybePromise && typeof maybePromise.then === 'function';
2217
- }
2218
- function makePromise(maybePromise) {
2219
- if (isPromise(maybePromise)) {
2220
- return maybePromise;
2221
- }
2222
- return Promise.resolve(maybePromise);
2223
- }
2224
-
2225
- function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2226
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2227
- function _defineProperty$1(e, r, t) { return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
2228
- function _toPropertyKey$1(t) { var i = _toPrimitive$1(t, "string"); return "symbol" == _typeof$1(i) ? i : i + ""; }
2229
- function _toPrimitive$1(t, r) { if ("object" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof$1(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
2230
- function _typeof$1(o) { "@babel/helpers - typeof"; return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof$1(o); }
2231
- var fetchApi = typeof fetch === 'function' ? fetch : undefined;
2232
- if (typeof global !== 'undefined' && global.fetch) {
2233
- fetchApi = global.fetch;
2234
- } else if (typeof window !== 'undefined' && window.fetch) {
2235
- fetchApi = window.fetch;
2236
- }
2237
- var XmlHttpRequestApi;
2238
- if (hasXMLHttpRequest()) {
2239
- if (typeof global !== 'undefined' && global.XMLHttpRequest) {
2240
- XmlHttpRequestApi = global.XMLHttpRequest;
2241
- } else if (typeof window !== 'undefined' && window.XMLHttpRequest) {
2242
- XmlHttpRequestApi = window.XMLHttpRequest;
2243
- }
2244
- }
2245
- var ActiveXObjectApi;
2246
- if (typeof ActiveXObject === 'function') {
2247
- if (typeof global !== 'undefined' && global.ActiveXObject) {
2248
- ActiveXObjectApi = global.ActiveXObject;
2249
- } else if (typeof window !== 'undefined' && window.ActiveXObject) {
2250
- ActiveXObjectApi = window.ActiveXObject;
2251
- }
2252
- }
2253
- if (typeof fetchApi !== 'function') fetchApi = undefined;
2254
- if (!fetchApi && !XmlHttpRequestApi && !ActiveXObjectApi) {
2255
- try {
2256
- import('./node-ponyfill-CCC52WRr.js').then(function (n) { return n.n; }).then(function (mod) {
2257
- fetchApi = mod.default;
2258
- }).catch(function () {});
2259
- } catch (e) {}
2260
- }
2261
- var addQueryString = function addQueryString(url, params) {
2262
- if (params && _typeof$1(params) === 'object') {
2263
- var queryString = '';
2264
- for (var paramName in params) {
2265
- queryString += '&' + encodeURIComponent(paramName) + '=' + encodeURIComponent(params[paramName]);
2266
- }
2267
- if (!queryString) return url;
2268
- url = url + (url.indexOf('?') !== -1 ? '&' : '?') + queryString.slice(1);
2269
- }
2270
- return url;
2271
- };
2272
- var fetchIt = function fetchIt(url, fetchOptions, callback, altFetch) {
2273
- var resolver = function resolver(response) {
2274
- if (!response.ok) return callback(response.statusText || 'Error', {
2275
- status: response.status
2276
- });
2277
- response.text().then(function (data) {
2278
- callback(null, {
2279
- status: response.status,
2280
- data: data
2281
- });
2282
- }).catch(callback);
2283
- };
2284
- if (altFetch) {
2285
- var altResponse = altFetch(url, fetchOptions);
2286
- if (altResponse instanceof Promise) {
2287
- altResponse.then(resolver).catch(callback);
2288
- return;
2289
- }
2290
- }
2291
- if (typeof fetch === 'function') {
2292
- fetch(url, fetchOptions).then(resolver).catch(callback);
2293
- } else {
2294
- fetchApi(url, fetchOptions).then(resolver).catch(callback);
2295
- }
2296
- };
2297
- var omitFetchOptions = false;
2298
- var requestWithFetch = function requestWithFetch(options, url, payload, callback) {
2299
- if (options.queryStringParams) {
2300
- url = addQueryString(url, options.queryStringParams);
2301
- }
2302
- var headers = _objectSpread$1({}, typeof options.customHeaders === 'function' ? options.customHeaders() : options.customHeaders);
2303
- if (typeof window === 'undefined' && typeof global !== 'undefined' && typeof global.process !== 'undefined' && global.process.versions && global.process.versions.node) {
2304
- headers['User-Agent'] = "i18next-http-backend (node/".concat(global.process.version, "; ").concat(global.process.platform, " ").concat(global.process.arch, ")");
2305
- }
2306
- if (payload) headers['Content-Type'] = 'application/json';
2307
- var reqOptions = typeof options.requestOptions === 'function' ? options.requestOptions(payload) : options.requestOptions;
2308
- var fetchOptions = _objectSpread$1({
2309
- method: payload ? 'POST' : 'GET',
2310
- body: payload ? options.stringify(payload) : undefined,
2311
- headers: headers
2312
- }, omitFetchOptions ? {} : reqOptions);
2313
- var altFetch = typeof options.alternateFetch === 'function' && options.alternateFetch.length >= 1 ? options.alternateFetch : undefined;
2314
- try {
2315
- fetchIt(url, fetchOptions, callback, altFetch);
2316
- } catch (e) {
2317
- if (!reqOptions || Object.keys(reqOptions).length === 0 || !e.message || e.message.indexOf('not implemented') < 0) {
2318
- return callback(e);
2319
- }
2320
- try {
2321
- Object.keys(reqOptions).forEach(function (opt) {
2322
- delete fetchOptions[opt];
2323
- });
2324
- fetchIt(url, fetchOptions, callback, altFetch);
2325
- omitFetchOptions = true;
2326
- } catch (err) {
2327
- callback(err);
2328
- }
2329
- }
2330
- };
2331
- var requestWithXmlHttpRequest = function requestWithXmlHttpRequest(options, url, payload, callback) {
2332
- if (payload && _typeof$1(payload) === 'object') {
2333
- payload = addQueryString('', payload).slice(1);
2334
- }
2335
- if (options.queryStringParams) {
2336
- url = addQueryString(url, options.queryStringParams);
2337
- }
2338
- try {
2339
- var x = XmlHttpRequestApi ? new XmlHttpRequestApi() : new ActiveXObjectApi('MSXML2.XMLHTTP.3.0');
2340
- x.open(payload ? 'POST' : 'GET', url, 1);
2341
- if (!options.crossDomain) {
2342
- x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
2343
- }
2344
- x.withCredentials = !!options.withCredentials;
2345
- if (payload) {
2346
- x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
2347
- }
2348
- if (x.overrideMimeType) {
2349
- x.overrideMimeType('application/json');
2350
- }
2351
- var h = options.customHeaders;
2352
- h = typeof h === 'function' ? h() : h;
2353
- if (h) {
2354
- for (var i in h) {
2355
- x.setRequestHeader(i, h[i]);
2356
- }
2357
- }
2358
- x.onreadystatechange = function () {
2359
- x.readyState > 3 && callback(x.status >= 400 ? x.statusText : null, {
2360
- status: x.status,
2361
- data: x.responseText
2362
- });
2363
- };
2364
- x.send(payload);
2365
- } catch (e) {
2366
- console && console.log(e);
2367
- }
2368
- };
2369
- var request = function request(options, url, payload, callback) {
2370
- if (typeof payload === 'function') {
2371
- callback = payload;
2372
- payload = undefined;
2373
- }
2374
- callback = callback || function () {};
2375
- if (fetchApi && url.indexOf('file:') !== 0) {
2376
- return requestWithFetch(options, url, payload, callback);
2377
- }
2378
- if (hasXMLHttpRequest() || typeof ActiveXObject === 'function') {
2379
- return requestWithXmlHttpRequest(options, url, payload, callback);
2380
- }
2381
- callback(new Error('No fetch and no xhr implementation found!'));
2382
- };
2383
-
2384
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2385
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2386
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2387
- function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
2388
- function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
2389
- function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; }
2390
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; }
2391
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
2392
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); }
2393
- var getDefaults = function getDefaults() {
2394
- return {
2395
- loadPath: '/locales/{{lng}}/{{ns}}.json',
2396
- addPath: '/locales/add/{{lng}}/{{ns}}',
2397
- parse: function parse(data) {
2398
- return JSON.parse(data);
2399
- },
2400
- stringify: JSON.stringify,
2401
- parsePayload: function parsePayload(namespace, key, fallbackValue) {
2402
- return _defineProperty({}, key, fallbackValue || '');
2403
- },
2404
- parseLoadPayload: function parseLoadPayload(languages, namespaces) {
2405
- return undefined;
2406
- },
2407
- request: request,
2408
- reloadInterval: typeof window !== 'undefined' ? false : 60 * 60 * 1000,
2409
- customHeaders: {},
2410
- queryStringParams: {},
2411
- crossDomain: false,
2412
- withCredentials: false,
2413
- overrideMimeType: false,
2414
- requestOptions: {
2415
- mode: 'cors',
2416
- credentials: 'same-origin',
2417
- cache: 'default'
2418
- }
2419
- };
2420
- };
2421
- var Backend = function () {
2422
- function Backend(services) {
2423
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2424
- var allOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2425
- _classCallCheck(this, Backend);
2426
- this.services = services;
2427
- this.options = options;
2428
- this.allOptions = allOptions;
2429
- this.type = 'backend';
2430
- this.init(services, options, allOptions);
2431
- }
2432
- return _createClass(Backend, [{
2433
- key: "init",
2434
- value: function init(services) {
2435
- var _this = this;
2436
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2437
- var allOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2438
- this.services = services;
2439
- this.options = _objectSpread(_objectSpread(_objectSpread({}, getDefaults()), this.options || {}), options);
2440
- this.allOptions = allOptions;
2441
- if (this.services && this.options.reloadInterval) {
2442
- var timer = setInterval(function () {
2443
- return _this.reload();
2444
- }, this.options.reloadInterval);
2445
- if (_typeof(timer) === 'object' && typeof timer.unref === 'function') timer.unref();
2446
- }
2447
- }
2448
- }, {
2449
- key: "readMulti",
2450
- value: function readMulti(languages, namespaces, callback) {
2451
- this._readAny(languages, languages, namespaces, namespaces, callback);
2452
- }
2453
- }, {
2454
- key: "read",
2455
- value: function read(language, namespace, callback) {
2456
- this._readAny([language], language, [namespace], namespace, callback);
2457
- }
2458
- }, {
2459
- key: "_readAny",
2460
- value: function _readAny(languages, loadUrlLanguages, namespaces, loadUrlNamespaces, callback) {
2461
- var _this2 = this;
2462
- var loadPath = this.options.loadPath;
2463
- if (typeof this.options.loadPath === 'function') {
2464
- loadPath = this.options.loadPath(languages, namespaces);
2465
- }
2466
- loadPath = makePromise(loadPath);
2467
- loadPath.then(function (resolvedLoadPath) {
2468
- if (!resolvedLoadPath) return callback(null, {});
2469
- var url = _this2.services.interpolator.interpolate(resolvedLoadPath, {
2470
- lng: languages.join('+'),
2471
- ns: namespaces.join('+')
2472
- });
2473
- _this2.loadUrl(url, callback, loadUrlLanguages, loadUrlNamespaces);
2474
- });
2475
- }
2476
- }, {
2477
- key: "loadUrl",
2478
- value: function loadUrl(url, callback, languages, namespaces) {
2479
- var _this3 = this;
2480
- var lng = typeof languages === 'string' ? [languages] : languages;
2481
- var ns = typeof namespaces === 'string' ? [namespaces] : namespaces;
2482
- var payload = this.options.parseLoadPayload(lng, ns);
2483
- this.options.request(this.options, url, payload, function (err, res) {
2484
- if (res && (res.status >= 500 && res.status < 600 || !res.status)) return callback('failed loading ' + url + '; status code: ' + res.status, true);
2485
- if (res && res.status >= 400 && res.status < 500) return callback('failed loading ' + url + '; status code: ' + res.status, false);
2486
- if (!res && err && err.message) {
2487
- var errorMessage = err.message.toLowerCase();
2488
- var isNetworkError = ['failed', 'fetch', 'network', 'load'].find(function (term) {
2489
- return errorMessage.indexOf(term) > -1;
2490
- });
2491
- if (isNetworkError) {
2492
- return callback('failed loading ' + url + ': ' + err.message, true);
2493
- }
2494
- }
2495
- if (err) return callback(err, false);
2496
- var ret, parseErr;
2497
- try {
2498
- if (typeof res.data === 'string') {
2499
- ret = _this3.options.parse(res.data, languages, namespaces);
2500
- } else {
2501
- ret = res.data;
2502
- }
2503
- } catch (e) {
2504
- parseErr = 'failed parsing ' + url + ' to json';
2505
- }
2506
- if (parseErr) return callback(parseErr, false);
2507
- callback(null, ret);
2508
- });
2509
- }
2510
- }, {
2511
- key: "create",
2512
- value: function create(languages, namespace, key, fallbackValue, callback) {
2513
- var _this4 = this;
2514
- if (!this.options.addPath) return;
2515
- if (typeof languages === 'string') languages = [languages];
2516
- var payload = this.options.parsePayload(namespace, key, fallbackValue);
2517
- var finished = 0;
2518
- var dataArray = [];
2519
- var resArray = [];
2520
- languages.forEach(function (lng) {
2521
- var addPath = _this4.options.addPath;
2522
- if (typeof _this4.options.addPath === 'function') {
2523
- addPath = _this4.options.addPath(lng, namespace);
2524
- }
2525
- var url = _this4.services.interpolator.interpolate(addPath, {
2526
- lng: lng,
2527
- ns: namespace
2528
- });
2529
- _this4.options.request(_this4.options, url, payload, function (data, res) {
2530
- finished += 1;
2531
- dataArray.push(data);
2532
- resArray.push(res);
2533
- if (finished === languages.length) {
2534
- if (typeof callback === 'function') callback(dataArray, resArray);
2535
- }
2536
- });
2537
- });
2538
- }
2539
- }, {
2540
- key: "reload",
2541
- value: function reload() {
2542
- var _this5 = this;
2543
- var _this$services = this.services,
2544
- backendConnector = _this$services.backendConnector,
2545
- languageUtils = _this$services.languageUtils,
2546
- logger = _this$services.logger;
2547
- var currentLanguage = backendConnector.language;
2548
- if (currentLanguage && currentLanguage.toLowerCase() === 'cimode') return;
2549
- var toLoad = [];
2550
- var append = function append(lng) {
2551
- var lngs = languageUtils.toResolveHierarchy(lng);
2552
- lngs.forEach(function (l) {
2553
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
2554
- });
2555
- };
2556
- append(currentLanguage);
2557
- if (this.allOptions.preload) this.allOptions.preload.forEach(function (l) {
2558
- return append(l);
2559
- });
2560
- toLoad.forEach(function (lng) {
2561
- _this5.allOptions.ns.forEach(function (ns) {
2562
- backendConnector.read(lng, ns, 'read', null, null, function (err, data) {
2563
- if (err) logger.warn("loading namespace ".concat(ns, " for language ").concat(lng, " failed"), err);
2564
- if (!err && data) logger.log("loaded namespace ".concat(ns, " for language ").concat(lng), data);
2565
- backendConnector.loaded("".concat(lng, "|").concat(ns), err, data);
2566
- });
2567
- });
2568
- });
2569
- }
2570
- }]);
2571
- }();
2572
- Backend.type = 'backend';
2573
-
2574
- const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
2575
- const htmlEntities = {
2576
- '&amp;': '&',
2577
- '&#38;': '&',
2578
- '&lt;': '<',
2579
- '&#60;': '<',
2580
- '&gt;': '>',
2581
- '&#62;': '>',
2582
- '&apos;': "'",
2583
- '&#39;': "'",
2584
- '&quot;': '"',
2585
- '&#34;': '"',
2586
- '&nbsp;': ' ',
2587
- '&#160;': ' ',
2588
- '&copy;': '©',
2589
- '&#169;': '©',
2590
- '&reg;': '®',
2591
- '&#174;': '®',
2592
- '&hellip;': '…',
2593
- '&#8230;': '…',
2594
- '&#x2F;': '/',
2595
- '&#47;': '/'
2596
- };
2597
- const unescapeHtmlEntity = m => htmlEntities[m];
2598
- const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
2599
-
2600
- let defaultOptions = {
2601
- bindI18n: 'languageChanged',
2602
- bindI18nStore: '',
2603
- transEmptyNodeValue: '',
2604
- transSupportBasicHtmlNodes: true,
2605
- transWrapTextNodes: '',
2606
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
2607
- useSuspense: true,
2608
- unescape
2609
- };
2610
- const setDefaults = (options = {}) => {
2611
- defaultOptions = {
2612
- ...defaultOptions,
2613
- ...options
2614
- };
2615
- };
2616
-
2617
- const initReactI18next = {
2618
- type: '3rdParty',
2619
- init(instance) {
2620
- setDefaults(instance.options.react);
2621
- }
2622
- };
2623
-
2624
- instance
2625
- // load translation using http -> see /public/locales
2626
- // learn more: https://github.com/i18next/i18next-http-backend
2627
- .use(Backend)
2628
- // detect user language
2629
- // learn more: https://github.com/i18next/i18next-browser-languageDetector
2630
- // .use(LanguageDetector)
2631
- // pass the i18n instance to react-i18next.
2632
- .use(initReactI18next)
2633
- // init i18next
2634
- // for all options read: https://www.i18next.com/overview/configuration-options
2635
- .init({
2636
- lng: getTranslationLocale(),
2637
- debug: false,
2638
- ns: [],
2639
- defaultNS: 'common',
2640
- backend: {
2641
- loadPath: '/vr/locale/{{lng}}/{{ns}}.json'
2642
- },
2643
- cache: {
2644
- enabled: true
2645
- },
2646
- react: {
2647
- useSuspense: true
2648
- },
2649
- load: 'languageOnly',
2650
- fallbackLng: false
2651
- });
2652
- var loadTranslations = /*#__PURE__*/function () {
2653
- var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(language) {
2654
- return _regeneratorRuntime.wrap(function (_context) {
2655
- while (1) switch (_context.prev = _context.next) {
2656
- case 0:
2657
- return _context.abrupt("return", new Promise(function (resolve) {
2658
- instance.changeLanguage(language, function () {
2659
- return resolve(true);
2660
- });
2661
- }));
2662
- case 1:
2663
- case "end":
2664
- return _context.stop();
2665
- }
2666
- }, _callee);
2667
- }));
2668
- return function loadTranslations(_x) {
2669
- return _ref.apply(this, arguments);
2670
- };
2671
- }();
2672
- function translate(key, options) {
2673
- return instance.t(key, options).toString();
2674
- }
2675
-
2676
- export { instance as default, loadTranslations, translate };