vue-i18n.js 49 KB

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