react-i18next.js 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactI18next = {}, global.React));
  5. })(this, (function (exports, React) { 'use strict';
  6. const isString$1 = obj => typeof obj === 'string';
  7. const defer = () => {
  8. let res;
  9. let rej;
  10. const promise = new Promise((resolve, reject) => {
  11. res = resolve;
  12. rej = reject;
  13. });
  14. promise.resolve = res;
  15. promise.reject = rej;
  16. return promise;
  17. };
  18. const makeString = object => {
  19. if (object == null) return '';
  20. return '' + object;
  21. };
  22. const copy = (a, s, t) => {
  23. a.forEach(m => {
  24. if (s[m]) t[m] = s[m];
  25. });
  26. };
  27. const lastOfPathSeparatorRegExp = /###/g;
  28. const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
  29. const canNotTraverseDeeper = object => !object || isString$1(object);
  30. const getLastOfPath = (object, path, Empty) => {
  31. const stack = !isString$1(path) ? path : path.split('.');
  32. let stackIndex = 0;
  33. while (stackIndex < stack.length - 1) {
  34. if (canNotTraverseDeeper(object)) return {};
  35. const key = cleanKey(stack[stackIndex]);
  36. if (!object[key] && Empty) object[key] = new Empty();
  37. if (Object.prototype.hasOwnProperty.call(object, key)) {
  38. object = object[key];
  39. } else {
  40. object = {};
  41. }
  42. ++stackIndex;
  43. }
  44. if (canNotTraverseDeeper(object)) return {};
  45. return {
  46. obj: object,
  47. k: cleanKey(stack[stackIndex])
  48. };
  49. };
  50. const setPath = (object, path, newValue) => {
  51. const {
  52. obj,
  53. k
  54. } = getLastOfPath(object, path, Object);
  55. if (obj !== undefined || path.length === 1) {
  56. obj[k] = newValue;
  57. return;
  58. }
  59. let e = path[path.length - 1];
  60. let p = path.slice(0, path.length - 1);
  61. let last = getLastOfPath(object, p, Object);
  62. while (last.obj === undefined && p.length) {
  63. e = `${p[p.length - 1]}.${e}`;
  64. p = p.slice(0, p.length - 1);
  65. last = getLastOfPath(object, p, Object);
  66. if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
  67. last.obj = undefined;
  68. }
  69. }
  70. last.obj[`${last.k}.${e}`] = newValue;
  71. };
  72. const pushPath = (object, path, newValue, concat) => {
  73. const {
  74. obj,
  75. k
  76. } = getLastOfPath(object, path, Object);
  77. obj[k] = obj[k] || [];
  78. obj[k].push(newValue);
  79. };
  80. const getPath = (object, path) => {
  81. const {
  82. obj,
  83. k
  84. } = getLastOfPath(object, path);
  85. if (!obj) return undefined;
  86. if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
  87. return obj[k];
  88. };
  89. const getPathWithDefaults = (data, defaultData, key) => {
  90. const value = getPath(data, key);
  91. if (value !== undefined) {
  92. return value;
  93. }
  94. return getPath(defaultData, key);
  95. };
  96. const deepExtend = (target, source, overwrite) => {
  97. for (const prop in source) {
  98. if (prop !== '__proto__' && prop !== 'constructor') {
  99. if (prop in target) {
  100. if (isString$1(target[prop]) || target[prop] instanceof String || isString$1(source[prop]) || source[prop] instanceof String) {
  101. if (overwrite) target[prop] = source[prop];
  102. } else {
  103. deepExtend(target[prop], source[prop], overwrite);
  104. }
  105. } else {
  106. target[prop] = source[prop];
  107. }
  108. }
  109. }
  110. return target;
  111. };
  112. const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  113. var _entityMap = {
  114. '&': '&amp;',
  115. '<': '&lt;',
  116. '>': '&gt;',
  117. '"': '&quot;',
  118. "'": '&#39;',
  119. '/': '&#x2F;'
  120. };
  121. const escape = data => {
  122. if (isString$1(data)) {
  123. return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
  124. }
  125. return data;
  126. };
  127. class RegExpCache {
  128. constructor(capacity) {
  129. this.capacity = capacity;
  130. this.regExpMap = new Map();
  131. this.regExpQueue = [];
  132. }
  133. getRegExp(pattern) {
  134. const regExpFromCache = this.regExpMap.get(pattern);
  135. if (regExpFromCache !== undefined) {
  136. return regExpFromCache;
  137. }
  138. const regExpNew = new RegExp(pattern);
  139. if (this.regExpQueue.length === this.capacity) {
  140. this.regExpMap.delete(this.regExpQueue.shift());
  141. }
  142. this.regExpMap.set(pattern, regExpNew);
  143. this.regExpQueue.push(pattern);
  144. return regExpNew;
  145. }
  146. }
  147. const chars = [' ', ',', '?', '!', ';'];
  148. const looksLikeObjectPathRegExpCache = new RegExpCache(20);
  149. const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
  150. nsSeparator = nsSeparator || '';
  151. keySeparator = keySeparator || '';
  152. const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
  153. if (possibleChars.length === 0) return true;
  154. const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
  155. let matched = !r.test(key);
  156. if (!matched) {
  157. const ki = key.indexOf(keySeparator);
  158. if (ki > 0 && !r.test(key.substring(0, ki))) {
  159. matched = true;
  160. }
  161. }
  162. return matched;
  163. };
  164. const deepFind = (obj, path, keySeparator = '.') => {
  165. if (!obj) return undefined;
  166. if (obj[path]) {
  167. if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
  168. return obj[path];
  169. }
  170. const tokens = path.split(keySeparator);
  171. let current = obj;
  172. for (let i = 0; i < tokens.length;) {
  173. if (!current || typeof current !== 'object') {
  174. return undefined;
  175. }
  176. let next;
  177. let nextPath = '';
  178. for (let j = i; j < tokens.length; ++j) {
  179. if (j !== i) {
  180. nextPath += keySeparator;
  181. }
  182. nextPath += tokens[j];
  183. next = current[nextPath];
  184. if (next !== undefined) {
  185. if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
  186. continue;
  187. }
  188. i += j - i + 1;
  189. break;
  190. }
  191. }
  192. current = next;
  193. }
  194. return current;
  195. };
  196. const getCleanedCode = code => code?.replace('_', '-');
  197. const consoleLogger = {
  198. type: 'logger',
  199. log(args) {
  200. this.output('log', args);
  201. },
  202. warn(args) {
  203. this.output('warn', args);
  204. },
  205. error(args) {
  206. this.output('error', args);
  207. },
  208. output(type, args) {
  209. console?.[type]?.apply?.(console, args);
  210. }
  211. };
  212. class Logger {
  213. constructor(concreteLogger, options = {}) {
  214. this.init(concreteLogger, options);
  215. }
  216. init(concreteLogger, options = {}) {
  217. this.prefix = options.prefix || 'i18next:';
  218. this.logger = concreteLogger || consoleLogger;
  219. this.options = options;
  220. this.debug = options.debug;
  221. }
  222. log(...args) {
  223. return this.forward(args, 'log', '', true);
  224. }
  225. warn(...args) {
  226. return this.forward(args, 'warn', '', true);
  227. }
  228. error(...args) {
  229. return this.forward(args, 'error', '');
  230. }
  231. deprecate(...args) {
  232. return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
  233. }
  234. forward(args, lvl, prefix, debugOnly) {
  235. if (debugOnly && !this.debug) return null;
  236. if (isString$1(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
  237. return this.logger[lvl](args);
  238. }
  239. create(moduleName) {
  240. return new Logger(this.logger, {
  241. ...{
  242. prefix: `${this.prefix}:${moduleName}:`
  243. },
  244. ...this.options
  245. });
  246. }
  247. clone(options) {
  248. options = options || this.options;
  249. options.prefix = options.prefix || this.prefix;
  250. return new Logger(this.logger, options);
  251. }
  252. }
  253. var baseLogger = new Logger();
  254. class EventEmitter {
  255. constructor() {
  256. this.observers = {};
  257. }
  258. on(events, listener) {
  259. events.split(' ').forEach(event => {
  260. if (!this.observers[event]) this.observers[event] = new Map();
  261. const numListeners = this.observers[event].get(listener) || 0;
  262. this.observers[event].set(listener, numListeners + 1);
  263. });
  264. return this;
  265. }
  266. off(event, listener) {
  267. if (!this.observers[event]) return;
  268. if (!listener) {
  269. delete this.observers[event];
  270. return;
  271. }
  272. this.observers[event].delete(listener);
  273. }
  274. emit(event, ...args) {
  275. if (this.observers[event]) {
  276. const cloned = Array.from(this.observers[event].entries());
  277. cloned.forEach(([observer, numTimesAdded]) => {
  278. for (let i = 0; i < numTimesAdded; i++) {
  279. observer(...args);
  280. }
  281. });
  282. }
  283. if (this.observers['*']) {
  284. const cloned = Array.from(this.observers['*'].entries());
  285. cloned.forEach(([observer, numTimesAdded]) => {
  286. for (let i = 0; i < numTimesAdded; i++) {
  287. observer.apply(observer, [event, ...args]);
  288. }
  289. });
  290. }
  291. }
  292. }
  293. class ResourceStore extends EventEmitter {
  294. constructor(data, options = {
  295. ns: ['translation'],
  296. defaultNS: 'translation'
  297. }) {
  298. super();
  299. this.data = data || {};
  300. this.options = options;
  301. if (this.options.keySeparator === undefined) {
  302. this.options.keySeparator = '.';
  303. }
  304. if (this.options.ignoreJSONStructure === undefined) {
  305. this.options.ignoreJSONStructure = true;
  306. }
  307. }
  308. addNamespaces(ns) {
  309. if (this.options.ns.indexOf(ns) < 0) {
  310. this.options.ns.push(ns);
  311. }
  312. }
  313. removeNamespaces(ns) {
  314. const index = this.options.ns.indexOf(ns);
  315. if (index > -1) {
  316. this.options.ns.splice(index, 1);
  317. }
  318. }
  319. getResource(lng, ns, key, options = {}) {
  320. const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
  321. const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
  322. let path;
  323. if (lng.indexOf('.') > -1) {
  324. path = lng.split('.');
  325. } else {
  326. path = [lng, ns];
  327. if (key) {
  328. if (Array.isArray(key)) {
  329. path.push(...key);
  330. } else if (isString$1(key) && keySeparator) {
  331. path.push(...key.split(keySeparator));
  332. } else {
  333. path.push(key);
  334. }
  335. }
  336. }
  337. const result = getPath(this.data, path);
  338. if (!result && !ns && !key && lng.indexOf('.') > -1) {
  339. lng = path[0];
  340. ns = path[1];
  341. key = path.slice(2).join('.');
  342. }
  343. if (result || !ignoreJSONStructure || !isString$1(key)) return result;
  344. return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
  345. }
  346. addResource(lng, ns, key, value, options = {
  347. silent: false
  348. }) {
  349. const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
  350. let path = [lng, ns];
  351. if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
  352. if (lng.indexOf('.') > -1) {
  353. path = lng.split('.');
  354. value = ns;
  355. ns = path[1];
  356. }
  357. this.addNamespaces(ns);
  358. setPath(this.data, path, value);
  359. if (!options.silent) this.emit('added', lng, ns, key, value);
  360. }
  361. addResources(lng, ns, resources, options = {
  362. silent: false
  363. }) {
  364. for (const m in resources) {
  365. if (isString$1(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
  366. silent: true
  367. });
  368. }
  369. if (!options.silent) this.emit('added', lng, ns, resources);
  370. }
  371. addResourceBundle(lng, ns, resources, deep, overwrite, options = {
  372. silent: false,
  373. skipCopy: false
  374. }) {
  375. let path = [lng, ns];
  376. if (lng.indexOf('.') > -1) {
  377. path = lng.split('.');
  378. deep = resources;
  379. resources = ns;
  380. ns = path[1];
  381. }
  382. this.addNamespaces(ns);
  383. let pack = getPath(this.data, path) || {};
  384. if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
  385. if (deep) {
  386. deepExtend(pack, resources, overwrite);
  387. } else {
  388. pack = {
  389. ...pack,
  390. ...resources
  391. };
  392. }
  393. setPath(this.data, path, pack);
  394. if (!options.silent) this.emit('added', lng, ns, resources);
  395. }
  396. removeResourceBundle(lng, ns) {
  397. if (this.hasResourceBundle(lng, ns)) {
  398. delete this.data[lng][ns];
  399. }
  400. this.removeNamespaces(ns);
  401. this.emit('removed', lng, ns);
  402. }
  403. hasResourceBundle(lng, ns) {
  404. return this.getResource(lng, ns) !== undefined;
  405. }
  406. getResourceBundle(lng, ns) {
  407. if (!ns) ns = this.options.defaultNS;
  408. return this.getResource(lng, ns);
  409. }
  410. getDataByLanguage(lng) {
  411. return this.data[lng];
  412. }
  413. hasLanguageSomeTranslations(lng) {
  414. const data = this.getDataByLanguage(lng);
  415. const n = data && Object.keys(data) || [];
  416. return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
  417. }
  418. toJSON() {
  419. return this.data;
  420. }
  421. }
  422. var postProcessor = {
  423. processors: {},
  424. addPostProcessor(module) {
  425. this.processors[module.name] = module;
  426. },
  427. handle(processors, value, key, options, translator) {
  428. processors.forEach(processor => {
  429. value = this.processors[processor]?.process(value, key, options, translator) ?? value;
  430. });
  431. return value;
  432. }
  433. };
  434. const PATH_KEY = Symbol('i18next/PATH_KEY');
  435. function createProxy() {
  436. const state = [];
  437. const handler = Object.create(null);
  438. let proxy;
  439. handler.get = (target, key) => {
  440. proxy?.revoke?.();
  441. if (key === PATH_KEY) return state;
  442. state.push(key);
  443. proxy = Proxy.revocable(target, handler);
  444. return proxy.proxy;
  445. };
  446. return Proxy.revocable(Object.create(null), handler).proxy;
  447. }
  448. function keysFromSelector(selector, opts) {
  449. const {
  450. [PATH_KEY]: path
  451. } = selector(createProxy());
  452. return path.join(opts?.keySeparator ?? '.');
  453. }
  454. const checkedLoadedFor = {};
  455. const shouldHandleAsObject = res => !isString$1(res) && typeof res !== 'boolean' && typeof res !== 'number';
  456. class Translator extends EventEmitter {
  457. constructor(services, options = {}) {
  458. super();
  459. copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
  460. this.options = options;
  461. if (this.options.keySeparator === undefined) {
  462. this.options.keySeparator = '.';
  463. }
  464. this.logger = baseLogger.create('translator');
  465. }
  466. changeLanguage(lng) {
  467. if (lng) this.language = lng;
  468. }
  469. exists(key, o = {
  470. interpolation: {}
  471. }) {
  472. const opt = {
  473. ...o
  474. };
  475. if (key == null) return false;
  476. const resolved = this.resolve(key, opt);
  477. if (resolved?.res === undefined) return false;
  478. const isObject = shouldHandleAsObject(resolved.res);
  479. if (opt.returnObjects === false && isObject) {
  480. return false;
  481. }
  482. return true;
  483. }
  484. extractFromKey(key, opt) {
  485. let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
  486. if (nsSeparator === undefined) nsSeparator = ':';
  487. const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
  488. let namespaces = opt.ns || this.options.defaultNS || [];
  489. const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
  490. const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
  491. if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
  492. const m = key.match(this.interpolator.nestingRegexp);
  493. if (m && m.length > 0) {
  494. return {
  495. key,
  496. namespaces: isString$1(namespaces) ? [namespaces] : namespaces
  497. };
  498. }
  499. const parts = key.split(nsSeparator);
  500. if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
  501. key = parts.join(keySeparator);
  502. }
  503. return {
  504. key,
  505. namespaces: isString$1(namespaces) ? [namespaces] : namespaces
  506. };
  507. }
  508. translate(keys, o, lastKey) {
  509. let opt = typeof o === 'object' ? {
  510. ...o
  511. } : o;
  512. if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
  513. opt = this.options.overloadTranslationOptionHandler(arguments);
  514. }
  515. if (typeof opt === 'object') opt = {
  516. ...opt
  517. };
  518. if (!opt) opt = {};
  519. if (keys == null) return '';
  520. if (typeof keys === 'function') keys = keysFromSelector(keys, {
  521. ...this.options,
  522. ...opt
  523. });
  524. if (!Array.isArray(keys)) keys = [String(keys)];
  525. const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
  526. const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
  527. const {
  528. key,
  529. namespaces
  530. } = this.extractFromKey(keys[keys.length - 1], opt);
  531. const namespace = namespaces[namespaces.length - 1];
  532. let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
  533. if (nsSeparator === undefined) nsSeparator = ':';
  534. const lng = opt.lng || this.language;
  535. const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
  536. if (lng?.toLowerCase() === 'cimode') {
  537. if (appendNamespaceToCIMode) {
  538. if (returnDetails) {
  539. return {
  540. res: `${namespace}${nsSeparator}${key}`,
  541. usedKey: key,
  542. exactUsedKey: key,
  543. usedLng: lng,
  544. usedNS: namespace,
  545. usedParams: this.getUsedParamsDetails(opt)
  546. };
  547. }
  548. return `${namespace}${nsSeparator}${key}`;
  549. }
  550. if (returnDetails) {
  551. return {
  552. res: key,
  553. usedKey: key,
  554. exactUsedKey: key,
  555. usedLng: lng,
  556. usedNS: namespace,
  557. usedParams: this.getUsedParamsDetails(opt)
  558. };
  559. }
  560. return key;
  561. }
  562. const resolved = this.resolve(keys, opt);
  563. let res = resolved?.res;
  564. const resUsedKey = resolved?.usedKey || key;
  565. const resExactUsedKey = resolved?.exactUsedKey || key;
  566. const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
  567. const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
  568. const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
  569. const needsPluralHandling = opt.count !== undefined && !isString$1(opt.count);
  570. const hasDefaultValue = Translator.hasDefaultValue(opt);
  571. const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
  572. const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
  573. ordinal: false
  574. }) : '';
  575. const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
  576. const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
  577. let resForObjHndl = res;
  578. if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
  579. resForObjHndl = defaultValue;
  580. }
  581. const handleAsObject = shouldHandleAsObject(resForObjHndl);
  582. const resType = Object.prototype.toString.apply(resForObjHndl);
  583. if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString$1(joinArrays) && Array.isArray(resForObjHndl))) {
  584. if (!opt.returnObjects && !this.options.returnObjects) {
  585. if (!this.options.returnedObjectHandler) {
  586. this.logger.warn('accessing an object - but returnObjects options is not enabled!');
  587. }
  588. const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
  589. ...opt,
  590. ns: namespaces
  591. }) : `key '${key} (${this.language})' returned an object instead of string.`;
  592. if (returnDetails) {
  593. resolved.res = r;
  594. resolved.usedParams = this.getUsedParamsDetails(opt);
  595. return resolved;
  596. }
  597. return r;
  598. }
  599. if (keySeparator) {
  600. const resTypeIsArray = Array.isArray(resForObjHndl);
  601. const copy = resTypeIsArray ? [] : {};
  602. const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
  603. for (const m in resForObjHndl) {
  604. if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
  605. const deepKey = `${newKeyToUse}${keySeparator}${m}`;
  606. if (hasDefaultValue && !res) {
  607. copy[m] = this.translate(deepKey, {
  608. ...opt,
  609. defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
  610. ...{
  611. joinArrays: false,
  612. ns: namespaces
  613. }
  614. });
  615. } else {
  616. copy[m] = this.translate(deepKey, {
  617. ...opt,
  618. ...{
  619. joinArrays: false,
  620. ns: namespaces
  621. }
  622. });
  623. }
  624. if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
  625. }
  626. }
  627. res = copy;
  628. }
  629. } else if (handleAsObjectInI18nFormat && isString$1(joinArrays) && Array.isArray(res)) {
  630. res = res.join(joinArrays);
  631. if (res) res = this.extendTranslation(res, keys, opt, lastKey);
  632. } else {
  633. let usedDefault = false;
  634. let usedKey = false;
  635. if (!this.isValidLookup(res) && hasDefaultValue) {
  636. usedDefault = true;
  637. res = defaultValue;
  638. }
  639. if (!this.isValidLookup(res)) {
  640. usedKey = true;
  641. res = key;
  642. }
  643. const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
  644. const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
  645. const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
  646. if (usedKey || usedDefault || updateMissing) {
  647. this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
  648. if (keySeparator) {
  649. const fk = this.resolve(key, {
  650. ...opt,
  651. keySeparator: false
  652. });
  653. 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.');
  654. }
  655. let lngs = [];
  656. const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
  657. if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
  658. for (let i = 0; i < fallbackLngs.length; i++) {
  659. lngs.push(fallbackLngs[i]);
  660. }
  661. } else if (this.options.saveMissingTo === 'all') {
  662. lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
  663. } else {
  664. lngs.push(opt.lng || this.language);
  665. }
  666. const send = (l, k, specificDefaultValue) => {
  667. const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
  668. if (this.options.missingKeyHandler) {
  669. this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
  670. } else if (this.backendConnector?.saveMissing) {
  671. this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
  672. }
  673. this.emit('missingKey', l, namespace, k, res);
  674. };
  675. if (this.options.saveMissing) {
  676. if (this.options.saveMissingPlurals && needsPluralHandling) {
  677. lngs.forEach(language => {
  678. const suffixes = this.pluralResolver.getSuffixes(language, opt);
  679. if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
  680. suffixes.push(`${this.options.pluralSeparator}zero`);
  681. }
  682. suffixes.forEach(suffix => {
  683. send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
  684. });
  685. });
  686. } else {
  687. send(lngs, key, defaultValue);
  688. }
  689. }
  690. }
  691. res = this.extendTranslation(res, keys, opt, resolved, lastKey);
  692. if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
  693. res = `${namespace}${nsSeparator}${key}`;
  694. }
  695. if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
  696. res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
  697. }
  698. }
  699. if (returnDetails) {
  700. resolved.res = res;
  701. resolved.usedParams = this.getUsedParamsDetails(opt);
  702. return resolved;
  703. }
  704. return res;
  705. }
  706. extendTranslation(res, key, opt, resolved, lastKey) {
  707. if (this.i18nFormat?.parse) {
  708. res = this.i18nFormat.parse(res, {
  709. ...this.options.interpolation.defaultVariables,
  710. ...opt
  711. }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
  712. resolved
  713. });
  714. } else if (!opt.skipInterpolation) {
  715. if (opt.interpolation) this.interpolator.init({
  716. ...opt,
  717. ...{
  718. interpolation: {
  719. ...this.options.interpolation,
  720. ...opt.interpolation
  721. }
  722. }
  723. });
  724. const skipOnVariables = isString$1(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
  725. let nestBef;
  726. if (skipOnVariables) {
  727. const nb = res.match(this.interpolator.nestingRegexp);
  728. nestBef = nb && nb.length;
  729. }
  730. let data = opt.replace && !isString$1(opt.replace) ? opt.replace : opt;
  731. if (this.options.interpolation.defaultVariables) data = {
  732. ...this.options.interpolation.defaultVariables,
  733. ...data
  734. };
  735. res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
  736. if (skipOnVariables) {
  737. const na = res.match(this.interpolator.nestingRegexp);
  738. const nestAft = na && na.length;
  739. if (nestBef < nestAft) opt.nest = false;
  740. }
  741. if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
  742. if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
  743. if (lastKey?.[0] === args[0] && !opt.context) {
  744. this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
  745. return null;
  746. }
  747. return this.translate(...args, key);
  748. }, opt);
  749. if (opt.interpolation) this.interpolator.reset();
  750. }
  751. const postProcess = opt.postProcess || this.options.postProcess;
  752. const postProcessorNames = isString$1(postProcess) ? [postProcess] : postProcess;
  753. if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
  754. res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
  755. i18nResolved: {
  756. ...resolved,
  757. usedParams: this.getUsedParamsDetails(opt)
  758. },
  759. ...opt
  760. } : opt, this);
  761. }
  762. return res;
  763. }
  764. resolve(keys, opt = {}) {
  765. let found;
  766. let usedKey;
  767. let exactUsedKey;
  768. let usedLng;
  769. let usedNS;
  770. if (isString$1(keys)) keys = [keys];
  771. keys.forEach(k => {
  772. if (this.isValidLookup(found)) return;
  773. const extracted = this.extractFromKey(k, opt);
  774. const key = extracted.key;
  775. usedKey = key;
  776. let namespaces = extracted.namespaces;
  777. if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
  778. const needsPluralHandling = opt.count !== undefined && !isString$1(opt.count);
  779. const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
  780. const needsContextHandling = opt.context !== undefined && (isString$1(opt.context) || typeof opt.context === 'number') && opt.context !== '';
  781. const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
  782. namespaces.forEach(ns => {
  783. if (this.isValidLookup(found)) return;
  784. usedNS = ns;
  785. if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
  786. checkedLoadedFor[`${codes[0]}-${ns}`] = true;
  787. 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!!!');
  788. }
  789. codes.forEach(code => {
  790. if (this.isValidLookup(found)) return;
  791. usedLng = code;
  792. const finalKeys = [key];
  793. if (this.i18nFormat?.addLookupKeys) {
  794. this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
  795. } else {
  796. let pluralSuffix;
  797. if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
  798. const zeroSuffix = `${this.options.pluralSeparator}zero`;
  799. const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
  800. if (needsPluralHandling) {
  801. if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
  802. finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
  803. }
  804. finalKeys.push(key + pluralSuffix);
  805. if (needsZeroSuffixLookup) {
  806. finalKeys.push(key + zeroSuffix);
  807. }
  808. }
  809. if (needsContextHandling) {
  810. const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
  811. finalKeys.push(contextKey);
  812. if (needsPluralHandling) {
  813. if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
  814. finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
  815. }
  816. finalKeys.push(contextKey + pluralSuffix);
  817. if (needsZeroSuffixLookup) {
  818. finalKeys.push(contextKey + zeroSuffix);
  819. }
  820. }
  821. }
  822. }
  823. let possibleKey;
  824. while (possibleKey = finalKeys.pop()) {
  825. if (!this.isValidLookup(found)) {
  826. exactUsedKey = possibleKey;
  827. found = this.getResource(code, ns, possibleKey, opt);
  828. }
  829. }
  830. });
  831. });
  832. });
  833. return {
  834. res: found,
  835. usedKey,
  836. exactUsedKey,
  837. usedLng,
  838. usedNS
  839. };
  840. }
  841. isValidLookup(res) {
  842. return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
  843. }
  844. getResource(code, ns, key, options = {}) {
  845. if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
  846. return this.resourceStore.getResource(code, ns, key, options);
  847. }
  848. getUsedParamsDetails(options = {}) {
  849. const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
  850. const useOptionsReplaceForData = options.replace && !isString$1(options.replace);
  851. let data = useOptionsReplaceForData ? options.replace : options;
  852. if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
  853. data.count = options.count;
  854. }
  855. if (this.options.interpolation.defaultVariables) {
  856. data = {
  857. ...this.options.interpolation.defaultVariables,
  858. ...data
  859. };
  860. }
  861. if (!useOptionsReplaceForData) {
  862. data = {
  863. ...data
  864. };
  865. for (const key of optionsKeys) {
  866. delete data[key];
  867. }
  868. }
  869. return data;
  870. }
  871. static hasDefaultValue(options) {
  872. const prefix = 'defaultValue';
  873. for (const option in options) {
  874. if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
  875. return true;
  876. }
  877. }
  878. return false;
  879. }
  880. }
  881. class LanguageUtil {
  882. constructor(options) {
  883. this.options = options;
  884. this.supportedLngs = this.options.supportedLngs || false;
  885. this.logger = baseLogger.create('languageUtils');
  886. }
  887. getScriptPartFromCode(code) {
  888. code = getCleanedCode(code);
  889. if (!code || code.indexOf('-') < 0) return null;
  890. const p = code.split('-');
  891. if (p.length === 2) return null;
  892. p.pop();
  893. if (p[p.length - 1].toLowerCase() === 'x') return null;
  894. return this.formatLanguageCode(p.join('-'));
  895. }
  896. getLanguagePartFromCode(code) {
  897. code = getCleanedCode(code);
  898. if (!code || code.indexOf('-') < 0) return code;
  899. const p = code.split('-');
  900. return this.formatLanguageCode(p[0]);
  901. }
  902. formatLanguageCode(code) {
  903. if (isString$1(code) && code.indexOf('-') > -1) {
  904. let formattedCode;
  905. try {
  906. formattedCode = Intl.getCanonicalLocales(code)[0];
  907. } catch (e) {}
  908. if (formattedCode && this.options.lowerCaseLng) {
  909. formattedCode = formattedCode.toLowerCase();
  910. }
  911. if (formattedCode) return formattedCode;
  912. if (this.options.lowerCaseLng) {
  913. return code.toLowerCase();
  914. }
  915. return code;
  916. }
  917. return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
  918. }
  919. isSupportedCode(code) {
  920. if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
  921. code = this.getLanguagePartFromCode(code);
  922. }
  923. return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
  924. }
  925. getBestMatchFromCodes(codes) {
  926. if (!codes) return null;
  927. let found;
  928. codes.forEach(code => {
  929. if (found) return;
  930. const cleanedLng = this.formatLanguageCode(code);
  931. if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
  932. });
  933. if (!found && this.options.supportedLngs) {
  934. codes.forEach(code => {
  935. if (found) return;
  936. const lngScOnly = this.getScriptPartFromCode(code);
  937. if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
  938. const lngOnly = this.getLanguagePartFromCode(code);
  939. if (this.isSupportedCode(lngOnly)) return found = lngOnly;
  940. found = this.options.supportedLngs.find(supportedLng => {
  941. if (supportedLng === lngOnly) return supportedLng;
  942. if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
  943. if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
  944. if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
  945. });
  946. });
  947. }
  948. if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
  949. return found;
  950. }
  951. getFallbackCodes(fallbacks, code) {
  952. if (!fallbacks) return [];
  953. if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
  954. if (isString$1(fallbacks)) fallbacks = [fallbacks];
  955. if (Array.isArray(fallbacks)) return fallbacks;
  956. if (!code) return fallbacks.default || [];
  957. let found = fallbacks[code];
  958. if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
  959. if (!found) found = fallbacks[this.formatLanguageCode(code)];
  960. if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
  961. if (!found) found = fallbacks.default;
  962. return found || [];
  963. }
  964. toResolveHierarchy(code, fallbackCode) {
  965. const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
  966. const codes = [];
  967. const addCode = c => {
  968. if (!c) return;
  969. if (this.isSupportedCode(c)) {
  970. codes.push(c);
  971. } else {
  972. this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
  973. }
  974. };
  975. if (isString$1(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
  976. if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
  977. if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
  978. if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
  979. } else if (isString$1(code)) {
  980. addCode(this.formatLanguageCode(code));
  981. }
  982. fallbackCodes.forEach(fc => {
  983. if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
  984. });
  985. return codes;
  986. }
  987. }
  988. const suffixesOrder = {
  989. zero: 0,
  990. one: 1,
  991. two: 2,
  992. few: 3,
  993. many: 4,
  994. other: 5
  995. };
  996. const dummyRule = {
  997. select: count => count === 1 ? 'one' : 'other',
  998. resolvedOptions: () => ({
  999. pluralCategories: ['one', 'other']
  1000. })
  1001. };
  1002. class PluralResolver {
  1003. constructor(languageUtils, options = {}) {
  1004. this.languageUtils = languageUtils;
  1005. this.options = options;
  1006. this.logger = baseLogger.create('pluralResolver');
  1007. this.pluralRulesCache = {};
  1008. }
  1009. addRule(lng, obj) {
  1010. this.rules[lng] = obj;
  1011. }
  1012. clearCache() {
  1013. this.pluralRulesCache = {};
  1014. }
  1015. getRule(code, options = {}) {
  1016. const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
  1017. const type = options.ordinal ? 'ordinal' : 'cardinal';
  1018. const cacheKey = JSON.stringify({
  1019. cleanedCode,
  1020. type
  1021. });
  1022. if (cacheKey in this.pluralRulesCache) {
  1023. return this.pluralRulesCache[cacheKey];
  1024. }
  1025. let rule;
  1026. try {
  1027. rule = new Intl.PluralRules(cleanedCode, {
  1028. type
  1029. });
  1030. } catch (err) {
  1031. if (!Intl) {
  1032. this.logger.error('No Intl support, please use an Intl polyfill!');
  1033. return dummyRule;
  1034. }
  1035. if (!code.match(/-|_/)) return dummyRule;
  1036. const lngPart = this.languageUtils.getLanguagePartFromCode(code);
  1037. rule = this.getRule(lngPart, options);
  1038. }
  1039. this.pluralRulesCache[cacheKey] = rule;
  1040. return rule;
  1041. }
  1042. needsPlural(code, options = {}) {
  1043. let rule = this.getRule(code, options);
  1044. if (!rule) rule = this.getRule('dev', options);
  1045. return rule?.resolvedOptions().pluralCategories.length > 1;
  1046. }
  1047. getPluralFormsOfKey(code, key, options = {}) {
  1048. return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
  1049. }
  1050. getSuffixes(code, options = {}) {
  1051. let rule = this.getRule(code, options);
  1052. if (!rule) rule = this.getRule('dev', options);
  1053. if (!rule) return [];
  1054. return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
  1055. }
  1056. getSuffix(code, count, options = {}) {
  1057. const rule = this.getRule(code, options);
  1058. if (rule) {
  1059. return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
  1060. }
  1061. this.logger.warn(`no plural rule found for: ${code}`);
  1062. return this.getSuffix('dev', count, options);
  1063. }
  1064. }
  1065. const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
  1066. let path = getPathWithDefaults(data, defaultData, key);
  1067. if (!path && ignoreJSONStructure && isString$1(key)) {
  1068. path = deepFind(data, key, keySeparator);
  1069. if (path === undefined) path = deepFind(defaultData, key, keySeparator);
  1070. }
  1071. return path;
  1072. };
  1073. const regexSafe = val => val.replace(/\$/g, '$$$$');
  1074. class Interpolator {
  1075. constructor(options = {}) {
  1076. this.logger = baseLogger.create('interpolator');
  1077. this.options = options;
  1078. this.format = options?.interpolation?.format || (value => value);
  1079. this.init(options);
  1080. }
  1081. init(options = {}) {
  1082. if (!options.interpolation) options.interpolation = {
  1083. escapeValue: true
  1084. };
  1085. const {
  1086. escape: escape$1,
  1087. escapeValue,
  1088. useRawValueToEscape,
  1089. prefix,
  1090. prefixEscaped,
  1091. suffix,
  1092. suffixEscaped,
  1093. formatSeparator,
  1094. unescapeSuffix,
  1095. unescapePrefix,
  1096. nestingPrefix,
  1097. nestingPrefixEscaped,
  1098. nestingSuffix,
  1099. nestingSuffixEscaped,
  1100. nestingOptionsSeparator,
  1101. maxReplaces,
  1102. alwaysFormat
  1103. } = options.interpolation;
  1104. this.escape = escape$1 !== undefined ? escape$1 : escape;
  1105. this.escapeValue = escapeValue !== undefined ? escapeValue : true;
  1106. this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
  1107. this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
  1108. this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
  1109. this.formatSeparator = formatSeparator || ',';
  1110. this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
  1111. this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
  1112. this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
  1113. this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
  1114. this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
  1115. this.maxReplaces = maxReplaces || 1000;
  1116. this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
  1117. this.resetRegExp();
  1118. }
  1119. reset() {
  1120. if (this.options) this.init(this.options);
  1121. }
  1122. resetRegExp() {
  1123. const getOrResetRegExp = (existingRegExp, pattern) => {
  1124. if (existingRegExp?.source === pattern) {
  1125. existingRegExp.lastIndex = 0;
  1126. return existingRegExp;
  1127. }
  1128. return new RegExp(pattern, 'g');
  1129. };
  1130. this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
  1131. this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
  1132. this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
  1133. }
  1134. interpolate(str, data, lng, options) {
  1135. let match;
  1136. let value;
  1137. let replaces;
  1138. const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
  1139. const handleFormat = key => {
  1140. if (key.indexOf(this.formatSeparator) < 0) {
  1141. const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
  1142. return this.alwaysFormat ? this.format(path, undefined, lng, {
  1143. ...options,
  1144. ...data,
  1145. interpolationkey: key
  1146. }) : path;
  1147. }
  1148. const p = key.split(this.formatSeparator);
  1149. const k = p.shift().trim();
  1150. const f = p.join(this.formatSeparator).trim();
  1151. return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
  1152. ...options,
  1153. ...data,
  1154. interpolationkey: k
  1155. });
  1156. };
  1157. this.resetRegExp();
  1158. const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
  1159. const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
  1160. const todos = [{
  1161. regex: this.regexpUnescape,
  1162. safeValue: val => regexSafe(val)
  1163. }, {
  1164. regex: this.regexp,
  1165. safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
  1166. }];
  1167. todos.forEach(todo => {
  1168. replaces = 0;
  1169. while (match = todo.regex.exec(str)) {
  1170. const matchedVar = match[1].trim();
  1171. value = handleFormat(matchedVar);
  1172. if (value === undefined) {
  1173. if (typeof missingInterpolationHandler === 'function') {
  1174. const temp = missingInterpolationHandler(str, match, options);
  1175. value = isString$1(temp) ? temp : '';
  1176. } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
  1177. value = '';
  1178. } else if (skipOnVariables) {
  1179. value = match[0];
  1180. continue;
  1181. } else {
  1182. this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
  1183. value = '';
  1184. }
  1185. } else if (!isString$1(value) && !this.useRawValueToEscape) {
  1186. value = makeString(value);
  1187. }
  1188. const safeValue = todo.safeValue(value);
  1189. str = str.replace(match[0], safeValue);
  1190. if (skipOnVariables) {
  1191. todo.regex.lastIndex += value.length;
  1192. todo.regex.lastIndex -= match[0].length;
  1193. } else {
  1194. todo.regex.lastIndex = 0;
  1195. }
  1196. replaces++;
  1197. if (replaces >= this.maxReplaces) {
  1198. break;
  1199. }
  1200. }
  1201. });
  1202. return str;
  1203. }
  1204. nest(str, fc, options = {}) {
  1205. let match;
  1206. let value;
  1207. let clonedOptions;
  1208. const handleHasOptions = (key, inheritedOptions) => {
  1209. const sep = this.nestingOptionsSeparator;
  1210. if (key.indexOf(sep) < 0) return key;
  1211. const c = key.split(new RegExp(`${sep}[ ]*{`));
  1212. let optionsString = `{${c[1]}`;
  1213. key = c[0];
  1214. optionsString = this.interpolate(optionsString, clonedOptions);
  1215. const matchedSingleQuotes = optionsString.match(/'/g);
  1216. const matchedDoubleQuotes = optionsString.match(/"/g);
  1217. if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
  1218. optionsString = optionsString.replace(/'/g, '"');
  1219. }
  1220. try {
  1221. clonedOptions = JSON.parse(optionsString);
  1222. if (inheritedOptions) clonedOptions = {
  1223. ...inheritedOptions,
  1224. ...clonedOptions
  1225. };
  1226. } catch (e) {
  1227. this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
  1228. return `${key}${sep}${optionsString}`;
  1229. }
  1230. if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
  1231. return key;
  1232. };
  1233. while (match = this.nestingRegexp.exec(str)) {
  1234. let formatters = [];
  1235. clonedOptions = {
  1236. ...options
  1237. };
  1238. clonedOptions = clonedOptions.replace && !isString$1(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
  1239. clonedOptions.applyPostProcessor = false;
  1240. delete clonedOptions.defaultValue;
  1241. const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
  1242. if (keyEndIndex !== -1) {
  1243. formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
  1244. match[1] = match[1].slice(0, keyEndIndex);
  1245. }
  1246. value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
  1247. if (value && match[0] === str && !isString$1(value)) return value;
  1248. if (!isString$1(value)) value = makeString(value);
  1249. if (!value) {
  1250. this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
  1251. value = '';
  1252. }
  1253. if (formatters.length) {
  1254. value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
  1255. ...options,
  1256. interpolationkey: match[1].trim()
  1257. }), value.trim());
  1258. }
  1259. str = str.replace(match[0], value);
  1260. this.regexp.lastIndex = 0;
  1261. }
  1262. return str;
  1263. }
  1264. }
  1265. const parseFormatStr = formatStr => {
  1266. let formatName = formatStr.toLowerCase().trim();
  1267. const formatOptions = {};
  1268. if (formatStr.indexOf('(') > -1) {
  1269. const p = formatStr.split('(');
  1270. formatName = p[0].toLowerCase().trim();
  1271. const optStr = p[1].substring(0, p[1].length - 1);
  1272. if (formatName === 'currency' && optStr.indexOf(':') < 0) {
  1273. if (!formatOptions.currency) formatOptions.currency = optStr.trim();
  1274. } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
  1275. if (!formatOptions.range) formatOptions.range = optStr.trim();
  1276. } else {
  1277. const opts = optStr.split(';');
  1278. opts.forEach(opt => {
  1279. if (opt) {
  1280. const [key, ...rest] = opt.split(':');
  1281. const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
  1282. const trimmedKey = key.trim();
  1283. if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
  1284. if (val === 'false') formatOptions[trimmedKey] = false;
  1285. if (val === 'true') formatOptions[trimmedKey] = true;
  1286. if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
  1287. }
  1288. });
  1289. }
  1290. }
  1291. return {
  1292. formatName,
  1293. formatOptions
  1294. };
  1295. };
  1296. const createCachedFormatter = fn => {
  1297. const cache = {};
  1298. return (v, l, o) => {
  1299. let optForCache = o;
  1300. if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
  1301. optForCache = {
  1302. ...optForCache,
  1303. [o.interpolationkey]: undefined
  1304. };
  1305. }
  1306. const key = l + JSON.stringify(optForCache);
  1307. let frm = cache[key];
  1308. if (!frm) {
  1309. frm = fn(getCleanedCode(l), o);
  1310. cache[key] = frm;
  1311. }
  1312. return frm(v);
  1313. };
  1314. };
  1315. const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
  1316. class Formatter {
  1317. constructor(options = {}) {
  1318. this.logger = baseLogger.create('formatter');
  1319. this.options = options;
  1320. this.init(options);
  1321. }
  1322. init(services, options = {
  1323. interpolation: {}
  1324. }) {
  1325. this.formatSeparator = options.interpolation.formatSeparator || ',';
  1326. const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
  1327. this.formats = {
  1328. number: cf((lng, opt) => {
  1329. const formatter = new Intl.NumberFormat(lng, {
  1330. ...opt
  1331. });
  1332. return val => formatter.format(val);
  1333. }),
  1334. currency: cf((lng, opt) => {
  1335. const formatter = new Intl.NumberFormat(lng, {
  1336. ...opt,
  1337. style: 'currency'
  1338. });
  1339. return val => formatter.format(val);
  1340. }),
  1341. datetime: cf((lng, opt) => {
  1342. const formatter = new Intl.DateTimeFormat(lng, {
  1343. ...opt
  1344. });
  1345. return val => formatter.format(val);
  1346. }),
  1347. relativetime: cf((lng, opt) => {
  1348. const formatter = new Intl.RelativeTimeFormat(lng, {
  1349. ...opt
  1350. });
  1351. return val => formatter.format(val, opt.range || 'day');
  1352. }),
  1353. list: cf((lng, opt) => {
  1354. const formatter = new Intl.ListFormat(lng, {
  1355. ...opt
  1356. });
  1357. return val => formatter.format(val);
  1358. })
  1359. };
  1360. }
  1361. add(name, fc) {
  1362. this.formats[name.toLowerCase().trim()] = fc;
  1363. }
  1364. addCached(name, fc) {
  1365. this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
  1366. }
  1367. format(value, format, lng, options = {}) {
  1368. const formats = format.split(this.formatSeparator);
  1369. if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
  1370. const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
  1371. formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
  1372. }
  1373. const result = formats.reduce((mem, f) => {
  1374. const {
  1375. formatName,
  1376. formatOptions
  1377. } = parseFormatStr(f);
  1378. if (this.formats[formatName]) {
  1379. let formatted = mem;
  1380. try {
  1381. const valOptions = options?.formatParams?.[options.interpolationkey] || {};
  1382. const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
  1383. formatted = this.formats[formatName](mem, l, {
  1384. ...formatOptions,
  1385. ...options,
  1386. ...valOptions
  1387. });
  1388. } catch (error) {
  1389. this.logger.warn(error);
  1390. }
  1391. return formatted;
  1392. } else {
  1393. this.logger.warn(`there was no format function for ${formatName}`);
  1394. }
  1395. return mem;
  1396. }, value);
  1397. return result;
  1398. }
  1399. }
  1400. const removePending = (q, name) => {
  1401. if (q.pending[name] !== undefined) {
  1402. delete q.pending[name];
  1403. q.pendingCount--;
  1404. }
  1405. };
  1406. class Connector extends EventEmitter {
  1407. constructor(backend, store, services, options = {}) {
  1408. super();
  1409. this.backend = backend;
  1410. this.store = store;
  1411. this.services = services;
  1412. this.languageUtils = services.languageUtils;
  1413. this.options = options;
  1414. this.logger = baseLogger.create('backendConnector');
  1415. this.waitingReads = [];
  1416. this.maxParallelReads = options.maxParallelReads || 10;
  1417. this.readingCalls = 0;
  1418. this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
  1419. this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
  1420. this.state = {};
  1421. this.queue = [];
  1422. this.backend?.init?.(services, options.backend, options);
  1423. }
  1424. queueLoad(languages, namespaces, options, callback) {
  1425. const toLoad = {};
  1426. const pending = {};
  1427. const toLoadLanguages = {};
  1428. const toLoadNamespaces = {};
  1429. languages.forEach(lng => {
  1430. let hasAllNamespaces = true;
  1431. namespaces.forEach(ns => {
  1432. const name = `${lng}|${ns}`;
  1433. if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
  1434. this.state[name] = 2;
  1435. } else if (this.state[name] < 0) ;else if (this.state[name] === 1) {
  1436. if (pending[name] === undefined) pending[name] = true;
  1437. } else {
  1438. this.state[name] = 1;
  1439. hasAllNamespaces = false;
  1440. if (pending[name] === undefined) pending[name] = true;
  1441. if (toLoad[name] === undefined) toLoad[name] = true;
  1442. if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
  1443. }
  1444. });
  1445. if (!hasAllNamespaces) toLoadLanguages[lng] = true;
  1446. });
  1447. if (Object.keys(toLoad).length || Object.keys(pending).length) {
  1448. this.queue.push({
  1449. pending,
  1450. pendingCount: Object.keys(pending).length,
  1451. loaded: {},
  1452. errors: [],
  1453. callback
  1454. });
  1455. }
  1456. return {
  1457. toLoad: Object.keys(toLoad),
  1458. pending: Object.keys(pending),
  1459. toLoadLanguages: Object.keys(toLoadLanguages),
  1460. toLoadNamespaces: Object.keys(toLoadNamespaces)
  1461. };
  1462. }
  1463. loaded(name, err, data) {
  1464. const s = name.split('|');
  1465. const lng = s[0];
  1466. const ns = s[1];
  1467. if (err) this.emit('failedLoading', lng, ns, err);
  1468. if (!err && data) {
  1469. this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
  1470. skipCopy: true
  1471. });
  1472. }
  1473. this.state[name] = err ? -1 : 2;
  1474. if (err && data) this.state[name] = 0;
  1475. const loaded = {};
  1476. this.queue.forEach(q => {
  1477. pushPath(q.loaded, [lng], ns);
  1478. removePending(q, name);
  1479. if (err) q.errors.push(err);
  1480. if (q.pendingCount === 0 && !q.done) {
  1481. Object.keys(q.loaded).forEach(l => {
  1482. if (!loaded[l]) loaded[l] = {};
  1483. const loadedKeys = q.loaded[l];
  1484. if (loadedKeys.length) {
  1485. loadedKeys.forEach(n => {
  1486. if (loaded[l][n] === undefined) loaded[l][n] = true;
  1487. });
  1488. }
  1489. });
  1490. q.done = true;
  1491. if (q.errors.length) {
  1492. q.callback(q.errors);
  1493. } else {
  1494. q.callback();
  1495. }
  1496. }
  1497. });
  1498. this.emit('loaded', loaded);
  1499. this.queue = this.queue.filter(q => !q.done);
  1500. }
  1501. read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
  1502. if (!lng.length) return callback(null, {});
  1503. if (this.readingCalls >= this.maxParallelReads) {
  1504. this.waitingReads.push({
  1505. lng,
  1506. ns,
  1507. fcName,
  1508. tried,
  1509. wait,
  1510. callback
  1511. });
  1512. return;
  1513. }
  1514. this.readingCalls++;
  1515. const resolver = (err, data) => {
  1516. this.readingCalls--;
  1517. if (this.waitingReads.length > 0) {
  1518. const next = this.waitingReads.shift();
  1519. this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
  1520. }
  1521. if (err && data && tried < this.maxRetries) {
  1522. setTimeout(() => {
  1523. this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
  1524. }, wait);
  1525. return;
  1526. }
  1527. callback(err, data);
  1528. };
  1529. const fc = this.backend[fcName].bind(this.backend);
  1530. if (fc.length === 2) {
  1531. try {
  1532. const r = fc(lng, ns);
  1533. if (r && typeof r.then === 'function') {
  1534. r.then(data => resolver(null, data)).catch(resolver);
  1535. } else {
  1536. resolver(null, r);
  1537. }
  1538. } catch (err) {
  1539. resolver(err);
  1540. }
  1541. return;
  1542. }
  1543. return fc(lng, ns, resolver);
  1544. }
  1545. prepareLoading(languages, namespaces, options = {}, callback) {
  1546. if (!this.backend) {
  1547. this.logger.warn('No backend was added via i18next.use. Will not load resources.');
  1548. return callback && callback();
  1549. }
  1550. if (isString$1(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
  1551. if (isString$1(namespaces)) namespaces = [namespaces];
  1552. const toLoad = this.queueLoad(languages, namespaces, options, callback);
  1553. if (!toLoad.toLoad.length) {
  1554. if (!toLoad.pending.length) callback();
  1555. return null;
  1556. }
  1557. toLoad.toLoad.forEach(name => {
  1558. this.loadOne(name);
  1559. });
  1560. }
  1561. load(languages, namespaces, callback) {
  1562. this.prepareLoading(languages, namespaces, {}, callback);
  1563. }
  1564. reload(languages, namespaces, callback) {
  1565. this.prepareLoading(languages, namespaces, {
  1566. reload: true
  1567. }, callback);
  1568. }
  1569. loadOne(name, prefix = '') {
  1570. const s = name.split('|');
  1571. const lng = s[0];
  1572. const ns = s[1];
  1573. this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
  1574. if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
  1575. if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
  1576. this.loaded(name, err, data);
  1577. });
  1578. }
  1579. saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
  1580. if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
  1581. 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!!!');
  1582. return;
  1583. }
  1584. if (key === undefined || key === null || key === '') return;
  1585. if (this.backend?.create) {
  1586. const opts = {
  1587. ...options,
  1588. isUpdate
  1589. };
  1590. const fc = this.backend.create.bind(this.backend);
  1591. if (fc.length < 6) {
  1592. try {
  1593. let r;
  1594. if (fc.length === 5) {
  1595. r = fc(languages, namespace, key, fallbackValue, opts);
  1596. } else {
  1597. r = fc(languages, namespace, key, fallbackValue);
  1598. }
  1599. if (r && typeof r.then === 'function') {
  1600. r.then(data => clb(null, data)).catch(clb);
  1601. } else {
  1602. clb(null, r);
  1603. }
  1604. } catch (err) {
  1605. clb(err);
  1606. }
  1607. } else {
  1608. fc(languages, namespace, key, fallbackValue, clb, opts);
  1609. }
  1610. }
  1611. if (!languages || !languages[0]) return;
  1612. this.store.addResource(languages[0], namespace, key, fallbackValue);
  1613. }
  1614. }
  1615. const get = () => ({
  1616. debug: false,
  1617. initAsync: true,
  1618. ns: ['translation'],
  1619. defaultNS: ['translation'],
  1620. fallbackLng: ['dev'],
  1621. fallbackNS: false,
  1622. supportedLngs: false,
  1623. nonExplicitSupportedLngs: false,
  1624. load: 'all',
  1625. preload: false,
  1626. simplifyPluralSuffix: true,
  1627. keySeparator: '.',
  1628. nsSeparator: ':',
  1629. pluralSeparator: '_',
  1630. contextSeparator: '_',
  1631. partialBundledLanguages: false,
  1632. saveMissing: false,
  1633. updateMissing: false,
  1634. saveMissingTo: 'fallback',
  1635. saveMissingPlurals: true,
  1636. missingKeyHandler: false,
  1637. missingInterpolationHandler: false,
  1638. postProcess: false,
  1639. postProcessPassResolved: false,
  1640. returnNull: false,
  1641. returnEmptyString: true,
  1642. returnObjects: false,
  1643. joinArrays: false,
  1644. returnedObjectHandler: false,
  1645. parseMissingKeyHandler: false,
  1646. appendNamespaceToMissingKey: false,
  1647. appendNamespaceToCIMode: false,
  1648. overloadTranslationOptionHandler: args => {
  1649. let ret = {};
  1650. if (typeof args[1] === 'object') ret = args[1];
  1651. if (isString$1(args[1])) ret.defaultValue = args[1];
  1652. if (isString$1(args[2])) ret.tDescription = args[2];
  1653. if (typeof args[2] === 'object' || typeof args[3] === 'object') {
  1654. const options = args[3] || args[2];
  1655. Object.keys(options).forEach(key => {
  1656. ret[key] = options[key];
  1657. });
  1658. }
  1659. return ret;
  1660. },
  1661. interpolation: {
  1662. escapeValue: true,
  1663. format: value => value,
  1664. prefix: '{{',
  1665. suffix: '}}',
  1666. formatSeparator: ',',
  1667. unescapePrefix: '-',
  1668. nestingPrefix: '$t(',
  1669. nestingSuffix: ')',
  1670. nestingOptionsSeparator: ',',
  1671. maxReplaces: 1000,
  1672. skipOnVariables: true
  1673. },
  1674. cacheInBuiltFormats: true
  1675. });
  1676. const transformOptions = options => {
  1677. if (isString$1(options.ns)) options.ns = [options.ns];
  1678. if (isString$1(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
  1679. if (isString$1(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
  1680. if (options.supportedLngs?.indexOf?.('cimode') < 0) {
  1681. options.supportedLngs = options.supportedLngs.concat(['cimode']);
  1682. }
  1683. if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
  1684. return options;
  1685. };
  1686. const noop = () => {};
  1687. const bindMemberFunctions = inst => {
  1688. const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
  1689. mems.forEach(mem => {
  1690. if (typeof inst[mem] === 'function') {
  1691. inst[mem] = inst[mem].bind(inst);
  1692. }
  1693. });
  1694. };
  1695. class I18n extends EventEmitter {
  1696. constructor(options = {}, callback) {
  1697. super();
  1698. this.options = transformOptions(options);
  1699. this.services = {};
  1700. this.logger = baseLogger;
  1701. this.modules = {
  1702. external: []
  1703. };
  1704. bindMemberFunctions(this);
  1705. if (callback && !this.isInitialized && !options.isClone) {
  1706. if (!this.options.initAsync) {
  1707. this.init(options, callback);
  1708. return this;
  1709. }
  1710. setTimeout(() => {
  1711. this.init(options, callback);
  1712. }, 0);
  1713. }
  1714. }
  1715. init(options = {}, callback) {
  1716. this.isInitializing = true;
  1717. if (typeof options === 'function') {
  1718. callback = options;
  1719. options = {};
  1720. }
  1721. if (options.defaultNS == null && options.ns) {
  1722. if (isString$1(options.ns)) {
  1723. options.defaultNS = options.ns;
  1724. } else if (options.ns.indexOf('translation') < 0) {
  1725. options.defaultNS = options.ns[0];
  1726. }
  1727. }
  1728. const defOpts = get();
  1729. this.options = {
  1730. ...defOpts,
  1731. ...this.options,
  1732. ...transformOptions(options)
  1733. };
  1734. this.options.interpolation = {
  1735. ...defOpts.interpolation,
  1736. ...this.options.interpolation
  1737. };
  1738. if (options.keySeparator !== undefined) {
  1739. this.options.userDefinedKeySeparator = options.keySeparator;
  1740. }
  1741. if (options.nsSeparator !== undefined) {
  1742. this.options.userDefinedNsSeparator = options.nsSeparator;
  1743. }
  1744. const createClassOnDemand = ClassOrObject => {
  1745. if (!ClassOrObject) return null;
  1746. if (typeof ClassOrObject === 'function') return new ClassOrObject();
  1747. return ClassOrObject;
  1748. };
  1749. if (!this.options.isClone) {
  1750. if (this.modules.logger) {
  1751. baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
  1752. } else {
  1753. baseLogger.init(null, this.options);
  1754. }
  1755. let formatter;
  1756. if (this.modules.formatter) {
  1757. formatter = this.modules.formatter;
  1758. } else {
  1759. formatter = Formatter;
  1760. }
  1761. const lu = new LanguageUtil(this.options);
  1762. this.store = new ResourceStore(this.options.resources, this.options);
  1763. const s = this.services;
  1764. s.logger = baseLogger;
  1765. s.resourceStore = this.store;
  1766. s.languageUtils = lu;
  1767. s.pluralResolver = new PluralResolver(lu, {
  1768. prepend: this.options.pluralSeparator,
  1769. simplifyPluralSuffix: this.options.simplifyPluralSuffix
  1770. });
  1771. const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
  1772. if (usingLegacyFormatFunction) {
  1773. this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
  1774. }
  1775. if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
  1776. s.formatter = createClassOnDemand(formatter);
  1777. if (s.formatter.init) s.formatter.init(s, this.options);
  1778. this.options.interpolation.format = s.formatter.format.bind(s.formatter);
  1779. }
  1780. s.interpolator = new Interpolator(this.options);
  1781. s.utils = {
  1782. hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
  1783. };
  1784. s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
  1785. s.backendConnector.on('*', (event, ...args) => {
  1786. this.emit(event, ...args);
  1787. });
  1788. if (this.modules.languageDetector) {
  1789. s.languageDetector = createClassOnDemand(this.modules.languageDetector);
  1790. if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
  1791. }
  1792. if (this.modules.i18nFormat) {
  1793. s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
  1794. if (s.i18nFormat.init) s.i18nFormat.init(this);
  1795. }
  1796. this.translator = new Translator(this.services, this.options);
  1797. this.translator.on('*', (event, ...args) => {
  1798. this.emit(event, ...args);
  1799. });
  1800. this.modules.external.forEach(m => {
  1801. if (m.init) m.init(this);
  1802. });
  1803. }
  1804. this.format = this.options.interpolation.format;
  1805. if (!callback) callback = noop;
  1806. if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
  1807. const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
  1808. if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
  1809. }
  1810. if (!this.services.languageDetector && !this.options.lng) {
  1811. this.logger.warn('init: no languageDetector is used and no lng is defined');
  1812. }
  1813. const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
  1814. storeApi.forEach(fcName => {
  1815. this[fcName] = (...args) => this.store[fcName](...args);
  1816. });
  1817. const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
  1818. storeApiChained.forEach(fcName => {
  1819. this[fcName] = (...args) => {
  1820. this.store[fcName](...args);
  1821. return this;
  1822. };
  1823. });
  1824. const deferred = defer();
  1825. const load = () => {
  1826. const finish = (err, t) => {
  1827. this.isInitializing = false;
  1828. if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
  1829. this.isInitialized = true;
  1830. if (!this.options.isClone) this.logger.log('initialized', this.options);
  1831. this.emit('initialized', this.options);
  1832. deferred.resolve(t);
  1833. callback(err, t);
  1834. };
  1835. if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
  1836. this.changeLanguage(this.options.lng, finish);
  1837. };
  1838. if (this.options.resources || !this.options.initAsync) {
  1839. load();
  1840. } else {
  1841. setTimeout(load, 0);
  1842. }
  1843. return deferred;
  1844. }
  1845. loadResources(language, callback = noop) {
  1846. let usedCallback = callback;
  1847. const usedLng = isString$1(language) ? language : this.language;
  1848. if (typeof language === 'function') usedCallback = language;
  1849. if (!this.options.resources || this.options.partialBundledLanguages) {
  1850. if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
  1851. const toLoad = [];
  1852. const append = lng => {
  1853. if (!lng) return;
  1854. if (lng === 'cimode') return;
  1855. const lngs = this.services.languageUtils.toResolveHierarchy(lng);
  1856. lngs.forEach(l => {
  1857. if (l === 'cimode') return;
  1858. if (toLoad.indexOf(l) < 0) toLoad.push(l);
  1859. });
  1860. };
  1861. if (!usedLng) {
  1862. const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
  1863. fallbacks.forEach(l => append(l));
  1864. } else {
  1865. append(usedLng);
  1866. }
  1867. this.options.preload?.forEach?.(l => append(l));
  1868. this.services.backendConnector.load(toLoad, this.options.ns, e => {
  1869. if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
  1870. usedCallback(e);
  1871. });
  1872. } else {
  1873. usedCallback(null);
  1874. }
  1875. }
  1876. reloadResources(lngs, ns, callback) {
  1877. const deferred = defer();
  1878. if (typeof lngs === 'function') {
  1879. callback = lngs;
  1880. lngs = undefined;
  1881. }
  1882. if (typeof ns === 'function') {
  1883. callback = ns;
  1884. ns = undefined;
  1885. }
  1886. if (!lngs) lngs = this.languages;
  1887. if (!ns) ns = this.options.ns;
  1888. if (!callback) callback = noop;
  1889. this.services.backendConnector.reload(lngs, ns, err => {
  1890. deferred.resolve();
  1891. callback(err);
  1892. });
  1893. return deferred;
  1894. }
  1895. use(module) {
  1896. if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
  1897. if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
  1898. if (module.type === 'backend') {
  1899. this.modules.backend = module;
  1900. }
  1901. if (module.type === 'logger' || module.log && module.warn && module.error) {
  1902. this.modules.logger = module;
  1903. }
  1904. if (module.type === 'languageDetector') {
  1905. this.modules.languageDetector = module;
  1906. }
  1907. if (module.type === 'i18nFormat') {
  1908. this.modules.i18nFormat = module;
  1909. }
  1910. if (module.type === 'postProcessor') {
  1911. postProcessor.addPostProcessor(module);
  1912. }
  1913. if (module.type === 'formatter') {
  1914. this.modules.formatter = module;
  1915. }
  1916. if (module.type === '3rdParty') {
  1917. this.modules.external.push(module);
  1918. }
  1919. return this;
  1920. }
  1921. setResolvedLanguage(l) {
  1922. if (!l || !this.languages) return;
  1923. if (['cimode', 'dev'].indexOf(l) > -1) return;
  1924. for (let li = 0; li < this.languages.length; li++) {
  1925. const lngInLngs = this.languages[li];
  1926. if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
  1927. if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
  1928. this.resolvedLanguage = lngInLngs;
  1929. break;
  1930. }
  1931. }
  1932. if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
  1933. this.resolvedLanguage = l;
  1934. this.languages.unshift(l);
  1935. }
  1936. }
  1937. changeLanguage(lng, callback) {
  1938. this.isLanguageChangingTo = lng;
  1939. const deferred = defer();
  1940. this.emit('languageChanging', lng);
  1941. const setLngProps = l => {
  1942. this.language = l;
  1943. this.languages = this.services.languageUtils.toResolveHierarchy(l);
  1944. this.resolvedLanguage = undefined;
  1945. this.setResolvedLanguage(l);
  1946. };
  1947. const done = (err, l) => {
  1948. if (l) {
  1949. if (this.isLanguageChangingTo === lng) {
  1950. setLngProps(l);
  1951. this.translator.changeLanguage(l);
  1952. this.isLanguageChangingTo = undefined;
  1953. this.emit('languageChanged', l);
  1954. this.logger.log('languageChanged', l);
  1955. }
  1956. } else {
  1957. this.isLanguageChangingTo = undefined;
  1958. }
  1959. deferred.resolve((...args) => this.t(...args));
  1960. if (callback) callback(err, (...args) => this.t(...args));
  1961. };
  1962. const setLng = lngs => {
  1963. if (!lng && !lngs && this.services.languageDetector) lngs = [];
  1964. const fl = isString$1(lngs) ? lngs : lngs && lngs[0];
  1965. const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString$1(lngs) ? [lngs] : lngs);
  1966. if (l) {
  1967. if (!this.language) {
  1968. setLngProps(l);
  1969. }
  1970. if (!this.translator.language) this.translator.changeLanguage(l);
  1971. this.services.languageDetector?.cacheUserLanguage?.(l);
  1972. }
  1973. this.loadResources(l, err => {
  1974. done(err, l);
  1975. });
  1976. };
  1977. if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
  1978. setLng(this.services.languageDetector.detect());
  1979. } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
  1980. if (this.services.languageDetector.detect.length === 0) {
  1981. this.services.languageDetector.detect().then(setLng);
  1982. } else {
  1983. this.services.languageDetector.detect(setLng);
  1984. }
  1985. } else {
  1986. setLng(lng);
  1987. }
  1988. return deferred;
  1989. }
  1990. getFixedT(lng, ns, keyPrefix) {
  1991. const fixedT = (key, opts, ...rest) => {
  1992. let o;
  1993. if (typeof opts !== 'object') {
  1994. o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
  1995. } else {
  1996. o = {
  1997. ...opts
  1998. };
  1999. }
  2000. o.lng = o.lng || fixedT.lng;
  2001. o.lngs = o.lngs || fixedT.lngs;
  2002. o.ns = o.ns || fixedT.ns;
  2003. if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
  2004. const keySeparator = this.options.keySeparator || '.';
  2005. let resultKey;
  2006. if (o.keyPrefix && Array.isArray(key)) {
  2007. resultKey = key.map(k => {
  2008. if (typeof k === 'function') k = keysFromSelector(k, {
  2009. ...this.options,
  2010. ...opts
  2011. });
  2012. return `${o.keyPrefix}${keySeparator}${k}`;
  2013. });
  2014. } else {
  2015. if (typeof key === 'function') key = keysFromSelector(key, {
  2016. ...this.options,
  2017. ...opts
  2018. });
  2019. resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
  2020. }
  2021. return this.t(resultKey, o);
  2022. };
  2023. if (isString$1(lng)) {
  2024. fixedT.lng = lng;
  2025. } else {
  2026. fixedT.lngs = lng;
  2027. }
  2028. fixedT.ns = ns;
  2029. fixedT.keyPrefix = keyPrefix;
  2030. return fixedT;
  2031. }
  2032. t(...args) {
  2033. return this.translator?.translate(...args);
  2034. }
  2035. exists(...args) {
  2036. return this.translator?.exists(...args);
  2037. }
  2038. setDefaultNamespace(ns) {
  2039. this.options.defaultNS = ns;
  2040. }
  2041. hasLoadedNamespace(ns, options = {}) {
  2042. if (!this.isInitialized) {
  2043. this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
  2044. return false;
  2045. }
  2046. if (!this.languages || !this.languages.length) {
  2047. this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
  2048. return false;
  2049. }
  2050. const lng = options.lng || this.resolvedLanguage || this.languages[0];
  2051. const fallbackLng = this.options ? this.options.fallbackLng : false;
  2052. const lastLng = this.languages[this.languages.length - 1];
  2053. if (lng.toLowerCase() === 'cimode') return true;
  2054. const loadNotPending = (l, n) => {
  2055. const loadState = this.services.backendConnector.state[`${l}|${n}`];
  2056. return loadState === -1 || loadState === 0 || loadState === 2;
  2057. };
  2058. if (options.precheck) {
  2059. const preResult = options.precheck(this, loadNotPending);
  2060. if (preResult !== undefined) return preResult;
  2061. }
  2062. if (this.hasResourceBundle(lng, ns)) return true;
  2063. if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
  2064. if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
  2065. return false;
  2066. }
  2067. loadNamespaces(ns, callback) {
  2068. const deferred = defer();
  2069. if (!this.options.ns) {
  2070. if (callback) callback();
  2071. return Promise.resolve();
  2072. }
  2073. if (isString$1(ns)) ns = [ns];
  2074. ns.forEach(n => {
  2075. if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
  2076. });
  2077. this.loadResources(err => {
  2078. deferred.resolve();
  2079. if (callback) callback(err);
  2080. });
  2081. return deferred;
  2082. }
  2083. loadLanguages(lngs, callback) {
  2084. const deferred = defer();
  2085. if (isString$1(lngs)) lngs = [lngs];
  2086. const preloaded = this.options.preload || [];
  2087. const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
  2088. if (!newLngs.length) {
  2089. if (callback) callback();
  2090. return Promise.resolve();
  2091. }
  2092. this.options.preload = preloaded.concat(newLngs);
  2093. this.loadResources(err => {
  2094. deferred.resolve();
  2095. if (callback) callback(err);
  2096. });
  2097. return deferred;
  2098. }
  2099. dir(lng) {
  2100. if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
  2101. if (!lng) return 'rtl';
  2102. try {
  2103. const l = new Intl.Locale(lng);
  2104. if (l && l.getTextInfo) {
  2105. const ti = l.getTextInfo();
  2106. if (ti && ti.direction) return ti.direction;
  2107. }
  2108. } catch (e) {}
  2109. 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'];
  2110. const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
  2111. if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
  2112. return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
  2113. }
  2114. static createInstance(options = {}, callback) {
  2115. const instance = new I18n(options, callback);
  2116. instance.createInstance = I18n.createInstance;
  2117. return instance;
  2118. }
  2119. cloneInstance(options = {}, callback = noop) {
  2120. const forkResourceStore = options.forkResourceStore;
  2121. if (forkResourceStore) delete options.forkResourceStore;
  2122. const mergedOptions = {
  2123. ...this.options,
  2124. ...options,
  2125. ...{
  2126. isClone: true
  2127. }
  2128. };
  2129. const clone = new I18n(mergedOptions);
  2130. if (options.debug !== undefined || options.prefix !== undefined) {
  2131. clone.logger = clone.logger.clone(options);
  2132. }
  2133. const membersToCopy = ['store', 'services', 'language'];
  2134. membersToCopy.forEach(m => {
  2135. clone[m] = this[m];
  2136. });
  2137. clone.services = {
  2138. ...this.services
  2139. };
  2140. clone.services.utils = {
  2141. hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
  2142. };
  2143. if (forkResourceStore) {
  2144. const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
  2145. prev[l] = {
  2146. ...this.store.data[l]
  2147. };
  2148. prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
  2149. acc[n] = {
  2150. ...prev[l][n]
  2151. };
  2152. return acc;
  2153. }, prev[l]);
  2154. return prev;
  2155. }, {});
  2156. clone.store = new ResourceStore(clonedData, mergedOptions);
  2157. clone.services.resourceStore = clone.store;
  2158. }
  2159. clone.translator = new Translator(clone.services, mergedOptions);
  2160. clone.translator.on('*', (event, ...args) => {
  2161. clone.emit(event, ...args);
  2162. });
  2163. clone.init(mergedOptions, callback);
  2164. clone.translator.options = mergedOptions;
  2165. clone.translator.backendConnector.services.utils = {
  2166. hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
  2167. };
  2168. return clone;
  2169. }
  2170. toJSON() {
  2171. return {
  2172. options: this.options,
  2173. store: this.store,
  2174. language: this.language,
  2175. languages: this.languages,
  2176. resolvedLanguage: this.resolvedLanguage
  2177. };
  2178. }
  2179. }
  2180. const instance = I18n.createInstance();
  2181. instance.createInstance;
  2182. instance.dir;
  2183. instance.init;
  2184. instance.loadResources;
  2185. instance.reloadResources;
  2186. instance.use;
  2187. instance.changeLanguage;
  2188. instance.getFixedT;
  2189. instance.t;
  2190. instance.exists;
  2191. instance.setDefaultNamespace;
  2192. instance.hasLoadedNamespace;
  2193. instance.loadNamespaces;
  2194. instance.loadLanguages;
  2195. function getDefaultExportFromCjs (x) {
  2196. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2197. }
  2198. var voidElements = {
  2199. "area": true,
  2200. "base": true,
  2201. "br": true,
  2202. "col": true,
  2203. "embed": true,
  2204. "hr": true,
  2205. "img": true,
  2206. "input": true,
  2207. "link": true,
  2208. "meta": true,
  2209. "param": true,
  2210. "source": true,
  2211. "track": true,
  2212. "wbr": true
  2213. };
  2214. var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
  2215. var t = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
  2216. function n(n) {
  2217. var r = {
  2218. type: "tag",
  2219. name: "",
  2220. voidElement: false,
  2221. attrs: {},
  2222. children: []
  2223. },
  2224. i = n.match(/<\/?([^\s]+?)[/\s>]/);
  2225. if (i && (r.name = i[1], (e[i[1]] || "/" === n.charAt(n.length - 2)) && (r.voidElement = true), r.name.startsWith("!--"))) {
  2226. var s = n.indexOf("--\x3e");
  2227. return {
  2228. type: "comment",
  2229. comment: -1 !== s ? n.slice(4, s) : ""
  2230. };
  2231. }
  2232. for (var a = new RegExp(t), c = null; null !== (c = a.exec(n));) if (c[0].trim()) if (c[1]) {
  2233. var o = c[1].trim(),
  2234. l = [o, ""];
  2235. o.indexOf("=") > -1 && (l = o.split("=")), r.attrs[l[0]] = l[1], a.lastIndex--;
  2236. } else c[2] && (r.attrs[c[2]] = c[3].trim().substring(1, c[3].length - 1));
  2237. return r;
  2238. }
  2239. var r = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,
  2240. i = /^\s*$/,
  2241. s = Object.create(null);
  2242. function a(e, t) {
  2243. switch (t.type) {
  2244. case "text":
  2245. return e + t.content;
  2246. case "tag":
  2247. return e += "<" + t.name + (t.attrs ? function (e) {
  2248. var t = [];
  2249. for (var n in e) t.push(n + '="' + e[n] + '"');
  2250. return t.length ? " " + t.join(" ") : "";
  2251. }(t.attrs) : "") + (t.voidElement ? "/>" : ">"), t.voidElement ? e : e + t.children.reduce(a, "") + "</" + t.name + ">";
  2252. case "comment":
  2253. return e + "\x3c!--" + t.comment + "--\x3e";
  2254. }
  2255. }
  2256. var c = {
  2257. parse: function (e, t) {
  2258. t || (t = {}), t.components || (t.components = s);
  2259. var a,
  2260. c = [],
  2261. o = [],
  2262. l = -1,
  2263. m = false;
  2264. if (0 !== e.indexOf("<")) {
  2265. var u = e.indexOf("<");
  2266. c.push({
  2267. type: "text",
  2268. content: -1 === u ? e : e.substring(0, u)
  2269. });
  2270. }
  2271. return e.replace(r, function (r, s) {
  2272. if (m) {
  2273. if (r !== "</" + a.name + ">") return;
  2274. m = false;
  2275. }
  2276. var u,
  2277. f = "/" !== r.charAt(1),
  2278. h = r.startsWith("\x3c!--"),
  2279. p = s + r.length,
  2280. d = e.charAt(p);
  2281. if (h) {
  2282. var v = n(r);
  2283. return l < 0 ? (c.push(v), c) : ((u = o[l]).children.push(v), c);
  2284. }
  2285. if (f && (l++, "tag" === (a = n(r)).type && t.components[a.name] && (a.type = "component", m = true), a.voidElement || m || !d || "<" === d || a.children.push({
  2286. type: "text",
  2287. content: e.slice(p, e.indexOf("<", p))
  2288. }), 0 === l && c.push(a), (u = o[l - 1]) && u.children.push(a), o[l] = a), (!f || a.voidElement) && (l > -1 && (a.voidElement || a.name === r.slice(2, -1)) && (l--, a = -1 === l ? c : o[l]), !m && "<" !== d && d)) {
  2289. u = -1 === l ? c : o[l].children;
  2290. var x = e.indexOf("<", p),
  2291. g = e.slice(p, -1 === x ? void 0 : x);
  2292. i.test(g) && (g = " "), (x > -1 && l + u.length >= 0 || " " !== g) && u.push({
  2293. type: "text",
  2294. content: g
  2295. });
  2296. }
  2297. }), c;
  2298. },
  2299. stringify: function (e) {
  2300. return e.reduce(function (e, t) {
  2301. return e + a("", t);
  2302. }, "");
  2303. }
  2304. };
  2305. const warn = (i18n, code, msg, rest) => {
  2306. const args = [msg, {
  2307. code,
  2308. ...(rest || {})
  2309. }];
  2310. if (i18n?.services?.logger?.forward) {
  2311. return i18n.services.logger.forward(args, 'warn', 'react-i18next::', true);
  2312. }
  2313. if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;
  2314. if (i18n?.services?.logger?.warn) {
  2315. i18n.services.logger.warn(...args);
  2316. } else if (console?.warn) {
  2317. console.warn(...args);
  2318. }
  2319. };
  2320. const alreadyWarned = {};
  2321. const warnOnce = (i18n, code, msg, rest) => {
  2322. if (isString(msg) && alreadyWarned[msg]) return;
  2323. if (isString(msg)) alreadyWarned[msg] = new Date();
  2324. warn(i18n, code, msg, rest);
  2325. };
  2326. const loadedClb = (i18n, cb) => () => {
  2327. if (i18n.isInitialized) {
  2328. cb();
  2329. } else {
  2330. const initialized = () => {
  2331. setTimeout(() => {
  2332. i18n.off('initialized', initialized);
  2333. }, 0);
  2334. cb();
  2335. };
  2336. i18n.on('initialized', initialized);
  2337. }
  2338. };
  2339. const loadNamespaces = (i18n, ns, cb) => {
  2340. i18n.loadNamespaces(ns, loadedClb(i18n, cb));
  2341. };
  2342. const loadLanguages = (i18n, lng, ns, cb) => {
  2343. if (isString(ns)) ns = [ns];
  2344. if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb);
  2345. ns.forEach(n => {
  2346. if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
  2347. });
  2348. i18n.loadLanguages(lng, loadedClb(i18n, cb));
  2349. };
  2350. const hasLoadedNamespace = (ns, i18n, options = {}) => {
  2351. if (!i18n.languages || !i18n.languages.length) {
  2352. warnOnce(i18n, 'NO_LANGUAGES', 'i18n.languages were undefined or empty', {
  2353. languages: i18n.languages
  2354. });
  2355. return true;
  2356. }
  2357. return i18n.hasLoadedNamespace(ns, {
  2358. lng: options.lng,
  2359. precheck: (i18nInstance, loadNotPending) => {
  2360. if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
  2361. }
  2362. });
  2363. };
  2364. const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');
  2365. const isString = obj => typeof obj === 'string';
  2366. const isObject = obj => typeof obj === 'object' && obj !== null;
  2367. const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
  2368. const htmlEntities = {
  2369. '&amp;': '&',
  2370. '&#38;': '&',
  2371. '&lt;': '<',
  2372. '&#60;': '<',
  2373. '&gt;': '>',
  2374. '&#62;': '>',
  2375. '&apos;': "'",
  2376. '&#39;': "'",
  2377. '&quot;': '"',
  2378. '&#34;': '"',
  2379. '&nbsp;': ' ',
  2380. '&#160;': ' ',
  2381. '&copy;': '©',
  2382. '&#169;': '©',
  2383. '&reg;': '®',
  2384. '&#174;': '®',
  2385. '&hellip;': '…',
  2386. '&#8230;': '…',
  2387. '&#x2F;': '/',
  2388. '&#47;': '/'
  2389. };
  2390. const unescapeHtmlEntity = m => htmlEntities[m];
  2391. const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
  2392. let defaultOptions = {
  2393. bindI18n: 'languageChanged',
  2394. bindI18nStore: '',
  2395. transEmptyNodeValue: '',
  2396. transSupportBasicHtmlNodes: true,
  2397. transWrapTextNodes: '',
  2398. transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
  2399. useSuspense: true,
  2400. unescape
  2401. };
  2402. const setDefaults = (options = {}) => {
  2403. defaultOptions = {
  2404. ...defaultOptions,
  2405. ...options
  2406. };
  2407. };
  2408. const getDefaults = () => defaultOptions;
  2409. let i18nInstance;
  2410. const setI18n = instance => {
  2411. i18nInstance = instance;
  2412. };
  2413. const getI18n = () => i18nInstance;
  2414. const hasChildren = (node, checkLength) => {
  2415. if (!node) return false;
  2416. const base = node.props?.children ?? node.children;
  2417. if (checkLength) return base.length > 0;
  2418. return !!base;
  2419. };
  2420. const getChildren = node => {
  2421. if (!node) return [];
  2422. const children = node.props?.children ?? node.children;
  2423. return node.props?.i18nIsDynamicList ? getAsArray(children) : children;
  2424. };
  2425. const hasValidReactChildren = children => Array.isArray(children) && children.every(React.isValidElement);
  2426. const getAsArray = data => Array.isArray(data) ? data : [data];
  2427. const mergeProps = (source, target) => {
  2428. const newTarget = {
  2429. ...target
  2430. };
  2431. newTarget.props = Object.assign(source.props, target.props);
  2432. return newTarget;
  2433. };
  2434. const nodesToString = (children, i18nOptions, i18n, i18nKey) => {
  2435. if (!children) return '';
  2436. let stringNode = '';
  2437. const childrenArray = getAsArray(children);
  2438. const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];
  2439. childrenArray.forEach((child, childIndex) => {
  2440. if (isString(child)) {
  2441. stringNode += `${child}`;
  2442. return;
  2443. }
  2444. if (React.isValidElement(child)) {
  2445. const {
  2446. props,
  2447. type
  2448. } = child;
  2449. const childPropsCount = Object.keys(props).length;
  2450. const shouldKeepChild = keepArray.indexOf(type) > -1;
  2451. const childChildren = props.children;
  2452. if (!childChildren && shouldKeepChild && !childPropsCount) {
  2453. stringNode += `<${type}/>`;
  2454. return;
  2455. }
  2456. if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {
  2457. stringNode += `<${childIndex}></${childIndex}>`;
  2458. return;
  2459. }
  2460. if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {
  2461. stringNode += `<${type}>${childChildren}</${type}>`;
  2462. return;
  2463. }
  2464. const content = nodesToString(childChildren, i18nOptions, i18n, i18nKey);
  2465. stringNode += `<${childIndex}>${content}</${childIndex}>`;
  2466. return;
  2467. }
  2468. if (child === null) {
  2469. warn(i18n, 'TRANS_NULL_VALUE', `Passed in a null value as child`, {
  2470. i18nKey
  2471. });
  2472. return;
  2473. }
  2474. if (isObject(child)) {
  2475. const {
  2476. format,
  2477. ...clone
  2478. } = child;
  2479. const keys = Object.keys(clone);
  2480. if (keys.length === 1) {
  2481. const value = format ? `${keys[0]}, ${format}` : keys[0];
  2482. stringNode += `{{${value}}}`;
  2483. return;
  2484. }
  2485. warn(i18n, 'TRANS_INVALID_OBJ', `Invalid child - Object should only have keys {{ value, format }} (format is optional).`, {
  2486. i18nKey,
  2487. child
  2488. });
  2489. return;
  2490. }
  2491. warn(i18n, 'TRANS_INVALID_VAR', `Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.`, {
  2492. i18nKey,
  2493. child
  2494. });
  2495. });
  2496. return stringNode;
  2497. };
  2498. const escapeLiteralLessThan = (str, keepArray = [], knownComponentsMap = {}) => {
  2499. if (!str) return str;
  2500. const knownNames = Object.keys(knownComponentsMap);
  2501. const allValidNames = [...keepArray, ...knownNames];
  2502. let result = '';
  2503. let i = 0;
  2504. while (i < str.length) {
  2505. if (str[i] === '<') {
  2506. let isValidTag = false;
  2507. const closingMatch = str.slice(i).match(/^<\/(\d+|[a-zA-Z][a-zA-Z0-9-]*)>/);
  2508. if (closingMatch) {
  2509. const tagName = closingMatch[1];
  2510. if (/^\d+$/.test(tagName) || allValidNames.includes(tagName)) {
  2511. isValidTag = true;
  2512. result += closingMatch[0];
  2513. i += closingMatch[0].length;
  2514. }
  2515. }
  2516. if (!isValidTag) {
  2517. const openingMatch = str.slice(i).match(/^<(\d+|[a-zA-Z][a-zA-Z0-9-]*)(\s+[\w-]+(?:=(?:"[^"]*"|'[^']*'|[^\s>]+))?)*\s*(\/)?>/);
  2518. if (openingMatch) {
  2519. const tagName = openingMatch[1];
  2520. if (/^\d+$/.test(tagName) || allValidNames.includes(tagName)) {
  2521. isValidTag = true;
  2522. result += openingMatch[0];
  2523. i += openingMatch[0].length;
  2524. }
  2525. }
  2526. }
  2527. if (!isValidTag) {
  2528. result += '&lt;';
  2529. i += 1;
  2530. }
  2531. } else {
  2532. result += str[i];
  2533. i += 1;
  2534. }
  2535. }
  2536. return result;
  2537. };
  2538. const renderNodes = (children, knownComponentsMap, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {
  2539. if (targetString === '') return [];
  2540. const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  2541. const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);
  2542. if (!children && !knownComponentsMap && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];
  2543. const data = knownComponentsMap ?? {};
  2544. const getData = childs => {
  2545. const childrenArray = getAsArray(childs);
  2546. childrenArray.forEach(child => {
  2547. if (isString(child)) return;
  2548. if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !React.isValidElement(child)) Object.assign(data, child);
  2549. });
  2550. };
  2551. getData(children);
  2552. const escapedString = escapeLiteralLessThan(targetString, keepArray, data);
  2553. const ast = c.parse(`<0>${escapedString}</0>`);
  2554. const opts = {
  2555. ...data,
  2556. ...combinedTOpts
  2557. };
  2558. const renderInner = (child, node, rootReactNode) => {
  2559. const childs = getChildren(child);
  2560. const mappedChildren = mapAST(childs, node.children, rootReactNode);
  2561. return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;
  2562. };
  2563. const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {
  2564. if (child.dummy) {
  2565. child.children = inner;
  2566. mem.push(React.cloneElement(child, {
  2567. key: i
  2568. }, isVoid ? undefined : inner));
  2569. } else {
  2570. mem.push(...React.Children.map([child], c => {
  2571. const INTERNAL_DYNAMIC_MARKER = 'data-i18n-is-dynamic-list';
  2572. const override = {
  2573. key: i,
  2574. [INTERNAL_DYNAMIC_MARKER]: undefined
  2575. };
  2576. if (c && c.props) {
  2577. Object.keys(c.props).forEach(k => {
  2578. if (k === 'ref' || k === 'children' || k === 'i18nIsDynamicList' || k === INTERNAL_DYNAMIC_MARKER) return;
  2579. override[k] = c.props[k];
  2580. });
  2581. }
  2582. return React.cloneElement(c, override, isVoid ? null : inner);
  2583. }));
  2584. }
  2585. };
  2586. const mapAST = (reactNode, astNode, rootReactNode) => {
  2587. const reactNodes = getAsArray(reactNode);
  2588. const astNodes = getAsArray(astNode);
  2589. return astNodes.reduce((mem, node, i) => {
  2590. const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
  2591. if (node.type === 'tag') {
  2592. let tmp = reactNodes[parseInt(node.name, 10)];
  2593. if (!tmp && knownComponentsMap) tmp = knownComponentsMap[node.name];
  2594. if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];
  2595. if (!tmp) tmp = {};
  2596. const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
  2597. props: node.attrs
  2598. }, tmp) : tmp;
  2599. const isElement = React.isValidElement(child);
  2600. const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
  2601. const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;
  2602. const isKnownComponent = isObject(knownComponentsMap) && Object.hasOwnProperty.call(knownComponentsMap, node.name);
  2603. if (isString(child)) {
  2604. const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
  2605. mem.push(value);
  2606. } else if (hasChildren(child) || isValidTranslationWithChildren) {
  2607. const inner = renderInner(child, node, rootReactNode);
  2608. pushTranslatedJSX(child, inner, mem, i);
  2609. } else if (isEmptyTransWithHTML) {
  2610. const inner = mapAST(reactNodes, node.children, rootReactNode);
  2611. pushTranslatedJSX(child, inner, mem, i);
  2612. } else if (Number.isNaN(parseFloat(node.name))) {
  2613. if (isKnownComponent) {
  2614. const inner = renderInner(child, node, rootReactNode);
  2615. pushTranslatedJSX(child, inner, mem, i, node.voidElement);
  2616. } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
  2617. if (node.voidElement) {
  2618. mem.push(React.createElement(node.name, {
  2619. key: `${node.name}-${i}`
  2620. }));
  2621. } else {
  2622. const inner = mapAST(reactNodes, node.children, rootReactNode);
  2623. mem.push(React.createElement(node.name, {
  2624. key: `${node.name}-${i}`
  2625. }, inner));
  2626. }
  2627. } else if (node.voidElement) {
  2628. mem.push(`<${node.name} />`);
  2629. } else {
  2630. const inner = mapAST(reactNodes, node.children, rootReactNode);
  2631. mem.push(`<${node.name}>${inner}</${node.name}>`);
  2632. }
  2633. } else if (isObject(child) && !isElement) {
  2634. const content = node.children[0] ? translationContent : null;
  2635. if (content) mem.push(content);
  2636. } else {
  2637. pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);
  2638. }
  2639. } else if (node.type === 'text') {
  2640. const wrapTextNodes = i18nOptions.transWrapTextNodes;
  2641. const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
  2642. if (wrapTextNodes) {
  2643. mem.push(React.createElement(wrapTextNodes, {
  2644. key: `${node.name}-${i}`
  2645. }, content));
  2646. } else {
  2647. mem.push(content);
  2648. }
  2649. }
  2650. return mem;
  2651. }, []);
  2652. };
  2653. const result = mapAST([{
  2654. dummy: true,
  2655. children: children || []
  2656. }], ast, getAsArray(children || []));
  2657. return getChildren(result[0]);
  2658. };
  2659. const fixComponentProps = (component, index, translation) => {
  2660. const componentKey = component.key || index;
  2661. const comp = React.cloneElement(component, {
  2662. key: componentKey
  2663. });
  2664. if (!comp.props || !comp.props.children || translation.indexOf(`${index}/>`) < 0 && translation.indexOf(`${index} />`) < 0) {
  2665. return comp;
  2666. }
  2667. function Componentized() {
  2668. return React.createElement(React.Fragment, null, comp);
  2669. }
  2670. return React.createElement(Componentized, {
  2671. key: componentKey
  2672. });
  2673. };
  2674. const generateArrayComponents = (components, translation) => components.map((c, index) => fixComponentProps(c, index, translation));
  2675. const generateObjectComponents = (components, translation) => {
  2676. const componentMap = {};
  2677. Object.keys(components).forEach(c => {
  2678. Object.assign(componentMap, {
  2679. [c]: fixComponentProps(components[c], c, translation)
  2680. });
  2681. });
  2682. return componentMap;
  2683. };
  2684. const generateComponents = (components, translation, i18n, i18nKey) => {
  2685. if (!components) return null;
  2686. if (Array.isArray(components)) {
  2687. return generateArrayComponents(components, translation);
  2688. }
  2689. if (isObject(components)) {
  2690. return generateObjectComponents(components, translation);
  2691. }
  2692. warnOnce(i18n, 'TRANS_INVALID_COMPONENTS', `<Trans /> "components" prop expects an object or array`, {
  2693. i18nKey
  2694. });
  2695. return null;
  2696. };
  2697. const isComponentsMap = object => {
  2698. if (!isObject(object)) return false;
  2699. if (Array.isArray(object)) return false;
  2700. return Object.keys(object).reduce((acc, key) => acc && Number.isNaN(Number.parseFloat(key)), true);
  2701. };
  2702. function Trans$1({
  2703. children,
  2704. count,
  2705. parent,
  2706. i18nKey,
  2707. context,
  2708. tOptions = {},
  2709. values,
  2710. defaults,
  2711. components,
  2712. ns,
  2713. i18n: i18nFromProps,
  2714. t: tFromProps,
  2715. shouldUnescape,
  2716. ...additionalProps
  2717. }) {
  2718. const i18n = i18nFromProps || getI18n();
  2719. if (!i18n) {
  2720. warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `Trans: You need to pass in an i18next instance using i18nextReactModule`, {
  2721. i18nKey
  2722. });
  2723. return children;
  2724. }
  2725. const t = tFromProps || i18n.t.bind(i18n) || (k => k);
  2726. const reactI18nextOptions = {
  2727. ...getDefaults(),
  2728. ...i18n.options?.react
  2729. };
  2730. let namespaces = ns || t.ns || i18n.options?.defaultNS;
  2731. namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
  2732. const nodeAsString = nodesToString(children, reactI18nextOptions, i18n, i18nKey);
  2733. const defaultValue = defaults || tOptions?.defaultValue || nodeAsString || reactI18nextOptions.transEmptyNodeValue || (typeof i18nKey === 'function' ? keysFromSelector(i18nKey) : i18nKey);
  2734. const {
  2735. hashTransKey
  2736. } = reactI18nextOptions;
  2737. const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);
  2738. if (i18n.options?.interpolation?.defaultVariables) {
  2739. values = values && Object.keys(values).length > 0 ? {
  2740. ...values,
  2741. ...i18n.options.interpolation.defaultVariables
  2742. } : {
  2743. ...i18n.options.interpolation.defaultVariables
  2744. };
  2745. }
  2746. const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {
  2747. interpolation: {
  2748. ...tOptions.interpolation,
  2749. prefix: '#$?',
  2750. suffix: '?$#'
  2751. }
  2752. };
  2753. const combinedTOpts = {
  2754. ...tOptions,
  2755. context: context || tOptions.context,
  2756. count,
  2757. ...values,
  2758. ...interpolationOverride,
  2759. defaultValue,
  2760. ns: namespaces
  2761. };
  2762. let translation = key ? t(key, combinedTOpts) : defaultValue;
  2763. if (translation === key && defaultValue) translation = defaultValue;
  2764. const generatedComponents = generateComponents(components, translation, i18n, i18nKey);
  2765. let indexedChildren = generatedComponents || children;
  2766. let componentsMap = null;
  2767. if (isComponentsMap(generatedComponents)) {
  2768. componentsMap = generatedComponents;
  2769. indexedChildren = children;
  2770. }
  2771. const content = renderNodes(indexedChildren, componentsMap, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
  2772. const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;
  2773. return useAsParent ? React.createElement(useAsParent, additionalProps, content) : content;
  2774. }
  2775. const initReactI18next = {
  2776. type: '3rdParty',
  2777. init(instance) {
  2778. setDefaults(instance.options.react);
  2779. setI18n(instance);
  2780. }
  2781. };
  2782. const I18nContext = React.createContext();
  2783. class ReportNamespaces {
  2784. constructor() {
  2785. this.usedNamespaces = {};
  2786. }
  2787. addUsedNamespaces(namespaces) {
  2788. namespaces.forEach(ns => {
  2789. if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
  2790. });
  2791. }
  2792. getUsedNamespaces() {
  2793. return Object.keys(this.usedNamespaces);
  2794. }
  2795. }
  2796. const composeInitialProps = ForComponent => async ctx => {
  2797. const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};
  2798. const i18nInitialProps = getInitialProps();
  2799. return {
  2800. ...componentsInitialProps,
  2801. ...i18nInitialProps
  2802. };
  2803. };
  2804. const getInitialProps = () => {
  2805. const i18n = getI18n();
  2806. const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];
  2807. const ret = {};
  2808. const initialI18nStore = {};
  2809. i18n.languages.forEach(l => {
  2810. initialI18nStore[l] = {};
  2811. namespaces.forEach(ns => {
  2812. initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};
  2813. });
  2814. });
  2815. ret.initialI18nStore = initialI18nStore;
  2816. ret.initialLanguage = i18n.language;
  2817. return ret;
  2818. };
  2819. function Trans({
  2820. children,
  2821. count,
  2822. parent,
  2823. i18nKey,
  2824. context,
  2825. tOptions = {},
  2826. values,
  2827. defaults,
  2828. components,
  2829. ns,
  2830. i18n: i18nFromProps,
  2831. t: tFromProps,
  2832. shouldUnescape,
  2833. ...additionalProps
  2834. }) {
  2835. const {
  2836. i18n: i18nFromContext,
  2837. defaultNS: defaultNSFromContext
  2838. } = React.useContext(I18nContext) || {};
  2839. const i18n = i18nFromProps || i18nFromContext || getI18n();
  2840. const t = tFromProps || i18n?.t.bind(i18n);
  2841. return Trans$1({
  2842. children,
  2843. count,
  2844. parent,
  2845. i18nKey,
  2846. context,
  2847. tOptions,
  2848. values,
  2849. defaults,
  2850. components,
  2851. ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,
  2852. i18n,
  2853. t: tFromProps,
  2854. shouldUnescape,
  2855. ...additionalProps
  2856. });
  2857. }
  2858. class TranslationParserError extends Error {
  2859. constructor(message, position, translationString) {
  2860. super(message);
  2861. this.name = 'TranslationParserError';
  2862. this.position = position;
  2863. this.translationString = translationString;
  2864. if (Error.captureStackTrace) {
  2865. Error.captureStackTrace(this, TranslationParserError);
  2866. }
  2867. }
  2868. }
  2869. const commonEntities = {
  2870. '&nbsp;': '\u00A0',
  2871. '&amp;': '&',
  2872. '&lt;': '<',
  2873. '&gt;': '>',
  2874. '&quot;': '"',
  2875. '&apos;': "'",
  2876. '&copy;': '©',
  2877. '&reg;': '®',
  2878. '&trade;': '™',
  2879. '&hellip;': '…',
  2880. '&ndash;': '–',
  2881. '&mdash;': '—',
  2882. '&lsquo;': '\u2018',
  2883. '&rsquo;': '\u2019',
  2884. '&sbquo;': '\u201A',
  2885. '&ldquo;': '\u201C',
  2886. '&rdquo;': '\u201D',
  2887. '&bdquo;': '\u201E',
  2888. '&dagger;': '†',
  2889. '&Dagger;': '‡',
  2890. '&bull;': '•',
  2891. '&prime;': '′',
  2892. '&Prime;': '″',
  2893. '&lsaquo;': '‹',
  2894. '&rsaquo;': '›',
  2895. '&sect;': '§',
  2896. '&para;': '¶',
  2897. '&middot;': '·',
  2898. '&ensp;': '\u2002',
  2899. '&emsp;': '\u2003',
  2900. '&thinsp;': '\u2009',
  2901. '&euro;': '€',
  2902. '&pound;': '£',
  2903. '&yen;': '¥',
  2904. '&cent;': '¢',
  2905. '&curren;': '¤',
  2906. '&times;': '×',
  2907. '&divide;': '÷',
  2908. '&minus;': '−',
  2909. '&plusmn;': '±',
  2910. '&ne;': '≠',
  2911. '&le;': '≤',
  2912. '&ge;': '≥',
  2913. '&asymp;': '≈',
  2914. '&equiv;': '≡',
  2915. '&infin;': '∞',
  2916. '&int;': '∫',
  2917. '&sum;': '∑',
  2918. '&prod;': '∏',
  2919. '&radic;': '√',
  2920. '&part;': '∂',
  2921. '&permil;': '‰',
  2922. '&deg;': '°',
  2923. '&micro;': 'µ',
  2924. '&larr;': '←',
  2925. '&uarr;': '↑',
  2926. '&rarr;': '→',
  2927. '&darr;': '↓',
  2928. '&harr;': '↔',
  2929. '&crarr;': '↵',
  2930. '&lArr;': '⇐',
  2931. '&uArr;': '⇑',
  2932. '&rArr;': '⇒',
  2933. '&dArr;': '⇓',
  2934. '&hArr;': '⇔',
  2935. '&alpha;': 'α',
  2936. '&beta;': 'β',
  2937. '&gamma;': 'γ',
  2938. '&delta;': 'δ',
  2939. '&epsilon;': 'ε',
  2940. '&zeta;': 'ζ',
  2941. '&eta;': 'η',
  2942. '&theta;': 'θ',
  2943. '&iota;': 'ι',
  2944. '&kappa;': 'κ',
  2945. '&lambda;': 'λ',
  2946. '&mu;': 'μ',
  2947. '&nu;': 'ν',
  2948. '&xi;': 'ξ',
  2949. '&omicron;': 'ο',
  2950. '&pi;': 'π',
  2951. '&rho;': 'ρ',
  2952. '&sigma;': 'σ',
  2953. '&tau;': 'τ',
  2954. '&upsilon;': 'υ',
  2955. '&phi;': 'φ',
  2956. '&chi;': 'χ',
  2957. '&psi;': 'ψ',
  2958. '&omega;': 'ω',
  2959. '&Alpha;': 'Α',
  2960. '&Beta;': 'Β',
  2961. '&Gamma;': 'Γ',
  2962. '&Delta;': 'Δ',
  2963. '&Epsilon;': 'Ε',
  2964. '&Zeta;': 'Ζ',
  2965. '&Eta;': 'Η',
  2966. '&Theta;': 'Θ',
  2967. '&Iota;': 'Ι',
  2968. '&Kappa;': 'Κ',
  2969. '&Lambda;': 'Λ',
  2970. '&Mu;': 'Μ',
  2971. '&Nu;': 'Ν',
  2972. '&Xi;': 'Ξ',
  2973. '&Omicron;': 'Ο',
  2974. '&Pi;': 'Π',
  2975. '&Rho;': 'Ρ',
  2976. '&Sigma;': 'Σ',
  2977. '&Tau;': 'Τ',
  2978. '&Upsilon;': 'Υ',
  2979. '&Phi;': 'Φ',
  2980. '&Chi;': 'Χ',
  2981. '&Psi;': 'Ψ',
  2982. '&Omega;': 'Ω',
  2983. '&Agrave;': 'À',
  2984. '&Aacute;': 'Á',
  2985. '&Acirc;': 'Â',
  2986. '&Atilde;': 'Ã',
  2987. '&Auml;': 'Ä',
  2988. '&Aring;': 'Å',
  2989. '&AElig;': 'Æ',
  2990. '&Ccedil;': 'Ç',
  2991. '&Egrave;': 'È',
  2992. '&Eacute;': 'É',
  2993. '&Ecirc;': 'Ê',
  2994. '&Euml;': 'Ë',
  2995. '&Igrave;': 'Ì',
  2996. '&Iacute;': 'Í',
  2997. '&Icirc;': 'Î',
  2998. '&Iuml;': 'Ï',
  2999. '&ETH;': 'Ð',
  3000. '&Ntilde;': 'Ñ',
  3001. '&Ograve;': 'Ò',
  3002. '&Oacute;': 'Ó',
  3003. '&Ocirc;': 'Ô',
  3004. '&Otilde;': 'Õ',
  3005. '&Ouml;': 'Ö',
  3006. '&Oslash;': 'Ø',
  3007. '&Ugrave;': 'Ù',
  3008. '&Uacute;': 'Ú',
  3009. '&Ucirc;': 'Û',
  3010. '&Uuml;': 'Ü',
  3011. '&Yacute;': 'Ý',
  3012. '&THORN;': 'Þ',
  3013. '&szlig;': 'ß',
  3014. '&agrave;': 'à',
  3015. '&aacute;': 'á',
  3016. '&acirc;': 'â',
  3017. '&atilde;': 'ã',
  3018. '&auml;': 'ä',
  3019. '&aring;': 'å',
  3020. '&aelig;': 'æ',
  3021. '&ccedil;': 'ç',
  3022. '&egrave;': 'è',
  3023. '&eacute;': 'é',
  3024. '&ecirc;': 'ê',
  3025. '&euml;': 'ë',
  3026. '&igrave;': 'ì',
  3027. '&iacute;': 'í',
  3028. '&icirc;': 'î',
  3029. '&iuml;': 'ï',
  3030. '&eth;': 'ð',
  3031. '&ntilde;': 'ñ',
  3032. '&ograve;': 'ò',
  3033. '&oacute;': 'ó',
  3034. '&ocirc;': 'ô',
  3035. '&otilde;': 'õ',
  3036. '&ouml;': 'ö',
  3037. '&oslash;': 'ø',
  3038. '&ugrave;': 'ù',
  3039. '&uacute;': 'ú',
  3040. '&ucirc;': 'û',
  3041. '&uuml;': 'ü',
  3042. '&yacute;': 'ý',
  3043. '&thorn;': 'þ',
  3044. '&yuml;': 'ÿ',
  3045. '&iexcl;': '¡',
  3046. '&iquest;': '¿',
  3047. '&fnof;': 'ƒ',
  3048. '&circ;': 'ˆ',
  3049. '&tilde;': '˜',
  3050. '&OElig;': 'Œ',
  3051. '&oelig;': 'œ',
  3052. '&Scaron;': 'Š',
  3053. '&scaron;': 'š',
  3054. '&Yuml;': 'Ÿ',
  3055. '&ordf;': 'ª',
  3056. '&ordm;': 'º',
  3057. '&macr;': '¯',
  3058. '&acute;': '´',
  3059. '&cedil;': '¸',
  3060. '&sup1;': '¹',
  3061. '&sup2;': '²',
  3062. '&sup3;': '³',
  3063. '&frac14;': '¼',
  3064. '&frac12;': '½',
  3065. '&frac34;': '¾',
  3066. '&spades;': '♠',
  3067. '&clubs;': '♣',
  3068. '&hearts;': '♥',
  3069. '&diams;': '♦',
  3070. '&loz;': '◊',
  3071. '&oline;': '‾',
  3072. '&frasl;': '⁄',
  3073. '&weierp;': '℘',
  3074. '&image;': 'ℑ',
  3075. '&real;': 'ℜ',
  3076. '&alefsym;': 'ℵ'
  3077. };
  3078. const entityPattern = new RegExp(Object.keys(commonEntities).map(entity => entity.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g');
  3079. const decodeHtmlEntities = text => text.replace(entityPattern, match => commonEntities[match]).replace(/&#(\d+);/g, (_, num) => String.fromCharCode(parseInt(num, 10))).replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  3080. const tokenize = translation => {
  3081. const tokens = [];
  3082. let position = 0;
  3083. let currentText = '';
  3084. const flushText = () => {
  3085. if (currentText) {
  3086. tokens.push({
  3087. type: 'Text',
  3088. value: currentText,
  3089. position: position - currentText.length
  3090. });
  3091. currentText = '';
  3092. }
  3093. };
  3094. while (position < translation.length) {
  3095. const char = translation[position];
  3096. if (char === '<') {
  3097. const tagMatch = translation.slice(position).match(/^<(\d+)>/);
  3098. if (tagMatch) {
  3099. flushText();
  3100. tokens.push({
  3101. type: 'TagOpen',
  3102. value: tagMatch[0],
  3103. position,
  3104. tagNumber: parseInt(tagMatch[1], 10)
  3105. });
  3106. position += tagMatch[0].length;
  3107. } else {
  3108. const closeTagMatch = translation.slice(position).match(/^<\/(\d+)>/);
  3109. if (closeTagMatch) {
  3110. flushText();
  3111. tokens.push({
  3112. type: 'TagClose',
  3113. value: closeTagMatch[0],
  3114. position,
  3115. tagNumber: parseInt(closeTagMatch[1], 10)
  3116. });
  3117. position += closeTagMatch[0].length;
  3118. } else {
  3119. currentText += char;
  3120. position += 1;
  3121. }
  3122. }
  3123. } else {
  3124. currentText += char;
  3125. position += 1;
  3126. }
  3127. }
  3128. flushText();
  3129. return tokens;
  3130. };
  3131. const renderDeclarationNode = (declaration, children, childDeclarations) => {
  3132. const {
  3133. type,
  3134. props = {}
  3135. } = declaration;
  3136. if (props.children && Array.isArray(props.children) && childDeclarations) {
  3137. const {
  3138. children: _childrenToRemove,
  3139. ...propsWithoutChildren
  3140. } = props;
  3141. return React.createElement(type, propsWithoutChildren, ...children);
  3142. }
  3143. if (children.length === 0) {
  3144. return React.createElement(type, props);
  3145. }
  3146. if (children.length === 1) {
  3147. return React.createElement(type, props, children[0]);
  3148. }
  3149. return React.createElement(type, props, ...children);
  3150. };
  3151. const renderTranslation = (translation, declarations = []) => {
  3152. if (!translation) {
  3153. return [];
  3154. }
  3155. const tokens = tokenize(translation);
  3156. const result = [];
  3157. const stack = [];
  3158. const literalTagNumbers = new Set();
  3159. const getCurrentDeclarations = () => {
  3160. if (stack.length === 0) {
  3161. return declarations;
  3162. }
  3163. const parentFrame = stack[stack.length - 1];
  3164. if (parentFrame.declaration.props?.children && Array.isArray(parentFrame.declaration.props.children)) {
  3165. return parentFrame.declaration.props.children;
  3166. }
  3167. return parentFrame.declarations;
  3168. };
  3169. tokens.forEach(token => {
  3170. switch (token.type) {
  3171. case 'Text':
  3172. {
  3173. const decoded = decodeHtmlEntities(token.value);
  3174. const targetArray = stack.length > 0 ? stack[stack.length - 1].children : result;
  3175. targetArray.push(decoded);
  3176. }
  3177. break;
  3178. case 'TagOpen':
  3179. {
  3180. const {
  3181. tagNumber
  3182. } = token;
  3183. const currentDeclarations = getCurrentDeclarations();
  3184. const declaration = currentDeclarations[tagNumber];
  3185. if (!declaration) {
  3186. literalTagNumbers.add(tagNumber);
  3187. const literalText = `<${tagNumber}>`;
  3188. const targetArray = stack.length > 0 ? stack[stack.length - 1].children : result;
  3189. targetArray.push(literalText);
  3190. break;
  3191. }
  3192. stack.push({
  3193. tagNumber,
  3194. children: [],
  3195. position: token.position,
  3196. declaration,
  3197. declarations: currentDeclarations
  3198. });
  3199. }
  3200. break;
  3201. case 'TagClose':
  3202. {
  3203. const {
  3204. tagNumber
  3205. } = token;
  3206. if (literalTagNumbers.has(tagNumber)) {
  3207. const literalText = `</${tagNumber}>`;
  3208. const literalTargetArray = stack.length > 0 ? stack[stack.length - 1].children : result;
  3209. literalTargetArray.push(literalText);
  3210. literalTagNumbers.delete(tagNumber);
  3211. break;
  3212. }
  3213. if (stack.length === 0) {
  3214. throw new TranslationParserError(`Unexpected closing tag </${tagNumber}> at position ${token.position}`, token.position, translation);
  3215. }
  3216. const frame = stack.pop();
  3217. if (frame.tagNumber !== tagNumber) {
  3218. throw new TranslationParserError(`Mismatched tags: expected </${frame.tagNumber}> but got </${tagNumber}> at position ${token.position}`, token.position, translation);
  3219. }
  3220. const element = renderDeclarationNode(frame.declaration, frame.children, frame.declarations);
  3221. const elementTargetArray = stack.length > 0 ? stack[stack.length - 1].children : result;
  3222. elementTargetArray.push(element);
  3223. }
  3224. break;
  3225. }
  3226. });
  3227. if (stack.length > 0) {
  3228. const unclosed = stack[stack.length - 1];
  3229. throw new TranslationParserError(`Unclosed tag <${unclosed.tagNumber}> at position ${unclosed.position}`, unclosed.position, translation);
  3230. }
  3231. return result;
  3232. };
  3233. function IcuTransWithoutContext({
  3234. i18nKey,
  3235. defaultTranslation,
  3236. content,
  3237. ns,
  3238. values = {},
  3239. i18n: i18nFromProps,
  3240. t: tFromProps
  3241. }) {
  3242. const i18n = i18nFromProps || getI18n();
  3243. if (!i18n) {
  3244. warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `IcuTrans: You need to pass in an i18next instance using i18nextReactModule`, {
  3245. i18nKey
  3246. });
  3247. return React.createElement(React.Fragment, {}, defaultTranslation);
  3248. }
  3249. const t = tFromProps || i18n.t?.bind(i18n) || (k => k);
  3250. let namespaces = ns || t.ns || i18n.options?.defaultNS;
  3251. namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
  3252. let mergedValues = values;
  3253. if (i18n.options?.interpolation?.defaultVariables) {
  3254. mergedValues = values && Object.keys(values).length > 0 ? {
  3255. ...values,
  3256. ...i18n.options.interpolation.defaultVariables
  3257. } : {
  3258. ...i18n.options.interpolation.defaultVariables
  3259. };
  3260. }
  3261. const translation = t(i18nKey, {
  3262. defaultValue: defaultTranslation,
  3263. ...mergedValues,
  3264. ns: namespaces
  3265. });
  3266. try {
  3267. const rendered = renderTranslation(translation, content);
  3268. return React.createElement(React.Fragment, {}, ...rendered);
  3269. } catch (error) {
  3270. warn(i18n, 'ICU_TRANS_RENDER_ERROR', `IcuTrans component error for key "${i18nKey}": ${error.message}`, {
  3271. i18nKey,
  3272. error
  3273. });
  3274. return React.createElement(React.Fragment, {}, translation);
  3275. }
  3276. }
  3277. IcuTransWithoutContext.displayName = 'IcuTransWithoutContext';
  3278. function IcuTrans({
  3279. i18nKey,
  3280. defaultTranslation,
  3281. content,
  3282. ns,
  3283. values = {},
  3284. i18n: i18nFromProps,
  3285. t: tFromProps
  3286. }) {
  3287. const {
  3288. i18n: i18nFromContext,
  3289. defaultNS: defaultNSFromContext
  3290. } = React.useContext(I18nContext) || {};
  3291. const i18n = i18nFromProps || i18nFromContext || getI18n();
  3292. const t = tFromProps || i18n?.t.bind(i18n);
  3293. return IcuTransWithoutContext({
  3294. i18nKey,
  3295. defaultTranslation,
  3296. content,
  3297. ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,
  3298. values,
  3299. i18n,
  3300. t: tFromProps
  3301. });
  3302. }
  3303. IcuTrans.displayName = 'IcuTrans';
  3304. var shim = {exports: {}};
  3305. var useSyncExternalStoreShim_development = {};
  3306. /**
  3307. * @license React
  3308. * use-sync-external-store-shim.development.js
  3309. *
  3310. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3311. *
  3312. * This source code is licensed under the MIT license found in the
  3313. * LICENSE file in the root directory of this source tree.
  3314. */
  3315. (function () {
  3316. function is(x, y) {
  3317. return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
  3318. }
  3319. function useSyncExternalStore$2(subscribe, getSnapshot) {
  3320. didWarnOld18Alpha || void 0 === React$1.startTransition || (didWarnOld18Alpha = true, console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));
  3321. var value = getSnapshot();
  3322. if (!didWarnUncachedGetSnapshot) {
  3323. var cachedValue = getSnapshot();
  3324. objectIs(value, cachedValue) || (console.error("The result of getSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true);
  3325. }
  3326. cachedValue = useState({
  3327. inst: {
  3328. value: value,
  3329. getSnapshot: getSnapshot
  3330. }
  3331. });
  3332. var inst = cachedValue[0].inst,
  3333. forceUpdate = cachedValue[1];
  3334. useLayoutEffect(function () {
  3335. inst.value = value;
  3336. inst.getSnapshot = getSnapshot;
  3337. checkIfSnapshotChanged(inst) && forceUpdate({
  3338. inst: inst
  3339. });
  3340. }, [subscribe, value, getSnapshot]);
  3341. useEffect(function () {
  3342. checkIfSnapshotChanged(inst) && forceUpdate({
  3343. inst: inst
  3344. });
  3345. return subscribe(function () {
  3346. checkIfSnapshotChanged(inst) && forceUpdate({
  3347. inst: inst
  3348. });
  3349. });
  3350. }, [subscribe]);
  3351. useDebugValue(value);
  3352. return value;
  3353. }
  3354. function checkIfSnapshotChanged(inst) {
  3355. var latestGetSnapshot = inst.getSnapshot;
  3356. inst = inst.value;
  3357. try {
  3358. var nextValue = latestGetSnapshot();
  3359. return !objectIs(inst, nextValue);
  3360. } catch (error) {
  3361. return true;
  3362. }
  3363. }
  3364. function useSyncExternalStore$1(subscribe, getSnapshot) {
  3365. return getSnapshot();
  3366. }
  3367. "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
  3368. var React$1 = React,
  3369. objectIs = "function" === typeof Object.is ? Object.is : is,
  3370. useState = React$1.useState,
  3371. useEffect = React$1.useEffect,
  3372. useLayoutEffect = React$1.useLayoutEffect,
  3373. useDebugValue = React$1.useDebugValue,
  3374. didWarnOld18Alpha = false,
  3375. didWarnUncachedGetSnapshot = false,
  3376. shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
  3377. useSyncExternalStoreShim_development.useSyncExternalStore = void 0 !== React$1.useSyncExternalStore ? React$1.useSyncExternalStore : shim;
  3378. "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  3379. })();
  3380. {
  3381. shim.exports = useSyncExternalStoreShim_development;
  3382. }
  3383. var shimExports = shim.exports;
  3384. const notReadyT = (k, optsOrDefaultValue) => {
  3385. if (isString(optsOrDefaultValue)) return optsOrDefaultValue;
  3386. if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
  3387. return Array.isArray(k) ? k[k.length - 1] : k;
  3388. };
  3389. const notReadySnapshot = {
  3390. t: notReadyT,
  3391. ready: false
  3392. };
  3393. const dummySubscribe = () => () => {};
  3394. const useTranslation = (ns, props = {}) => {
  3395. const {
  3396. i18n: i18nFromProps
  3397. } = props;
  3398. const {
  3399. i18n: i18nFromContext,
  3400. defaultNS: defaultNSFromContext
  3401. } = React.useContext(I18nContext) || {};
  3402. const i18n = i18nFromProps || i18nFromContext || getI18n();
  3403. if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
  3404. if (!i18n) {
  3405. warnOnce(i18n, 'NO_I18NEXT_INSTANCE', 'useTranslation: You will need to pass in an i18next instance by using initReactI18next');
  3406. }
  3407. const i18nOptions = React.useMemo(() => ({
  3408. ...getDefaults(),
  3409. ...i18n?.options?.react,
  3410. ...props
  3411. }), [i18n, props]);
  3412. const {
  3413. useSuspense,
  3414. keyPrefix
  3415. } = i18nOptions;
  3416. const nsOrContext = ns || defaultNSFromContext || i18n?.options?.defaultNS;
  3417. const unstableNamespaces = isString(nsOrContext) ? [nsOrContext] : nsOrContext || ['translation'];
  3418. const namespaces = React.useMemo(() => unstableNamespaces, unstableNamespaces);
  3419. i18n?.reportNamespaces?.addUsedNamespaces?.(namespaces);
  3420. const revisionRef = React.useRef(0);
  3421. const subscribe = React.useCallback(callback => {
  3422. if (!i18n) return dummySubscribe;
  3423. const {
  3424. bindI18n,
  3425. bindI18nStore
  3426. } = i18nOptions;
  3427. const wrappedCallback = () => {
  3428. revisionRef.current += 1;
  3429. callback();
  3430. };
  3431. if (bindI18n) i18n.on(bindI18n, wrappedCallback);
  3432. if (bindI18nStore) i18n.store.on(bindI18nStore, wrappedCallback);
  3433. return () => {
  3434. if (bindI18n) bindI18n.split(' ').forEach(e => i18n.off(e, wrappedCallback));
  3435. if (bindI18nStore) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, wrappedCallback));
  3436. };
  3437. }, [i18n, i18nOptions]);
  3438. const snapshotRef = React.useRef();
  3439. const getSnapshot = React.useCallback(() => {
  3440. if (!i18n) {
  3441. return notReadySnapshot;
  3442. }
  3443. const calculatedReady = !!(i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
  3444. const currentLng = props.lng || i18n.language;
  3445. const currentRevision = revisionRef.current;
  3446. const lastSnapshot = snapshotRef.current;
  3447. if (lastSnapshot && lastSnapshot.ready === calculatedReady && lastSnapshot.lng === currentLng && lastSnapshot.keyPrefix === keyPrefix && lastSnapshot.revision === currentRevision) {
  3448. return lastSnapshot;
  3449. }
  3450. const calculatedT = i18n.getFixedT(currentLng, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
  3451. const newSnapshot = {
  3452. t: calculatedT,
  3453. ready: calculatedReady,
  3454. lng: currentLng,
  3455. keyPrefix,
  3456. revision: currentRevision
  3457. };
  3458. snapshotRef.current = newSnapshot;
  3459. return newSnapshot;
  3460. }, [i18n, namespaces, keyPrefix, i18nOptions, props.lng]);
  3461. const [loadCount, setLoadCount] = React.useState(0);
  3462. const {
  3463. t,
  3464. ready
  3465. } = shimExports.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  3466. React.useEffect(() => {
  3467. if (i18n && !ready && !useSuspense) {
  3468. const onLoaded = () => setLoadCount(c => c + 1);
  3469. if (props.lng) {
  3470. loadLanguages(i18n, props.lng, namespaces, onLoaded);
  3471. } else {
  3472. loadNamespaces(i18n, namespaces, onLoaded);
  3473. }
  3474. }
  3475. }, [i18n, props.lng, namespaces, ready, useSuspense, loadCount]);
  3476. const finalI18n = i18n || {};
  3477. const wrapperRef = React.useRef(null);
  3478. const wrapperLangRef = React.useRef();
  3479. const createI18nWrapper = original => {
  3480. const descriptors = Object.getOwnPropertyDescriptors(original);
  3481. if (descriptors.__original) delete descriptors.__original;
  3482. const wrapper = Object.create(Object.getPrototypeOf(original), descriptors);
  3483. if (!Object.prototype.hasOwnProperty.call(wrapper, '__original')) {
  3484. try {
  3485. Object.defineProperty(wrapper, '__original', {
  3486. value: original,
  3487. writable: false,
  3488. enumerable: false,
  3489. configurable: false
  3490. });
  3491. } catch (_) {}
  3492. }
  3493. return wrapper;
  3494. };
  3495. const ret = React.useMemo(() => {
  3496. const original = finalI18n;
  3497. const lang = original?.language;
  3498. let i18nWrapper = original;
  3499. if (original) {
  3500. if (wrapperRef.current && wrapperRef.current.__original === original) {
  3501. if (wrapperLangRef.current !== lang) {
  3502. i18nWrapper = createI18nWrapper(original);
  3503. wrapperRef.current = i18nWrapper;
  3504. wrapperLangRef.current = lang;
  3505. } else {
  3506. i18nWrapper = wrapperRef.current;
  3507. }
  3508. } else {
  3509. i18nWrapper = createI18nWrapper(original);
  3510. wrapperRef.current = i18nWrapper;
  3511. wrapperLangRef.current = lang;
  3512. }
  3513. }
  3514. const arr = [t, i18nWrapper, ready];
  3515. arr.t = t;
  3516. arr.i18n = i18nWrapper;
  3517. arr.ready = ready;
  3518. return arr;
  3519. }, [t, finalI18n, ready, finalI18n.resolvedLanguage, finalI18n.language, finalI18n.languages]);
  3520. if (i18n && useSuspense && !ready) {
  3521. throw new Promise(resolve => {
  3522. const onLoaded = () => resolve();
  3523. if (props.lng) {
  3524. loadLanguages(i18n, props.lng, namespaces, onLoaded);
  3525. } else {
  3526. loadNamespaces(i18n, namespaces, onLoaded);
  3527. }
  3528. });
  3529. }
  3530. return ret;
  3531. };
  3532. const withTranslation = (ns, options = {}) => function Extend(WrappedComponent) {
  3533. function I18nextWithTranslation({
  3534. forwardedRef,
  3535. ...rest
  3536. }) {
  3537. const [t, i18n, ready] = useTranslation(ns, {
  3538. ...rest,
  3539. keyPrefix: options.keyPrefix
  3540. });
  3541. const passDownProps = {
  3542. ...rest,
  3543. t,
  3544. i18n,
  3545. tReady: ready
  3546. };
  3547. if (options.withRef && forwardedRef) {
  3548. passDownProps.ref = forwardedRef;
  3549. } else if (!options.withRef && forwardedRef) {
  3550. passDownProps.forwardedRef = forwardedRef;
  3551. }
  3552. return React.createElement(WrappedComponent, passDownProps);
  3553. }
  3554. I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(WrappedComponent)})`;
  3555. I18nextWithTranslation.WrappedComponent = WrappedComponent;
  3556. const forwardRef = (props, ref) => React.createElement(I18nextWithTranslation, Object.assign({}, props, {
  3557. forwardedRef: ref
  3558. }));
  3559. return options.withRef ? React.forwardRef(forwardRef) : I18nextWithTranslation;
  3560. };
  3561. const Translation = ({
  3562. ns,
  3563. children,
  3564. ...options
  3565. }) => {
  3566. const [t, i18n, ready] = useTranslation(ns, options);
  3567. return children(t, {
  3568. i18n,
  3569. lng: i18n.language
  3570. }, ready);
  3571. };
  3572. function I18nextProvider({
  3573. i18n,
  3574. defaultNS,
  3575. children
  3576. }) {
  3577. const value = React.useMemo(() => ({
  3578. i18n,
  3579. defaultNS
  3580. }), [i18n, defaultNS]);
  3581. return React.createElement(I18nContext.Provider, {
  3582. value
  3583. }, children);
  3584. }
  3585. const useSSR = (initialI18nStore, initialLanguage, props = {}) => {
  3586. const {
  3587. i18n: i18nFromProps
  3588. } = props;
  3589. const {
  3590. i18n: i18nFromContext
  3591. } = React.useContext(I18nContext) || {};
  3592. const i18n = i18nFromProps || i18nFromContext || getI18n();
  3593. if (i18n.options?.isClone) return;
  3594. if (initialI18nStore && !i18n.initializedStoreOnce) {
  3595. i18n.services.resourceStore.data = initialI18nStore;
  3596. i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {
  3597. Object.keys(lngResources).forEach(ns => {
  3598. if (mem.indexOf(ns) < 0) mem.push(ns);
  3599. });
  3600. return mem;
  3601. }, i18n.options.ns);
  3602. i18n.initializedStoreOnce = true;
  3603. i18n.isInitialized = true;
  3604. }
  3605. if (initialLanguage && !i18n.initializedLanguageOnce) {
  3606. i18n.changeLanguage(initialLanguage);
  3607. i18n.initializedLanguageOnce = true;
  3608. }
  3609. };
  3610. const withSSR = () => function Extend(WrappedComponent) {
  3611. function I18nextWithSSR({
  3612. initialI18nStore,
  3613. initialLanguage,
  3614. ...rest
  3615. }) {
  3616. useSSR(initialI18nStore, initialLanguage);
  3617. return React.createElement(WrappedComponent, {
  3618. ...rest
  3619. });
  3620. }
  3621. I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
  3622. I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;
  3623. I18nextWithSSR.WrappedComponent = WrappedComponent;
  3624. return I18nextWithSSR;
  3625. };
  3626. const date = () => '';
  3627. const time = () => '';
  3628. const number = () => '';
  3629. const select = () => '';
  3630. const plural = () => '';
  3631. const selectOrdinal = () => '';
  3632. exports.I18nContext = I18nContext;
  3633. exports.I18nextProvider = I18nextProvider;
  3634. exports.IcuTrans = IcuTrans;
  3635. exports.IcuTransWithoutContext = IcuTransWithoutContext;
  3636. exports.Trans = Trans;
  3637. exports.TransWithoutContext = Trans$1;
  3638. exports.Translation = Translation;
  3639. exports.composeInitialProps = composeInitialProps;
  3640. exports.date = date;
  3641. exports.getDefaults = getDefaults;
  3642. exports.getI18n = getI18n;
  3643. exports.getInitialProps = getInitialProps;
  3644. exports.initReactI18next = initReactI18next;
  3645. exports.number = number;
  3646. exports.plural = plural;
  3647. exports.select = select;
  3648. exports.selectOrdinal = selectOrdinal;
  3649. exports.setDefaults = setDefaults;
  3650. exports.setI18n = setI18n;
  3651. exports.time = time;
  3652. exports.useSSR = useSSR;
  3653. exports.useTranslation = useTranslation;
  3654. exports.withSSR = withSSR;
  3655. exports.withTranslation = withTranslation;
  3656. }));