i18next.js 80 KB

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