i18next.js 85 KB

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