@teammy/server 0.2.23 → 0.2.24

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