vue-i18n.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  1. /*!
  2. * vue-i18n v8.15.5
  3. * (c) 2020 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.VueI18n = factory());
  10. }(this, (function () { 'use strict';
  11. /* */
  12. /**
  13. * constants
  14. */
  15. var numberFormatKeys = [
  16. 'style',
  17. 'currency',
  18. 'currencyDisplay',
  19. 'useGrouping',
  20. 'minimumIntegerDigits',
  21. 'minimumFractionDigits',
  22. 'maximumFractionDigits',
  23. 'minimumSignificantDigits',
  24. 'maximumSignificantDigits',
  25. 'localeMatcher',
  26. 'formatMatcher',
  27. 'unit'
  28. ];
  29. /**
  30. * utilities
  31. */
  32. function warn (msg, err) {
  33. if (typeof console !== 'undefined') {
  34. console.warn('[vue-i18n] ' + msg);
  35. /* istanbul ignore if */
  36. if (err) {
  37. console.warn(err.stack);
  38. }
  39. }
  40. }
  41. function error (msg, err) {
  42. if (typeof console !== 'undefined') {
  43. console.error('[vue-i18n] ' + msg);
  44. /* istanbul ignore if */
  45. if (err) {
  46. console.error(err.stack);
  47. }
  48. }
  49. }
  50. function isObject (obj) {
  51. return obj !== null && typeof obj === 'object'
  52. }
  53. var toString = Object.prototype.toString;
  54. var OBJECT_STRING = '[object Object]';
  55. function isPlainObject (obj) {
  56. return toString.call(obj) === OBJECT_STRING
  57. }
  58. function isNull (val) {
  59. return val === null || val === undefined
  60. }
  61. function parseArgs () {
  62. var args = [], len = arguments.length;
  63. while ( len-- ) args[ len ] = arguments[ len ];
  64. var locale = null;
  65. var params = null;
  66. if (args.length === 1) {
  67. if (isObject(args[0]) || Array.isArray(args[0])) {
  68. params = args[0];
  69. } else if (typeof args[0] === 'string') {
  70. locale = args[0];
  71. }
  72. } else if (args.length === 2) {
  73. if (typeof args[0] === 'string') {
  74. locale = args[0];
  75. }
  76. /* istanbul ignore if */
  77. if (isObject(args[1]) || Array.isArray(args[1])) {
  78. params = args[1];
  79. }
  80. }
  81. return { locale: locale, params: params }
  82. }
  83. function looseClone (obj) {
  84. return JSON.parse(JSON.stringify(obj))
  85. }
  86. function remove (arr, item) {
  87. if (arr.length) {
  88. var index = arr.indexOf(item);
  89. if (index > -1) {
  90. return arr.splice(index, 1)
  91. }
  92. }
  93. }
  94. var hasOwnProperty = Object.prototype.hasOwnProperty;
  95. function hasOwn (obj, key) {
  96. return hasOwnProperty.call(obj, key)
  97. }
  98. function merge (target) {
  99. var arguments$1 = arguments;
  100. var output = Object(target);
  101. for (var i = 1; i < arguments.length; i++) {
  102. var source = arguments$1[i];
  103. if (source !== undefined && source !== null) {
  104. var key = (void 0);
  105. for (key in source) {
  106. if (hasOwn(source, key)) {
  107. if (isObject(source[key])) {
  108. output[key] = merge(output[key], source[key]);
  109. } else {
  110. output[key] = source[key];
  111. }
  112. }
  113. }
  114. }
  115. }
  116. return output
  117. }
  118. function looseEqual (a, b) {
  119. if (a === b) { return true }
  120. var isObjectA = isObject(a);
  121. var isObjectB = isObject(b);
  122. if (isObjectA && isObjectB) {
  123. try {
  124. var isArrayA = Array.isArray(a);
  125. var isArrayB = Array.isArray(b);
  126. if (isArrayA && isArrayB) {
  127. return a.length === b.length && a.every(function (e, i) {
  128. return looseEqual(e, b[i])
  129. })
  130. } else if (!isArrayA && !isArrayB) {
  131. var keysA = Object.keys(a);
  132. var keysB = Object.keys(b);
  133. return keysA.length === keysB.length && keysA.every(function (key) {
  134. return looseEqual(a[key], b[key])
  135. })
  136. } else {
  137. /* istanbul ignore next */
  138. return false
  139. }
  140. } catch (e) {
  141. /* istanbul ignore next */
  142. return false
  143. }
  144. } else if (!isObjectA && !isObjectB) {
  145. return String(a) === String(b)
  146. } else {
  147. return false
  148. }
  149. }
  150. /* */
  151. function extend (Vue) {
  152. if (!Vue.prototype.hasOwnProperty('$i18n')) {
  153. // $FlowFixMe
  154. Object.defineProperty(Vue.prototype, '$i18n', {
  155. get: function get () { return this._i18n }
  156. });
  157. }
  158. Vue.prototype.$t = function (key) {
  159. var values = [], len = arguments.length - 1;
  160. while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ];
  161. var i18n = this.$i18n;
  162. return i18n._t.apply(i18n, [ key, i18n.locale, i18n._getMessages(), this ].concat( values ))
  163. };
  164. Vue.prototype.$tc = function (key, choice) {
  165. var values = [], len = arguments.length - 2;
  166. while ( len-- > 0 ) values[ len ] = arguments[ len + 2 ];
  167. var i18n = this.$i18n;
  168. return i18n._tc.apply(i18n, [ key, i18n.locale, i18n._getMessages(), this, choice ].concat( values ))
  169. };
  170. Vue.prototype.$te = function (key, locale) {
  171. var i18n = this.$i18n;
  172. return i18n._te(key, i18n.locale, i18n._getMessages(), locale)
  173. };
  174. Vue.prototype.$d = function (value) {
  175. var ref;
  176. var args = [], len = arguments.length - 1;
  177. while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
  178. return (ref = this.$i18n).d.apply(ref, [ value ].concat( args ))
  179. };
  180. Vue.prototype.$n = function (value) {
  181. var ref;
  182. var args = [], len = arguments.length - 1;
  183. while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
  184. return (ref = this.$i18n).n.apply(ref, [ value ].concat( args ))
  185. };
  186. }
  187. /* */
  188. var mixin = {
  189. beforeCreate: function beforeCreate () {
  190. var options = this.$options;
  191. options.i18n = options.i18n || (options.__i18n ? {} : null);
  192. if (options.i18n) {
  193. if (options.i18n instanceof VueI18n) {
  194. // init locale messages via custom blocks
  195. if (options.__i18n) {
  196. try {
  197. var localeMessages = {};
  198. options.__i18n.forEach(function (resource) {
  199. localeMessages = merge(localeMessages, JSON.parse(resource));
  200. });
  201. Object.keys(localeMessages).forEach(function (locale) {
  202. options.i18n.mergeLocaleMessage(locale, localeMessages[locale]);
  203. });
  204. } catch (e) {
  205. {
  206. error("Cannot parse locale messages via custom blocks.", e);
  207. }
  208. }
  209. }
  210. this._i18n = options.i18n;
  211. this._i18nWatcher = this._i18n.watchI18nData();
  212. } else if (isPlainObject(options.i18n)) {
  213. // component local i18n
  214. if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
  215. options.i18n.root = this.$root;
  216. options.i18n.formatter = this.$root.$i18n.formatter;
  217. options.i18n.fallbackLocale = this.$root.$i18n.fallbackLocale;
  218. options.i18n.formatFallbackMessages = this.$root.$i18n.formatFallbackMessages;
  219. options.i18n.silentTranslationWarn = this.$root.$i18n.silentTranslationWarn;
  220. options.i18n.silentFallbackWarn = this.$root.$i18n.silentFallbackWarn;
  221. options.i18n.pluralizationRules = this.$root.$i18n.pluralizationRules;
  222. options.i18n.preserveDirectiveContent = this.$root.$i18n.preserveDirectiveContent;
  223. }
  224. // init locale messages via custom blocks
  225. if (options.__i18n) {
  226. try {
  227. var localeMessages$1 = {};
  228. options.__i18n.forEach(function (resource) {
  229. localeMessages$1 = merge(localeMessages$1, JSON.parse(resource));
  230. });
  231. options.i18n.messages = localeMessages$1;
  232. } catch (e) {
  233. {
  234. warn("Cannot parse locale messages via custom blocks.", e);
  235. }
  236. }
  237. }
  238. var ref = options.i18n;
  239. var sharedMessages = ref.sharedMessages;
  240. if (sharedMessages && isPlainObject(sharedMessages)) {
  241. options.i18n.messages = merge(options.i18n.messages, sharedMessages);
  242. }
  243. this._i18n = new VueI18n(options.i18n);
  244. this._i18nWatcher = this._i18n.watchI18nData();
  245. if (options.i18n.sync === undefined || !!options.i18n.sync) {
  246. this._localeWatcher = this.$i18n.watchLocale();
  247. }
  248. } else {
  249. {
  250. warn("Cannot be interpreted 'i18n' option.");
  251. }
  252. }
  253. } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
  254. // root i18n
  255. this._i18n = this.$root.$i18n;
  256. } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
  257. // parent i18n
  258. this._i18n = options.parent.$i18n;
  259. }
  260. },
  261. beforeMount: function beforeMount () {
  262. var options = this.$options;
  263. options.i18n = options.i18n || (options.__i18n ? {} : null);
  264. if (options.i18n) {
  265. if (options.i18n instanceof VueI18n) {
  266. // init locale messages via custom blocks
  267. this._i18n.subscribeDataChanging(this);
  268. this._subscribing = true;
  269. } else if (isPlainObject(options.i18n)) {
  270. this._i18n.subscribeDataChanging(this);
  271. this._subscribing = true;
  272. } else {
  273. {
  274. warn("Cannot be interpreted 'i18n' option.");
  275. }
  276. }
  277. } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
  278. this._i18n.subscribeDataChanging(this);
  279. this._subscribing = true;
  280. } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
  281. this._i18n.subscribeDataChanging(this);
  282. this._subscribing = true;
  283. }
  284. },
  285. beforeDestroy: function beforeDestroy () {
  286. if (!this._i18n) { return }
  287. var self = this;
  288. this.$nextTick(function () {
  289. if (self._subscribing) {
  290. self._i18n.unsubscribeDataChanging(self);
  291. delete self._subscribing;
  292. }
  293. if (self._i18nWatcher) {
  294. self._i18nWatcher();
  295. self._i18n.destroyVM();
  296. delete self._i18nWatcher;
  297. }
  298. if (self._localeWatcher) {
  299. self._localeWatcher();
  300. delete self._localeWatcher;
  301. }
  302. self._i18n = null;
  303. });
  304. }
  305. };
  306. /* */
  307. var interpolationComponent = {
  308. name: 'i18n',
  309. functional: true,
  310. props: {
  311. tag: {
  312. type: String
  313. },
  314. path: {
  315. type: String,
  316. required: true
  317. },
  318. locale: {
  319. type: String
  320. },
  321. places: {
  322. type: [Array, Object]
  323. }
  324. },
  325. render: function render (h, ref) {
  326. var data = ref.data;
  327. var parent = ref.parent;
  328. var props = ref.props;
  329. var slots = ref.slots;
  330. var $i18n = parent.$i18n;
  331. if (!$i18n) {
  332. {
  333. warn('Cannot find VueI18n instance!');
  334. }
  335. return
  336. }
  337. var path = props.path;
  338. var locale = props.locale;
  339. var places = props.places;
  340. var params = slots();
  341. var children = $i18n.i(
  342. path,
  343. locale,
  344. onlyHasDefaultPlace(params) || places
  345. ? useLegacyPlaces(params.default, places)
  346. : params
  347. );
  348. var tag = props.tag || 'span';
  349. return tag ? h(tag, data, children) : children
  350. }
  351. };
  352. function onlyHasDefaultPlace (params) {
  353. var prop;
  354. for (prop in params) {
  355. if (prop !== 'default') { return false }
  356. }
  357. return Boolean(prop)
  358. }
  359. function useLegacyPlaces (children, places) {
  360. var params = places ? createParamsFromPlaces(places) : {};
  361. if (!children) { return params }
  362. // Filter empty text nodes
  363. children = children.filter(function (child) {
  364. return child.tag || child.text.trim() !== ''
  365. });
  366. var everyPlace = children.every(vnodeHasPlaceAttribute);
  367. if (everyPlace) {
  368. warn('`place` attribute is deprecated in next major version. Please switch to Vue slots.');
  369. }
  370. return children.reduce(
  371. everyPlace ? assignChildPlace : assignChildIndex,
  372. params
  373. )
  374. }
  375. function createParamsFromPlaces (places) {
  376. {
  377. warn('`places` prop is deprecated in next major version. Please switch to Vue slots.');
  378. }
  379. return Array.isArray(places)
  380. ? places.reduce(assignChildIndex, {})
  381. : Object.assign({}, places)
  382. }
  383. function assignChildPlace (params, child) {
  384. if (child.data && child.data.attrs && child.data.attrs.place) {
  385. params[child.data.attrs.place] = child;
  386. }
  387. return params
  388. }
  389. function assignChildIndex (params, child, index) {
  390. params[index] = child;
  391. return params
  392. }
  393. function vnodeHasPlaceAttribute (vnode) {
  394. return Boolean(vnode.data && vnode.data.attrs && vnode.data.attrs.place)
  395. }
  396. /* */
  397. var numberComponent = {
  398. name: 'i18n-n',
  399. functional: true,
  400. props: {
  401. tag: {
  402. type: String,
  403. default: 'span'
  404. },
  405. value: {
  406. type: Number,
  407. required: true
  408. },
  409. format: {
  410. type: [String, Object]
  411. },
  412. locale: {
  413. type: String
  414. }
  415. },
  416. render: function render (h, ref) {
  417. var props = ref.props;
  418. var parent = ref.parent;
  419. var data = ref.data;
  420. var i18n = parent.$i18n;
  421. if (!i18n) {
  422. {
  423. warn('Cannot find VueI18n instance!');
  424. }
  425. return null
  426. }
  427. var key = null;
  428. var options = null;
  429. if (typeof props.format === 'string') {
  430. key = props.format;
  431. } else if (isObject(props.format)) {
  432. if (props.format.key) {
  433. key = props.format.key;
  434. }
  435. // Filter out number format options only
  436. options = Object.keys(props.format).reduce(function (acc, prop) {
  437. var obj;
  438. if (numberFormatKeys.includes(prop)) {
  439. return Object.assign({}, acc, ( obj = {}, obj[prop] = props.format[prop], obj ))
  440. }
  441. return acc
  442. }, null);
  443. }
  444. var locale = props.locale || i18n.locale;
  445. var parts = i18n._ntp(props.value, locale, key, options);
  446. var values = parts.map(function (part, index) {
  447. var obj;
  448. var slot = data.scopedSlots && data.scopedSlots[part.type];
  449. return slot ? slot(( obj = {}, obj[part.type] = part.value, obj.index = index, obj.parts = parts, obj )) : part.value
  450. });
  451. return h(props.tag, {
  452. attrs: data.attrs,
  453. 'class': data['class'],
  454. staticClass: data.staticClass
  455. }, values)
  456. }
  457. };
  458. /* */
  459. function bind (el, binding, vnode) {
  460. if (!assert(el, vnode)) { return }
  461. t(el, binding, vnode);
  462. }
  463. function update (el, binding, vnode, oldVNode) {
  464. if (!assert(el, vnode)) { return }
  465. var i18n = vnode.context.$i18n;
  466. if (localeEqual(el, vnode) &&
  467. (looseEqual(binding.value, binding.oldValue) &&
  468. looseEqual(el._localeMessage, i18n.getLocaleMessage(i18n.locale)))) { return }
  469. t(el, binding, vnode);
  470. }
  471. function unbind (el, binding, vnode, oldVNode) {
  472. var vm = vnode.context;
  473. if (!vm) {
  474. warn('Vue instance does not exists in VNode context');
  475. return
  476. }
  477. var i18n = vnode.context.$i18n || {};
  478. if (!binding.modifiers.preserve && !i18n.preserveDirectiveContent) {
  479. el.textContent = '';
  480. }
  481. el._vt = undefined;
  482. delete el['_vt'];
  483. el._locale = undefined;
  484. delete el['_locale'];
  485. el._localeMessage = undefined;
  486. delete el['_localeMessage'];
  487. }
  488. function assert (el, vnode) {
  489. var vm = vnode.context;
  490. if (!vm) {
  491. warn('Vue instance does not exists in VNode context');
  492. return false
  493. }
  494. if (!vm.$i18n) {
  495. warn('VueI18n instance does not exists in Vue instance');
  496. return false
  497. }
  498. return true
  499. }
  500. function localeEqual (el, vnode) {
  501. var vm = vnode.context;
  502. return el._locale === vm.$i18n.locale
  503. }
  504. function t (el, binding, vnode) {
  505. var ref$1, ref$2;
  506. var value = binding.value;
  507. var ref = parseValue(value);
  508. var path = ref.path;
  509. var locale = ref.locale;
  510. var args = ref.args;
  511. var choice = ref.choice;
  512. if (!path && !locale && !args) {
  513. warn('value type not supported');
  514. return
  515. }
  516. if (!path) {
  517. warn('`path` is required in v-t directive');
  518. return
  519. }
  520. var vm = vnode.context;
  521. if (choice) {
  522. el._vt = el.textContent = (ref$1 = vm.$i18n).tc.apply(ref$1, [ path, choice ].concat( makeParams(locale, args) ));
  523. } else {
  524. el._vt = el.textContent = (ref$2 = vm.$i18n).t.apply(ref$2, [ path ].concat( makeParams(locale, args) ));
  525. }
  526. el._locale = vm.$i18n.locale;
  527. el._localeMessage = vm.$i18n.getLocaleMessage(vm.$i18n.locale);
  528. }
  529. function parseValue (value) {
  530. var path;
  531. var locale;
  532. var args;
  533. var choice;
  534. if (typeof value === 'string') {
  535. path = value;
  536. } else if (isPlainObject(value)) {
  537. path = value.path;
  538. locale = value.locale;
  539. args = value.args;
  540. choice = value.choice;
  541. }
  542. return { path: path, locale: locale, args: args, choice: choice }
  543. }
  544. function makeParams (locale, args) {
  545. var params = [];
  546. locale && params.push(locale);
  547. if (args && (Array.isArray(args) || isPlainObject(args))) {
  548. params.push(args);
  549. }
  550. return params
  551. }
  552. var Vue;
  553. function install (_Vue) {
  554. /* istanbul ignore if */
  555. if (install.installed && _Vue === Vue) {
  556. warn('already installed.');
  557. return
  558. }
  559. install.installed = true;
  560. Vue = _Vue;
  561. var version = (Vue.version && Number(Vue.version.split('.')[0])) || -1;
  562. /* istanbul ignore if */
  563. if (version < 2) {
  564. warn(("vue-i18n (" + (install.version) + ") need to use Vue 2.0 or later (Vue: " + (Vue.version) + ")."));
  565. return
  566. }
  567. extend(Vue);
  568. Vue.mixin(mixin);
  569. Vue.directive('t', { bind: bind, update: update, unbind: unbind });
  570. Vue.component(interpolationComponent.name, interpolationComponent);
  571. Vue.component(numberComponent.name, numberComponent);
  572. // use simple mergeStrategies to prevent i18n instance lose '__proto__'
  573. var strats = Vue.config.optionMergeStrategies;
  574. strats.i18n = function (parentVal, childVal) {
  575. return childVal === undefined
  576. ? parentVal
  577. : childVal
  578. };
  579. }
  580. /* */
  581. var BaseFormatter = function BaseFormatter () {
  582. this._caches = Object.create(null);
  583. };
  584. BaseFormatter.prototype.interpolate = function interpolate (message, values) {
  585. if (!values) {
  586. return [message]
  587. }
  588. var tokens = this._caches[message];
  589. if (!tokens) {
  590. tokens = parse(message);
  591. this._caches[message] = tokens;
  592. }
  593. return compile(tokens, values)
  594. };
  595. var RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
  596. var RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
  597. function parse (format) {
  598. var tokens = [];
  599. var position = 0;
  600. var text = '';
  601. while (position < format.length) {
  602. var char = format[position++];
  603. if (char === '{') {
  604. if (text) {
  605. tokens.push({ type: 'text', value: text });
  606. }
  607. text = '';
  608. var sub = '';
  609. char = format[position++];
  610. while (char !== undefined && char !== '}') {
  611. sub += char;
  612. char = format[position++];
  613. }
  614. var isClosed = char === '}';
  615. var type = RE_TOKEN_LIST_VALUE.test(sub)
  616. ? 'list'
  617. : isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
  618. ? 'named'
  619. : 'unknown';
  620. tokens.push({ value: sub, type: type });
  621. } else if (char === '%') {
  622. // when found rails i18n syntax, skip text capture
  623. if (format[(position)] !== '{') {
  624. text += char;
  625. }
  626. } else {
  627. text += char;
  628. }
  629. }
  630. text && tokens.push({ type: 'text', value: text });
  631. return tokens
  632. }
  633. function compile (tokens, values) {
  634. var compiled = [];
  635. var index = 0;
  636. var mode = Array.isArray(values)
  637. ? 'list'
  638. : isObject(values)
  639. ? 'named'
  640. : 'unknown';
  641. if (mode === 'unknown') { return compiled }
  642. while (index < tokens.length) {
  643. var token = tokens[index];
  644. switch (token.type) {
  645. case 'text':
  646. compiled.push(token.value);
  647. break
  648. case 'list':
  649. compiled.push(values[parseInt(token.value, 10)]);
  650. break
  651. case 'named':
  652. if (mode === 'named') {
  653. compiled.push((values)[token.value]);
  654. } else {
  655. {
  656. warn(("Type of token '" + (token.type) + "' and format of value '" + mode + "' don't match!"));
  657. }
  658. }
  659. break
  660. case 'unknown':
  661. {
  662. warn("Detect 'unknown' type of token!");
  663. }
  664. break
  665. }
  666. index++;
  667. }
  668. return compiled
  669. }
  670. /* */
  671. /**
  672. * Path parser
  673. * - Inspired:
  674. * Vue.js Path parser
  675. */
  676. // actions
  677. var APPEND = 0;
  678. var PUSH = 1;
  679. var INC_SUB_PATH_DEPTH = 2;
  680. var PUSH_SUB_PATH = 3;
  681. // states
  682. var BEFORE_PATH = 0;
  683. var IN_PATH = 1;
  684. var BEFORE_IDENT = 2;
  685. var IN_IDENT = 3;
  686. var IN_SUB_PATH = 4;
  687. var IN_SINGLE_QUOTE = 5;
  688. var IN_DOUBLE_QUOTE = 6;
  689. var AFTER_PATH = 7;
  690. var ERROR = 8;
  691. var pathStateMachine = [];
  692. pathStateMachine[BEFORE_PATH] = {
  693. 'ws': [BEFORE_PATH],
  694. 'ident': [IN_IDENT, APPEND],
  695. '[': [IN_SUB_PATH],
  696. 'eof': [AFTER_PATH]
  697. };
  698. pathStateMachine[IN_PATH] = {
  699. 'ws': [IN_PATH],
  700. '.': [BEFORE_IDENT],
  701. '[': [IN_SUB_PATH],
  702. 'eof': [AFTER_PATH]
  703. };
  704. pathStateMachine[BEFORE_IDENT] = {
  705. 'ws': [BEFORE_IDENT],
  706. 'ident': [IN_IDENT, APPEND],
  707. '0': [IN_IDENT, APPEND],
  708. 'number': [IN_IDENT, APPEND]
  709. };
  710. pathStateMachine[IN_IDENT] = {
  711. 'ident': [IN_IDENT, APPEND],
  712. '0': [IN_IDENT, APPEND],
  713. 'number': [IN_IDENT, APPEND],
  714. 'ws': [IN_PATH, PUSH],
  715. '.': [BEFORE_IDENT, PUSH],
  716. '[': [IN_SUB_PATH, PUSH],
  717. 'eof': [AFTER_PATH, PUSH]
  718. };
  719. pathStateMachine[IN_SUB_PATH] = {
  720. "'": [IN_SINGLE_QUOTE, APPEND],
  721. '"': [IN_DOUBLE_QUOTE, APPEND],
  722. '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH],
  723. ']': [IN_PATH, PUSH_SUB_PATH],
  724. 'eof': ERROR,
  725. 'else': [IN_SUB_PATH, APPEND]
  726. };
  727. pathStateMachine[IN_SINGLE_QUOTE] = {
  728. "'": [IN_SUB_PATH, APPEND],
  729. 'eof': ERROR,
  730. 'else': [IN_SINGLE_QUOTE, APPEND]
  731. };
  732. pathStateMachine[IN_DOUBLE_QUOTE] = {
  733. '"': [IN_SUB_PATH, APPEND],
  734. 'eof': ERROR,
  735. 'else': [IN_DOUBLE_QUOTE, APPEND]
  736. };
  737. /**
  738. * Check if an expression is a literal value.
  739. */
  740. var literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  741. function isLiteral (exp) {
  742. return literalValueRE.test(exp)
  743. }
  744. /**
  745. * Strip quotes from a string
  746. */
  747. function stripQuotes (str) {
  748. var a = str.charCodeAt(0);
  749. var b = str.charCodeAt(str.length - 1);
  750. return a === b && (a === 0x22 || a === 0x27)
  751. ? str.slice(1, -1)
  752. : str
  753. }
  754. /**
  755. * Determine the type of a character in a keypath.
  756. */
  757. function getPathCharType (ch) {
  758. if (ch === undefined || ch === null) { return 'eof' }
  759. var code = ch.charCodeAt(0);
  760. switch (code) {
  761. case 0x5B: // [
  762. case 0x5D: // ]
  763. case 0x2E: // .
  764. case 0x22: // "
  765. case 0x27: // '
  766. return ch
  767. case 0x5F: // _
  768. case 0x24: // $
  769. case 0x2D: // -
  770. return 'ident'
  771. case 0x09: // Tab
  772. case 0x0A: // Newline
  773. case 0x0D: // Return
  774. case 0xA0: // No-break space
  775. case 0xFEFF: // Byte Order Mark
  776. case 0x2028: // Line Separator
  777. case 0x2029: // Paragraph Separator
  778. return 'ws'
  779. }
  780. return 'ident'
  781. }
  782. /**
  783. * Format a subPath, return its plain form if it is
  784. * a literal string or number. Otherwise prepend the
  785. * dynamic indicator (*).
  786. */
  787. function formatSubPath (path) {
  788. var trimmed = path.trim();
  789. // invalid leading 0
  790. if (path.charAt(0) === '0' && isNaN(path)) { return false }
  791. return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed
  792. }
  793. /**
  794. * Parse a string path into an array of segments
  795. */
  796. function parse$1 (path) {
  797. var keys = [];
  798. var index = -1;
  799. var mode = BEFORE_PATH;
  800. var subPathDepth = 0;
  801. var c;
  802. var key;
  803. var newChar;
  804. var type;
  805. var transition;
  806. var action;
  807. var typeMap;
  808. var actions = [];
  809. actions[PUSH] = function () {
  810. if (key !== undefined) {
  811. keys.push(key);
  812. key = undefined;
  813. }
  814. };
  815. actions[APPEND] = function () {
  816. if (key === undefined) {
  817. key = newChar;
  818. } else {
  819. key += newChar;
  820. }
  821. };
  822. actions[INC_SUB_PATH_DEPTH] = function () {
  823. actions[APPEND]();
  824. subPathDepth++;
  825. };
  826. actions[PUSH_SUB_PATH] = function () {
  827. if (subPathDepth > 0) {
  828. subPathDepth--;
  829. mode = IN_SUB_PATH;
  830. actions[APPEND]();
  831. } else {
  832. subPathDepth = 0;
  833. if (key === undefined) { return false }
  834. key = formatSubPath(key);
  835. if (key === false) {
  836. return false
  837. } else {
  838. actions[PUSH]();
  839. }
  840. }
  841. };
  842. function maybeUnescapeQuote () {
  843. var nextChar = path[index + 1];
  844. if ((mode === IN_SINGLE_QUOTE && nextChar === "'") ||
  845. (mode === IN_DOUBLE_QUOTE && nextChar === '"')) {
  846. index++;
  847. newChar = '\\' + nextChar;
  848. actions[APPEND]();
  849. return true
  850. }
  851. }
  852. while (mode !== null) {
  853. index++;
  854. c = path[index];
  855. if (c === '\\' && maybeUnescapeQuote()) {
  856. continue
  857. }
  858. type = getPathCharType(c);
  859. typeMap = pathStateMachine[mode];
  860. transition = typeMap[type] || typeMap['else'] || ERROR;
  861. if (transition === ERROR) {
  862. return // parse error
  863. }
  864. mode = transition[0];
  865. action = actions[transition[1]];
  866. if (action) {
  867. newChar = transition[2];
  868. newChar = newChar === undefined
  869. ? c
  870. : newChar;
  871. if (action() === false) {
  872. return
  873. }
  874. }
  875. if (mode === AFTER_PATH) {
  876. return keys
  877. }
  878. }
  879. }
  880. var I18nPath = function I18nPath () {
  881. this._cache = Object.create(null);
  882. };
  883. /**
  884. * External parse that check for a cache hit first
  885. */
  886. I18nPath.prototype.parsePath = function parsePath (path) {
  887. var hit = this._cache[path];
  888. if (!hit) {
  889. hit = parse$1(path);
  890. if (hit) {
  891. this._cache[path] = hit;
  892. }
  893. }
  894. return hit || []
  895. };
  896. /**
  897. * Get path value from path string
  898. */
  899. I18nPath.prototype.getPathValue = function getPathValue (obj, path) {
  900. if (!isObject(obj)) { return null }
  901. var paths = this.parsePath(path);
  902. if (paths.length === 0) {
  903. return null
  904. } else {
  905. var length = paths.length;
  906. var last = obj;
  907. var i = 0;
  908. while (i < length) {
  909. var value = last[paths[i]];
  910. if (value === undefined) {
  911. return null
  912. }
  913. last = value;
  914. i++;
  915. }
  916. return last
  917. }
  918. };
  919. /* */
  920. var htmlTagMatcher = /<\/?[\w\s="/.':;#-\/]+>/;
  921. var linkKeyMatcher = /(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))/g;
  922. var linkKeyPrefixMatcher = /^@(?:\.([a-z]+))?:/;
  923. var bracketsMatcher = /[()]/g;
  924. var defaultModifiers = {
  925. 'upper': function (str) { return str.toLocaleUpperCase(); },
  926. 'lower': function (str) { return str.toLocaleLowerCase(); },
  927. 'capitalize': function (str) { return ("" + (str.charAt(0).toLocaleUpperCase()) + (str.substr(1))); }
  928. };
  929. var defaultFormatter = new BaseFormatter();
  930. var VueI18n = function VueI18n (options) {
  931. var this$1 = this;
  932. if ( options === void 0 ) options = {};
  933. // Auto install if it is not done yet and `window` has `Vue`.
  934. // To allow users to avoid auto-installation in some cases,
  935. // this code should be placed here. See #290
  936. /* istanbul ignore if */
  937. if (!Vue && typeof window !== 'undefined' && window.Vue) {
  938. install(window.Vue);
  939. }
  940. var locale = options.locale || 'en-US';
  941. var fallbackLocale = options.fallbackLocale || 'en-US';
  942. var messages = options.messages || {};
  943. var dateTimeFormats = options.dateTimeFormats || {};
  944. var numberFormats = options.numberFormats || {};
  945. this._vm = null;
  946. this._formatter = options.formatter || defaultFormatter;
  947. this._modifiers = options.modifiers || {};
  948. this._missing = options.missing || null;
  949. this._root = options.root || null;
  950. this._sync = options.sync === undefined ? true : !!options.sync;
  951. this._fallbackRoot = options.fallbackRoot === undefined
  952. ? true
  953. : !!options.fallbackRoot;
  954. this._formatFallbackMessages = options.formatFallbackMessages === undefined
  955. ? false
  956. : !!options.formatFallbackMessages;
  957. this._silentTranslationWarn = options.silentTranslationWarn === undefined
  958. ? false
  959. : options.silentTranslationWarn;
  960. this._silentFallbackWarn = options.silentFallbackWarn === undefined
  961. ? false
  962. : !!options.silentFallbackWarn;
  963. this._dateTimeFormatters = {};
  964. this._numberFormatters = {};
  965. this._path = new I18nPath();
  966. this._dataListeners = [];
  967. this._preserveDirectiveContent = options.preserveDirectiveContent === undefined
  968. ? false
  969. : !!options.preserveDirectiveContent;
  970. this.pluralizationRules = options.pluralizationRules || {};
  971. this._warnHtmlInMessage = options.warnHtmlInMessage || 'off';
  972. this._exist = function (message, key) {
  973. if (!message || !key) { return false }
  974. if (!isNull(this$1._path.getPathValue(message, key))) { return true }
  975. // fallback for flat key
  976. if (message[key]) { return true }
  977. return false
  978. };
  979. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  980. Object.keys(messages).forEach(function (locale) {
  981. this$1._checkLocaleMessage(locale, this$1._warnHtmlInMessage, messages[locale]);
  982. });
  983. }
  984. this._initVM({
  985. locale: locale,
  986. fallbackLocale: fallbackLocale,
  987. messages: messages,
  988. dateTimeFormats: dateTimeFormats,
  989. numberFormats: numberFormats
  990. });
  991. };
  992. var prototypeAccessors = { vm: { configurable: true },messages: { configurable: true },dateTimeFormats: { configurable: true },numberFormats: { configurable: true },availableLocales: { configurable: true },locale: { configurable: true },fallbackLocale: { configurable: true },formatFallbackMessages: { configurable: true },missing: { configurable: true },formatter: { configurable: true },silentTranslationWarn: { configurable: true },silentFallbackWarn: { configurable: true },preserveDirectiveContent: { configurable: true },warnHtmlInMessage: { configurable: true } };
  993. VueI18n.prototype._checkLocaleMessage = function _checkLocaleMessage (locale, level, message) {
  994. var paths = [];
  995. var fn = function (level, locale, message, paths) {
  996. if (isPlainObject(message)) {
  997. Object.keys(message).forEach(function (key) {
  998. var val = message[key];
  999. if (isPlainObject(val)) {
  1000. paths.push(key);
  1001. paths.push('.');
  1002. fn(level, locale, val, paths);
  1003. paths.pop();
  1004. paths.pop();
  1005. } else {
  1006. paths.push(key);
  1007. fn(level, locale, val, paths);
  1008. paths.pop();
  1009. }
  1010. });
  1011. } else if (Array.isArray(message)) {
  1012. message.forEach(function (item, index) {
  1013. if (isPlainObject(item)) {
  1014. paths.push(("[" + index + "]"));
  1015. paths.push('.');
  1016. fn(level, locale, item, paths);
  1017. paths.pop();
  1018. paths.pop();
  1019. } else {
  1020. paths.push(("[" + index + "]"));
  1021. fn(level, locale, item, paths);
  1022. paths.pop();
  1023. }
  1024. });
  1025. } else if (typeof message === 'string') {
  1026. var ret = htmlTagMatcher.test(message);
  1027. if (ret) {
  1028. var msg = "Detected HTML in message '" + message + "' of keypath '" + (paths.join('')) + "' at '" + locale + "'. Consider component interpolation with '<i18n>' to avoid XSS. See https://bit.ly/2ZqJzkp";
  1029. if (level === 'warn') {
  1030. warn(msg);
  1031. } else if (level === 'error') {
  1032. error(msg);
  1033. }
  1034. }
  1035. }
  1036. };
  1037. fn(level, locale, message, paths);
  1038. };
  1039. VueI18n.prototype._initVM = function _initVM (data) {
  1040. var silent = Vue.config.silent;
  1041. Vue.config.silent = true;
  1042. this._vm = new Vue({ data: data });
  1043. Vue.config.silent = silent;
  1044. };
  1045. VueI18n.prototype.destroyVM = function destroyVM () {
  1046. this._vm.$destroy();
  1047. };
  1048. VueI18n.prototype.subscribeDataChanging = function subscribeDataChanging (vm) {
  1049. this._dataListeners.push(vm);
  1050. };
  1051. VueI18n.prototype.unsubscribeDataChanging = function unsubscribeDataChanging (vm) {
  1052. remove(this._dataListeners, vm);
  1053. };
  1054. VueI18n.prototype.watchI18nData = function watchI18nData () {
  1055. var self = this;
  1056. return this._vm.$watch('$data', function () {
  1057. var i = self._dataListeners.length;
  1058. while (i--) {
  1059. Vue.nextTick(function () {
  1060. self._dataListeners[i] && self._dataListeners[i].$forceUpdate();
  1061. });
  1062. }
  1063. }, { deep: true })
  1064. };
  1065. VueI18n.prototype.watchLocale = function watchLocale () {
  1066. /* istanbul ignore if */
  1067. if (!this._sync || !this._root) { return null }
  1068. var target = this._vm;
  1069. return this._root.$i18n.vm.$watch('locale', function (val) {
  1070. target.$set(target, 'locale', val);
  1071. target.$forceUpdate();
  1072. }, { immediate: true })
  1073. };
  1074. prototypeAccessors.vm.get = function () { return this._vm };
  1075. prototypeAccessors.messages.get = function () { return looseClone(this._getMessages()) };
  1076. prototypeAccessors.dateTimeFormats.get = function () { return looseClone(this._getDateTimeFormats()) };
  1077. prototypeAccessors.numberFormats.get = function () { return looseClone(this._getNumberFormats()) };
  1078. prototypeAccessors.availableLocales.get = function () { return Object.keys(this.messages).sort() };
  1079. prototypeAccessors.locale.get = function () { return this._vm.locale };
  1080. prototypeAccessors.locale.set = function (locale) {
  1081. this._vm.$set(this._vm, 'locale', locale);
  1082. };
  1083. prototypeAccessors.fallbackLocale.get = function () { return this._vm.fallbackLocale };
  1084. prototypeAccessors.fallbackLocale.set = function (locale) {
  1085. this._vm.$set(this._vm, 'fallbackLocale', locale);
  1086. };
  1087. prototypeAccessors.formatFallbackMessages.get = function () { return this._formatFallbackMessages };
  1088. prototypeAccessors.formatFallbackMessages.set = function (fallback) { this._formatFallbackMessages = fallback; };
  1089. prototypeAccessors.missing.get = function () { return this._missing };
  1090. prototypeAccessors.missing.set = function (handler) { this._missing = handler; };
  1091. prototypeAccessors.formatter.get = function () { return this._formatter };
  1092. prototypeAccessors.formatter.set = function (formatter) { this._formatter = formatter; };
  1093. prototypeAccessors.silentTranslationWarn.get = function () { return this._silentTranslationWarn };
  1094. prototypeAccessors.silentTranslationWarn.set = function (silent) { this._silentTranslationWarn = silent; };
  1095. prototypeAccessors.silentFallbackWarn.get = function () { return this._silentFallbackWarn };
  1096. prototypeAccessors.silentFallbackWarn.set = function (silent) { this._silentFallbackWarn = silent; };
  1097. prototypeAccessors.preserveDirectiveContent.get = function () { return this._preserveDirectiveContent };
  1098. prototypeAccessors.preserveDirectiveContent.set = function (preserve) { this._preserveDirectiveContent = preserve; };
  1099. prototypeAccessors.warnHtmlInMessage.get = function () { return this._warnHtmlInMessage };
  1100. prototypeAccessors.warnHtmlInMessage.set = function (level) {
  1101. var this$1 = this;
  1102. var orgLevel = this._warnHtmlInMessage;
  1103. this._warnHtmlInMessage = level;
  1104. if (orgLevel !== level && (level === 'warn' || level === 'error')) {
  1105. var messages = this._getMessages();
  1106. Object.keys(messages).forEach(function (locale) {
  1107. this$1._checkLocaleMessage(locale, this$1._warnHtmlInMessage, messages[locale]);
  1108. });
  1109. }
  1110. };
  1111. VueI18n.prototype._getMessages = function _getMessages () { return this._vm.messages };
  1112. VueI18n.prototype._getDateTimeFormats = function _getDateTimeFormats () { return this._vm.dateTimeFormats };
  1113. VueI18n.prototype._getNumberFormats = function _getNumberFormats () { return this._vm.numberFormats };
  1114. VueI18n.prototype._warnDefault = function _warnDefault (locale, key, result, vm, values, interpolateMode) {
  1115. if (!isNull(result)) { return result }
  1116. if (this._missing) {
  1117. var missingRet = this._missing.apply(null, [locale, key, vm, values]);
  1118. if (typeof missingRet === 'string') {
  1119. return missingRet
  1120. }
  1121. } else {
  1122. if (!this._isSilentTranslationWarn(key)) {
  1123. warn(
  1124. "Cannot translate the value of keypath '" + key + "'. " +
  1125. 'Use the value of keypath as default.'
  1126. );
  1127. }
  1128. }
  1129. if (this._formatFallbackMessages) {
  1130. var parsedArgs = parseArgs.apply(void 0, values);
  1131. return this._render(key, interpolateMode, parsedArgs.params, key)
  1132. } else {
  1133. return key
  1134. }
  1135. };
  1136. VueI18n.prototype._isFallbackRoot = function _isFallbackRoot (val) {
  1137. return !val && !isNull(this._root) && this._fallbackRoot
  1138. };
  1139. VueI18n.prototype._isSilentFallbackWarn = function _isSilentFallbackWarn (key) {
  1140. return this._silentFallbackWarn instanceof RegExp
  1141. ? this._silentFallbackWarn.test(key)
  1142. : this._silentFallbackWarn
  1143. };
  1144. VueI18n.prototype._isSilentFallback = function _isSilentFallback (locale, key) {
  1145. return this._isSilentFallbackWarn(key) && (this._isFallbackRoot() || locale !== this.fallbackLocale)
  1146. };
  1147. VueI18n.prototype._isSilentTranslationWarn = function _isSilentTranslationWarn (key) {
  1148. return this._silentTranslationWarn instanceof RegExp
  1149. ? this._silentTranslationWarn.test(key)
  1150. : this._silentTranslationWarn
  1151. };
  1152. VueI18n.prototype._interpolate = function _interpolate (
  1153. locale,
  1154. message,
  1155. key,
  1156. host,
  1157. interpolateMode,
  1158. values,
  1159. visitedLinkStack
  1160. ) {
  1161. if (!message) { return null }
  1162. var pathRet = this._path.getPathValue(message, key);
  1163. if (Array.isArray(pathRet) || isPlainObject(pathRet)) { return pathRet }
  1164. var ret;
  1165. if (isNull(pathRet)) {
  1166. /* istanbul ignore else */
  1167. if (isPlainObject(message)) {
  1168. ret = message[key];
  1169. if (typeof ret !== 'string') {
  1170. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) {
  1171. warn(("Value of key '" + key + "' is not a string!"));
  1172. }
  1173. return null
  1174. }
  1175. } else {
  1176. return null
  1177. }
  1178. } else {
  1179. /* istanbul ignore else */
  1180. if (typeof pathRet === 'string') {
  1181. ret = pathRet;
  1182. } else {
  1183. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) {
  1184. warn(("Value of key '" + key + "' is not a string!"));
  1185. }
  1186. return null
  1187. }
  1188. }
  1189. // Check for the existence of links within the translated string
  1190. if (ret.indexOf('@:') >= 0 || ret.indexOf('@.') >= 0) {
  1191. ret = this._link(locale, message, ret, host, 'raw', values, visitedLinkStack);
  1192. }
  1193. return this._render(ret, interpolateMode, values, key)
  1194. };
  1195. VueI18n.prototype._link = function _link (
  1196. locale,
  1197. message,
  1198. str,
  1199. host,
  1200. interpolateMode,
  1201. values,
  1202. visitedLinkStack
  1203. ) {
  1204. var ret = str;
  1205. // Match all the links within the local
  1206. // We are going to replace each of
  1207. // them with its translation
  1208. var matches = ret.match(linkKeyMatcher);
  1209. for (var idx in matches) {
  1210. // ie compatible: filter custom array
  1211. // prototype method
  1212. if (!matches.hasOwnProperty(idx)) {
  1213. continue
  1214. }
  1215. var link = matches[idx];
  1216. var linkKeyPrefixMatches = link.match(linkKeyPrefixMatcher);
  1217. var linkPrefix = linkKeyPrefixMatches[0];
  1218. var formatterName = linkKeyPrefixMatches[1];
  1219. // Remove the leading @:, @.case: and the brackets
  1220. var linkPlaceholder = link.replace(linkPrefix, '').replace(bracketsMatcher, '');
  1221. if (visitedLinkStack.includes(linkPlaceholder)) {
  1222. {
  1223. warn(("Circular reference found. \"" + link + "\" is already visited in the chain of " + (visitedLinkStack.reverse().join(' <- '))));
  1224. }
  1225. return ret
  1226. }
  1227. visitedLinkStack.push(linkPlaceholder);
  1228. // Translate the link
  1229. var translated = this._interpolate(
  1230. locale, message, linkPlaceholder, host,
  1231. interpolateMode === 'raw' ? 'string' : interpolateMode,
  1232. interpolateMode === 'raw' ? undefined : values,
  1233. visitedLinkStack
  1234. );
  1235. if (this._isFallbackRoot(translated)) {
  1236. if (!this._isSilentTranslationWarn(linkPlaceholder)) {
  1237. warn(("Fall back to translate the link placeholder '" + linkPlaceholder + "' with root locale."));
  1238. }
  1239. /* istanbul ignore if */
  1240. if (!this._root) { throw Error('unexpected error') }
  1241. var root = this._root.$i18n;
  1242. translated = root._translate(
  1243. root._getMessages(), root.locale, root.fallbackLocale,
  1244. linkPlaceholder, host, interpolateMode, values
  1245. );
  1246. }
  1247. translated = this._warnDefault(
  1248. locale, linkPlaceholder, translated, host,
  1249. Array.isArray(values) ? values : [values],
  1250. interpolateMode
  1251. );
  1252. if (this._modifiers.hasOwnProperty(formatterName)) {
  1253. translated = this._modifiers[formatterName](translated);
  1254. } else if (defaultModifiers.hasOwnProperty(formatterName)) {
  1255. translated = defaultModifiers[formatterName](translated);
  1256. }
  1257. visitedLinkStack.pop();
  1258. // Replace the link with the translated
  1259. ret = !translated ? ret : ret.replace(link, translated);
  1260. }
  1261. return ret
  1262. };
  1263. VueI18n.prototype._render = function _render (message, interpolateMode, values, path) {
  1264. var ret = this._formatter.interpolate(message, values, path);
  1265. // If the custom formatter refuses to work - apply the default one
  1266. if (!ret) {
  1267. ret = defaultFormatter.interpolate(message, values, path);
  1268. }
  1269. // if interpolateMode is **not** 'string' ('row'),
  1270. // return the compiled data (e.g. ['foo', VNode, 'bar']) with formatter
  1271. return interpolateMode === 'string' && typeof ret !== 'string' ? ret.join('') : ret
  1272. };
  1273. VueI18n.prototype._translate = function _translate (
  1274. messages,
  1275. locale,
  1276. fallback,
  1277. key,
  1278. host,
  1279. interpolateMode,
  1280. args
  1281. ) {
  1282. var res =
  1283. this._interpolate(locale, messages[locale], key, host, interpolateMode, args, [key]);
  1284. if (!isNull(res)) { return res }
  1285. res = this._interpolate(fallback, messages[fallback], key, host, interpolateMode, args, [key]);
  1286. if (!isNull(res)) {
  1287. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1288. warn(("Fall back to translate the keypath '" + key + "' with '" + fallback + "' locale."));
  1289. }
  1290. return res
  1291. } else {
  1292. return null
  1293. }
  1294. };
  1295. VueI18n.prototype._t = function _t (key, _locale, messages, host) {
  1296. var ref;
  1297. var values = [], len = arguments.length - 4;
  1298. while ( len-- > 0 ) values[ len ] = arguments[ len + 4 ];
  1299. if (!key) { return '' }
  1300. var parsedArgs = parseArgs.apply(void 0, values);
  1301. var locale = parsedArgs.locale || _locale;
  1302. var ret = this._translate(
  1303. messages, locale, this.fallbackLocale, key,
  1304. host, 'string', parsedArgs.params
  1305. );
  1306. if (this._isFallbackRoot(ret)) {
  1307. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1308. warn(("Fall back to translate the keypath '" + key + "' with root locale."));
  1309. }
  1310. /* istanbul ignore if */
  1311. if (!this._root) { throw Error('unexpected error') }
  1312. return (ref = this._root).$t.apply(ref, [ key ].concat( values ))
  1313. } else {
  1314. return this._warnDefault(locale, key, ret, host, values, 'string')
  1315. }
  1316. };
  1317. VueI18n.prototype.t = function t (key) {
  1318. var ref;
  1319. var values = [], len = arguments.length - 1;
  1320. while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ];
  1321. return (ref = this)._t.apply(ref, [ key, this.locale, this._getMessages(), null ].concat( values ))
  1322. };
  1323. VueI18n.prototype._i = function _i (key, locale, messages, host, values) {
  1324. var ret =
  1325. this._translate(messages, locale, this.fallbackLocale, key, host, 'raw', values);
  1326. if (this._isFallbackRoot(ret)) {
  1327. if (!this._isSilentTranslationWarn(key)) {
  1328. warn(("Fall back to interpolate the keypath '" + key + "' with root locale."));
  1329. }
  1330. if (!this._root) { throw Error('unexpected error') }
  1331. return this._root.$i18n.i(key, locale, values)
  1332. } else {
  1333. return this._warnDefault(locale, key, ret, host, [values], 'raw')
  1334. }
  1335. };
  1336. VueI18n.prototype.i = function i (key, locale, values) {
  1337. /* istanbul ignore if */
  1338. if (!key) { return '' }
  1339. if (typeof locale !== 'string') {
  1340. locale = this.locale;
  1341. }
  1342. return this._i(key, locale, this._getMessages(), null, values)
  1343. };
  1344. VueI18n.prototype._tc = function _tc (
  1345. key,
  1346. _locale,
  1347. messages,
  1348. host,
  1349. choice
  1350. ) {
  1351. var ref;
  1352. var values = [], len = arguments.length - 5;
  1353. while ( len-- > 0 ) values[ len ] = arguments[ len + 5 ];
  1354. if (!key) { return '' }
  1355. if (choice === undefined) {
  1356. choice = 1;
  1357. }
  1358. var predefined = { 'count': choice, 'n': choice };
  1359. var parsedArgs = parseArgs.apply(void 0, values);
  1360. parsedArgs.params = Object.assign(predefined, parsedArgs.params);
  1361. values = parsedArgs.locale === null ? [parsedArgs.params] : [parsedArgs.locale, parsedArgs.params];
  1362. return this.fetchChoice((ref = this)._t.apply(ref, [ key, _locale, messages, host ].concat( values )), choice)
  1363. };
  1364. VueI18n.prototype.fetchChoice = function fetchChoice (message, choice) {
  1365. /* istanbul ignore if */
  1366. if (!message && typeof message !== 'string') { return null }
  1367. var choices = message.split('|');
  1368. choice = this.getChoiceIndex(choice, choices.length);
  1369. if (!choices[choice]) { return message }
  1370. return choices[choice].trim()
  1371. };
  1372. /**
  1373. * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
  1374. * @param choicesLength {number} an overall amount of available choices
  1375. * @returns a final choice index
  1376. */
  1377. VueI18n.prototype.getChoiceIndex = function getChoiceIndex (choice, choicesLength) {
  1378. // Default (old) getChoiceIndex implementation - english-compatible
  1379. var defaultImpl = function (_choice, _choicesLength) {
  1380. _choice = Math.abs(_choice);
  1381. if (_choicesLength === 2) {
  1382. return _choice
  1383. ? _choice > 1
  1384. ? 1
  1385. : 0
  1386. : 1
  1387. }
  1388. return _choice ? Math.min(_choice, 2) : 0
  1389. };
  1390. if (this.locale in this.pluralizationRules) {
  1391. return this.pluralizationRules[this.locale].apply(this, [choice, choicesLength])
  1392. } else {
  1393. return defaultImpl(choice, choicesLength)
  1394. }
  1395. };
  1396. VueI18n.prototype.tc = function tc (key, choice) {
  1397. var ref;
  1398. var values = [], len = arguments.length - 2;
  1399. while ( len-- > 0 ) values[ len ] = arguments[ len + 2 ];
  1400. return (ref = this)._tc.apply(ref, [ key, this.locale, this._getMessages(), null, choice ].concat( values ))
  1401. };
  1402. VueI18n.prototype._te = function _te (key, locale, messages) {
  1403. var args = [], len = arguments.length - 3;
  1404. while ( len-- > 0 ) args[ len ] = arguments[ len + 3 ];
  1405. var _locale = parseArgs.apply(void 0, args).locale || locale;
  1406. return this._exist(messages[_locale], key)
  1407. };
  1408. VueI18n.prototype.te = function te (key, locale) {
  1409. return this._te(key, this.locale, this._getMessages(), locale)
  1410. };
  1411. VueI18n.prototype.getLocaleMessage = function getLocaleMessage (locale) {
  1412. return looseClone(this._vm.messages[locale] || {})
  1413. };
  1414. VueI18n.prototype.setLocaleMessage = function setLocaleMessage (locale, message) {
  1415. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  1416. this._checkLocaleMessage(locale, this._warnHtmlInMessage, message);
  1417. if (this._warnHtmlInMessage === 'error') { return }
  1418. }
  1419. this._vm.$set(this._vm.messages, locale, message);
  1420. };
  1421. VueI18n.prototype.mergeLocaleMessage = function mergeLocaleMessage (locale, message) {
  1422. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  1423. this._checkLocaleMessage(locale, this._warnHtmlInMessage, message);
  1424. if (this._warnHtmlInMessage === 'error') { return }
  1425. }
  1426. this._vm.$set(this._vm.messages, locale, merge({}, this._vm.messages[locale] || {}, message));
  1427. };
  1428. VueI18n.prototype.getDateTimeFormat = function getDateTimeFormat (locale) {
  1429. return looseClone(this._vm.dateTimeFormats[locale] || {})
  1430. };
  1431. VueI18n.prototype.setDateTimeFormat = function setDateTimeFormat (locale, format) {
  1432. this._vm.$set(this._vm.dateTimeFormats, locale, format);
  1433. };
  1434. VueI18n.prototype.mergeDateTimeFormat = function mergeDateTimeFormat (locale, format) {
  1435. this._vm.$set(this._vm.dateTimeFormats, locale, merge(this._vm.dateTimeFormats[locale] || {}, format));
  1436. };
  1437. VueI18n.prototype._localizeDateTime = function _localizeDateTime (
  1438. value,
  1439. locale,
  1440. fallback,
  1441. dateTimeFormats,
  1442. key
  1443. ) {
  1444. var _locale = locale;
  1445. var formats = dateTimeFormats[_locale];
  1446. // fallback locale
  1447. if (isNull(formats) || isNull(formats[key])) {
  1448. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1449. warn(("Fall back to '" + fallback + "' datetime formats from '" + locale + "' datetime formats."));
  1450. }
  1451. _locale = fallback;
  1452. formats = dateTimeFormats[_locale];
  1453. }
  1454. if (isNull(formats) || isNull(formats[key])) {
  1455. return null
  1456. } else {
  1457. var format = formats[key];
  1458. var id = _locale + "__" + key;
  1459. var formatter = this._dateTimeFormatters[id];
  1460. if (!formatter) {
  1461. formatter = this._dateTimeFormatters[id] = new Intl.DateTimeFormat(_locale, format);
  1462. }
  1463. return formatter.format(value)
  1464. }
  1465. };
  1466. VueI18n.prototype._d = function _d (value, locale, key) {
  1467. /* istanbul ignore if */
  1468. if (!VueI18n.availabilities.dateTimeFormat) {
  1469. warn('Cannot format a Date value due to not supported Intl.DateTimeFormat.');
  1470. return ''
  1471. }
  1472. if (!key) {
  1473. return new Intl.DateTimeFormat(locale).format(value)
  1474. }
  1475. var ret =
  1476. this._localizeDateTime(value, locale, this.fallbackLocale, this._getDateTimeFormats(), key);
  1477. if (this._isFallbackRoot(ret)) {
  1478. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1479. warn(("Fall back to datetime localization of root: key '" + key + "'."));
  1480. }
  1481. /* istanbul ignore if */
  1482. if (!this._root) { throw Error('unexpected error') }
  1483. return this._root.$i18n.d(value, key, locale)
  1484. } else {
  1485. return ret || ''
  1486. }
  1487. };
  1488. VueI18n.prototype.d = function d (value) {
  1489. var args = [], len = arguments.length - 1;
  1490. while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
  1491. var locale = this.locale;
  1492. var key = null;
  1493. if (args.length === 1) {
  1494. if (typeof args[0] === 'string') {
  1495. key = args[0];
  1496. } else if (isObject(args[0])) {
  1497. if (args[0].locale) {
  1498. locale = args[0].locale;
  1499. }
  1500. if (args[0].key) {
  1501. key = args[0].key;
  1502. }
  1503. }
  1504. } else if (args.length === 2) {
  1505. if (typeof args[0] === 'string') {
  1506. key = args[0];
  1507. }
  1508. if (typeof args[1] === 'string') {
  1509. locale = args[1];
  1510. }
  1511. }
  1512. return this._d(value, locale, key)
  1513. };
  1514. VueI18n.prototype.getNumberFormat = function getNumberFormat (locale) {
  1515. return looseClone(this._vm.numberFormats[locale] || {})
  1516. };
  1517. VueI18n.prototype.setNumberFormat = function setNumberFormat (locale, format) {
  1518. this._vm.$set(this._vm.numberFormats, locale, format);
  1519. };
  1520. VueI18n.prototype.mergeNumberFormat = function mergeNumberFormat (locale, format) {
  1521. this._vm.$set(this._vm.numberFormats, locale, merge(this._vm.numberFormats[locale] || {}, format));
  1522. };
  1523. VueI18n.prototype._getNumberFormatter = function _getNumberFormatter (
  1524. value,
  1525. locale,
  1526. fallback,
  1527. numberFormats,
  1528. key,
  1529. options
  1530. ) {
  1531. var _locale = locale;
  1532. var formats = numberFormats[_locale];
  1533. // fallback locale
  1534. if (isNull(formats) || isNull(formats[key])) {
  1535. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1536. warn(("Fall back to '" + fallback + "' number formats from '" + locale + "' number formats."));
  1537. }
  1538. _locale = fallback;
  1539. formats = numberFormats[_locale];
  1540. }
  1541. if (isNull(formats) || isNull(formats[key])) {
  1542. return null
  1543. } else {
  1544. var format = formats[key];
  1545. var formatter;
  1546. if (options) {
  1547. // If options specified - create one time number formatter
  1548. formatter = new Intl.NumberFormat(_locale, Object.assign({}, format, options));
  1549. } else {
  1550. var id = _locale + "__" + key;
  1551. formatter = this._numberFormatters[id];
  1552. if (!formatter) {
  1553. formatter = this._numberFormatters[id] = new Intl.NumberFormat(_locale, format);
  1554. }
  1555. }
  1556. return formatter
  1557. }
  1558. };
  1559. VueI18n.prototype._n = function _n (value, locale, key, options) {
  1560. /* istanbul ignore if */
  1561. if (!VueI18n.availabilities.numberFormat) {
  1562. {
  1563. warn('Cannot format a Number value due to not supported Intl.NumberFormat.');
  1564. }
  1565. return ''
  1566. }
  1567. if (!key) {
  1568. var nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options);
  1569. return nf.format(value)
  1570. }
  1571. var formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options);
  1572. var ret = formatter && formatter.format(value);
  1573. if (this._isFallbackRoot(ret)) {
  1574. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1575. warn(("Fall back to number localization of root: key '" + key + "'."));
  1576. }
  1577. /* istanbul ignore if */
  1578. if (!this._root) { throw Error('unexpected error') }
  1579. return this._root.$i18n.n(value, Object.assign({}, { key: key, locale: locale }, options))
  1580. } else {
  1581. return ret || ''
  1582. }
  1583. };
  1584. VueI18n.prototype.n = function n (value) {
  1585. var args = [], len = arguments.length - 1;
  1586. while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
  1587. var locale = this.locale;
  1588. var key = null;
  1589. var options = null;
  1590. if (args.length === 1) {
  1591. if (typeof args[0] === 'string') {
  1592. key = args[0];
  1593. } else if (isObject(args[0])) {
  1594. if (args[0].locale) {
  1595. locale = args[0].locale;
  1596. }
  1597. if (args[0].key) {
  1598. key = args[0].key;
  1599. }
  1600. // Filter out number format options only
  1601. options = Object.keys(args[0]).reduce(function (acc, key) {
  1602. var obj;
  1603. if (numberFormatKeys.includes(key)) {
  1604. return Object.assign({}, acc, ( obj = {}, obj[key] = args[0][key], obj ))
  1605. }
  1606. return acc
  1607. }, null);
  1608. }
  1609. } else if (args.length === 2) {
  1610. if (typeof args[0] === 'string') {
  1611. key = args[0];
  1612. }
  1613. if (typeof args[1] === 'string') {
  1614. locale = args[1];
  1615. }
  1616. }
  1617. return this._n(value, locale, key, options)
  1618. };
  1619. VueI18n.prototype._ntp = function _ntp (value, locale, key, options) {
  1620. /* istanbul ignore if */
  1621. if (!VueI18n.availabilities.numberFormat) {
  1622. {
  1623. warn('Cannot format to parts a Number value due to not supported Intl.NumberFormat.');
  1624. }
  1625. return []
  1626. }
  1627. if (!key) {
  1628. var nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options);
  1629. return nf.formatToParts(value)
  1630. }
  1631. var formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options);
  1632. var ret = formatter && formatter.formatToParts(value);
  1633. if (this._isFallbackRoot(ret)) {
  1634. if (!this._isSilentTranslationWarn(key)) {
  1635. warn(("Fall back to format number to parts of root: key '" + key + "' ."));
  1636. }
  1637. /* istanbul ignore if */
  1638. if (!this._root) { throw Error('unexpected error') }
  1639. return this._root.$i18n._ntp(value, locale, key, options)
  1640. } else {
  1641. return ret || []
  1642. }
  1643. };
  1644. Object.defineProperties( VueI18n.prototype, prototypeAccessors );
  1645. var availabilities;
  1646. // $FlowFixMe
  1647. Object.defineProperty(VueI18n, 'availabilities', {
  1648. get: function get () {
  1649. if (!availabilities) {
  1650. var intlDefined = typeof Intl !== 'undefined';
  1651. availabilities = {
  1652. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1653. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1654. };
  1655. }
  1656. return availabilities
  1657. }
  1658. });
  1659. VueI18n.install = install;
  1660. VueI18n.version = '8.15.5';
  1661. return VueI18n;
  1662. })));