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