i18next.bundled.js 78 KB

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