vue-i18n.runtime.esm-bundler.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. /*!
  2. * vue-i18n v9.1.9
  3. * (c) 2021 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, hasOwn, isObject, isBoolean, isString, isRegExp, isFunction, assign, isNumber, warn, createEmitter, isEmptyObject } from '@intlify/shared';
  7. import { createCompileError, handleFlatJson, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, getLocaleChain, setDevToolsHook } from '@intlify/core-base';
  8. import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
  9. import { setupDevtoolsPlugin } from '@vue/devtools-api';
  10. import { VueDevToolsLabels, VueDevToolsPlaceholders, VueDevToolsTimelineColors } from '@intlify/vue-devtools';
  11. /**
  12. * Vue I18n Version
  13. *
  14. * @remarks
  15. * Semver format. Same format as the package.json `version` field.
  16. *
  17. * @VueI18nGeneral
  18. */
  19. const VERSION = '9.1.9';
  20. /**
  21. * This is only called in esm-bundler builds.
  22. * istanbul-ignore-next
  23. */
  24. function initFeatureFlags() {
  25. let needWarn = false;
  26. if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {
  27. needWarn = true;
  28. getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;
  29. }
  30. if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {
  31. needWarn = true;
  32. getGlobalThis().__VUE_I18N_LEGACY_API__ = true;
  33. }
  34. if (typeof __VUE_I18N_PROD_DEVTOOLS__ !== 'boolean') {
  35. needWarn = true;
  36. getGlobalThis().__VUE_I18N_PROD_DEVTOOLS__ = false;
  37. }
  38. if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
  39. getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
  40. }
  41. if ((process.env.NODE_ENV !== 'production') && typeof true === 'boolean') {
  42. needWarn = true;
  43. }
  44. if ((process.env.NODE_ENV !== 'production') && needWarn) {
  45. console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` +
  46. `configure your bundler to explicitly replace feature flag globals ` +
  47. `with boolean literals to get proper tree-shaking in the final bundle.`);
  48. }
  49. }
  50. const warnMessages = {
  51. [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
  52. [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`,
  53. [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`,
  54. [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`,
  55. [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`,
  56. [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  57. [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
  58. };
  59. function getWarnMessage(code, ...args) {
  60. return format(warnMessages[code], ...args);
  61. }
  62. function createI18nError(code, ...args) {
  63. return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);
  64. }
  65. const errorMessages = {
  66. [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
  67. [15 /* INVALID_ARGUMENT */]: 'Invalid argument',
  68. [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
  69. [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
  70. [22 /* UNEXPECTED_ERROR */]: 'Unexpected error',
  71. [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
  72. [19 /* REQUIRED_VALUE */]: `Required in value: {0}`,
  73. [20 /* INVALID_VALUE */]: `Invalid value`,
  74. [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
  75. };
  76. const DEVTOOLS_META = '__INTLIFY_META__';
  77. const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
  78. const DatetimePartsSymbol = makeSymbol('__datetimeParts');
  79. const NumberPartsSymbol = makeSymbol('__numberParts');
  80. const EnableEmitter = makeSymbol('__enableEmitter');
  81. const DisableEmitter = makeSymbol('__disableEmitter');
  82. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  83. makeSymbol('__intlifyMeta');
  84. const InejctWithOption = makeSymbol('__injectWithOption');
  85. let composerID = 0;
  86. function defineCoreMissingHandler(missing) {
  87. return ((ctx, locale, key, type) => {
  88. return missing(locale, key, getCurrentInstance() || undefined, type);
  89. });
  90. }
  91. function getLocaleMessages(locale, options) {
  92. const { messages, __i18n } = options;
  93. // prettier-ignore
  94. const ret = isPlainObject(messages)
  95. ? messages
  96. : isArray(__i18n)
  97. ? {}
  98. : { [locale]: {} };
  99. // merge locale messages of i18n custom block
  100. if (isArray(__i18n)) {
  101. __i18n.forEach(({ locale, resource }) => {
  102. if (locale) {
  103. ret[locale] = ret[locale] || {};
  104. deepCopy(resource, ret[locale]);
  105. }
  106. else {
  107. deepCopy(resource, ret);
  108. }
  109. });
  110. }
  111. // handle messages for flat json
  112. if (options.flatJson) {
  113. for (const key in ret) {
  114. if (hasOwn(ret, key)) {
  115. handleFlatJson(ret[key]);
  116. }
  117. }
  118. }
  119. return ret;
  120. }
  121. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  122. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  123. function deepCopy(src, des) {
  124. // src and des should both be objects, and non of then can be a array
  125. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  126. throw createI18nError(20 /* INVALID_VALUE */);
  127. }
  128. for (const key in src) {
  129. if (hasOwn(src, key)) {
  130. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  131. // replace with src[key] when:
  132. // src[key] or des[key] is not a object, or
  133. // src[key] or des[key] is a array
  134. des[key] = src[key];
  135. }
  136. else {
  137. // src[key] and des[key] are both object, merge them
  138. deepCopy(src[key], des[key]);
  139. }
  140. }
  141. }
  142. }
  143. // for Intlify DevTools
  144. const getMetaInfo = /* #__PURE__*/ () => {
  145. const instance = getCurrentInstance();
  146. return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any
  147. ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any
  148. : null;
  149. };
  150. /**
  151. * Create composer interface factory
  152. *
  153. * @internal
  154. */
  155. function createComposer(options = {}) {
  156. const { __root } = options;
  157. const _isGlobal = __root === undefined;
  158. let _inheritLocale = isBoolean(options.inheritLocale)
  159. ? options.inheritLocale
  160. : true;
  161. const _locale = ref(
  162. // prettier-ignore
  163. __root && _inheritLocale
  164. ? __root.locale.value
  165. : isString(options.locale)
  166. ? options.locale
  167. : 'en-US');
  168. const _fallbackLocale = ref(
  169. // prettier-ignore
  170. __root && _inheritLocale
  171. ? __root.fallbackLocale.value
  172. : isString(options.fallbackLocale) ||
  173. isArray(options.fallbackLocale) ||
  174. isPlainObject(options.fallbackLocale) ||
  175. options.fallbackLocale === false
  176. ? options.fallbackLocale
  177. : _locale.value);
  178. const _messages = ref(getLocaleMessages(_locale.value, options));
  179. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  180. ? options.datetimeFormats
  181. : { [_locale.value]: {} });
  182. const _numberFormats = ref(isPlainObject(options.numberFormats)
  183. ? options.numberFormats
  184. : { [_locale.value]: {} });
  185. // warning suppress options
  186. // prettier-ignore
  187. let _missingWarn = __root
  188. ? __root.missingWarn
  189. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  190. ? options.missingWarn
  191. : true;
  192. // prettier-ignore
  193. let _fallbackWarn = __root
  194. ? __root.fallbackWarn
  195. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  196. ? options.fallbackWarn
  197. : true;
  198. // prettier-ignore
  199. let _fallbackRoot = __root
  200. ? __root.fallbackRoot
  201. : isBoolean(options.fallbackRoot)
  202. ? options.fallbackRoot
  203. : true;
  204. // configure fall back to root
  205. let _fallbackFormat = !!options.fallbackFormat;
  206. // runtime missing
  207. let _missing = isFunction(options.missing) ? options.missing : null;
  208. let _runtimeMissing = isFunction(options.missing)
  209. ? defineCoreMissingHandler(options.missing)
  210. : null;
  211. // postTranslation handler
  212. let _postTranslation = isFunction(options.postTranslation)
  213. ? options.postTranslation
  214. : null;
  215. let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  216. ? options.warnHtmlMessage
  217. : true;
  218. let _escapeParameter = !!options.escapeParameter;
  219. // custom linked modifiers
  220. // prettier-ignore
  221. const _modifiers = __root
  222. ? __root.modifiers
  223. : isPlainObject(options.modifiers)
  224. ? options.modifiers
  225. : {};
  226. // pluralRules
  227. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  228. // runtime context
  229. // eslint-disable-next-line prefer-const
  230. let _context;
  231. function getCoreContext() {
  232. return createCoreContext({
  233. version: VERSION,
  234. locale: _locale.value,
  235. fallbackLocale: _fallbackLocale.value,
  236. messages: _messages.value,
  237. datetimeFormats: _datetimeFormats.value,
  238. numberFormats: _numberFormats.value,
  239. modifiers: _modifiers,
  240. pluralRules: _pluralRules,
  241. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  242. missingWarn: _missingWarn,
  243. fallbackWarn: _fallbackWarn,
  244. fallbackFormat: _fallbackFormat,
  245. unresolving: true,
  246. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  247. warnHtmlMessage: _warnHtmlMessage,
  248. escapeParameter: _escapeParameter,
  249. __datetimeFormatters: isPlainObject(_context)
  250. ? _context.__datetimeFormatters
  251. : undefined,
  252. __numberFormatters: isPlainObject(_context)
  253. ? _context.__numberFormatters
  254. : undefined,
  255. __v_emitter: isPlainObject(_context)
  256. ? _context.__v_emitter
  257. : undefined,
  258. __meta: { framework: 'vue' }
  259. });
  260. }
  261. _context = getCoreContext();
  262. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  263. // track reactivity
  264. function trackReactivityValues() {
  265. return [
  266. _locale.value,
  267. _fallbackLocale.value,
  268. _messages.value,
  269. _datetimeFormats.value,
  270. _numberFormats.value
  271. ];
  272. }
  273. // locale
  274. const locale = computed({
  275. get: () => _locale.value,
  276. set: val => {
  277. _locale.value = val;
  278. _context.locale = _locale.value;
  279. }
  280. });
  281. // fallbackLocale
  282. const fallbackLocale = computed({
  283. get: () => _fallbackLocale.value,
  284. set: val => {
  285. _fallbackLocale.value = val;
  286. _context.fallbackLocale = _fallbackLocale.value;
  287. updateFallbackLocale(_context, _locale.value, val);
  288. }
  289. });
  290. // messages
  291. const messages = computed(() => _messages.value);
  292. // datetimeFormats
  293. const datetimeFormats = computed(() => _datetimeFormats.value);
  294. // numberFormats
  295. const numberFormats = computed(() => _numberFormats.value);
  296. // getPostTranslationHandler
  297. function getPostTranslationHandler() {
  298. return isFunction(_postTranslation) ? _postTranslation : null;
  299. }
  300. // setPostTranslationHandler
  301. function setPostTranslationHandler(handler) {
  302. _postTranslation = handler;
  303. _context.postTranslation = handler;
  304. }
  305. // getMissingHandler
  306. function getMissingHandler() {
  307. return _missing;
  308. }
  309. // setMissingHandler
  310. function setMissingHandler(handler) {
  311. if (handler !== null) {
  312. _runtimeMissing = defineCoreMissingHandler(handler);
  313. }
  314. _missing = handler;
  315. _context.missing = _runtimeMissing;
  316. }
  317. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  318. ) {
  319. return type !== 'translate' || !!arg.resolvedMessage === false;
  320. }
  321. function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
  322. trackReactivityValues(); // track reactive dependency
  323. // NOTE: experimental !!
  324. let ret;
  325. if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
  326. try {
  327. setAdditionalMeta(getMetaInfo());
  328. ret = fn(_context);
  329. }
  330. finally {
  331. setAdditionalMeta(null);
  332. }
  333. }
  334. else {
  335. ret = fn(_context);
  336. }
  337. if (isNumber(ret) && ret === NOT_REOSLVED) {
  338. const [key, arg2] = argumentParser();
  339. if ((process.env.NODE_ENV !== 'production') &&
  340. __root &&
  341. isString(key) &&
  342. isResolvedTranslateMessage(warnType, arg2)) {
  343. if (_fallbackRoot &&
  344. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  345. isTranslateMissingWarn(_missingWarn, key))) {
  346. warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
  347. key,
  348. type: warnType
  349. }));
  350. }
  351. // for vue-devtools timeline event
  352. if ((process.env.NODE_ENV !== 'production')) {
  353. const { __v_emitter: emitter } = _context;
  354. if (emitter && _fallbackRoot) {
  355. emitter.emit("fallback" /* FALBACK */, {
  356. type: warnType,
  357. key,
  358. to: 'global',
  359. groupId: `${warnType}:${key}`
  360. });
  361. }
  362. }
  363. }
  364. return __root && _fallbackRoot
  365. ? fallbackSuccess(__root)
  366. : fallbackFail(key);
  367. }
  368. else if (successCondition(ret)) {
  369. return ret;
  370. }
  371. else {
  372. /* istanbul ignore next */
  373. throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */);
  374. }
  375. }
  376. // t
  377. function t(...args) {
  378. return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val));
  379. }
  380. // rt
  381. function rt(...args) {
  382. const [arg1, arg2, arg3] = args;
  383. if (arg3 && !isObject(arg3)) {
  384. throw createI18nError(15 /* INVALID_ARGUMENT */);
  385. }
  386. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  387. }
  388. // d
  389. function d(...args) {
  390. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  391. }
  392. // n
  393. function n(...args) {
  394. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  395. }
  396. // for custom processor
  397. function normalize(values) {
  398. return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
  399. }
  400. const interpolate = (val) => val;
  401. const processor = {
  402. normalize,
  403. interpolate,
  404. type: 'vnode'
  405. };
  406. // transrateVNode, using for `i18n-t` component
  407. function transrateVNode(...args) {
  408. return wrapWithDeps(context => {
  409. let ret;
  410. const _context = context;
  411. try {
  412. _context.processor = processor;
  413. ret = translate(_context, ...args);
  414. }
  415. finally {
  416. _context.processor = null;
  417. }
  418. return ret;
  419. }, () => parseTranslateArgs(...args), 'translate',
  420. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  421. root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
  422. }
  423. // numberParts, using for `i18n-n` component
  424. function numberParts(...args) {
  425. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format',
  426. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  427. root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  428. }
  429. // datetimeParts, using for `i18n-d` component
  430. function datetimeParts(...args) {
  431. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format',
  432. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  433. root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  434. }
  435. function setPluralRules(rules) {
  436. _pluralRules = rules;
  437. _context.pluralRules = _pluralRules;
  438. }
  439. // te
  440. function te(key, locale) {
  441. const targetLocale = isString(locale) ? locale : _locale.value;
  442. const message = getLocaleMessage(targetLocale);
  443. return resolveValue(message, key) !== null;
  444. }
  445. function resolveMessages(key) {
  446. let messages = null;
  447. const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value);
  448. for (let i = 0; i < locales.length; i++) {
  449. const targetLocaleMessages = _messages.value[locales[i]] || {};
  450. const messageValue = resolveValue(targetLocaleMessages, key);
  451. if (messageValue != null) {
  452. messages = messageValue;
  453. break;
  454. }
  455. }
  456. return messages;
  457. }
  458. // tm
  459. function tm(key) {
  460. const messages = resolveMessages(key);
  461. // prettier-ignore
  462. return messages != null
  463. ? messages
  464. : __root
  465. ? __root.tm(key) || {}
  466. : {};
  467. }
  468. // getLocaleMessage
  469. function getLocaleMessage(locale) {
  470. return (_messages.value[locale] || {});
  471. }
  472. // setLocaleMessage
  473. function setLocaleMessage(locale, message) {
  474. _messages.value[locale] = message;
  475. _context.messages = _messages.value;
  476. }
  477. // mergeLocaleMessage
  478. function mergeLocaleMessage(locale, message) {
  479. _messages.value[locale] = _messages.value[locale] || {};
  480. deepCopy(message, _messages.value[locale]);
  481. _context.messages = _messages.value;
  482. }
  483. // getDateTimeFormat
  484. function getDateTimeFormat(locale) {
  485. return _datetimeFormats.value[locale] || {};
  486. }
  487. // setDateTimeFormat
  488. function setDateTimeFormat(locale, format) {
  489. _datetimeFormats.value[locale] = format;
  490. _context.datetimeFormats = _datetimeFormats.value;
  491. clearDateTimeFormat(_context, locale, format);
  492. }
  493. // mergeDateTimeFormat
  494. function mergeDateTimeFormat(locale, format) {
  495. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  496. _context.datetimeFormats = _datetimeFormats.value;
  497. clearDateTimeFormat(_context, locale, format);
  498. }
  499. // getNumberFormat
  500. function getNumberFormat(locale) {
  501. return _numberFormats.value[locale] || {};
  502. }
  503. // setNumberFormat
  504. function setNumberFormat(locale, format) {
  505. _numberFormats.value[locale] = format;
  506. _context.numberFormats = _numberFormats.value;
  507. clearNumberFormat(_context, locale, format);
  508. }
  509. // mergeNumberFormat
  510. function mergeNumberFormat(locale, format) {
  511. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  512. _context.numberFormats = _numberFormats.value;
  513. clearNumberFormat(_context, locale, format);
  514. }
  515. // for debug
  516. composerID++;
  517. // watch root locale & fallbackLocale
  518. if (__root) {
  519. watch(__root.locale, (val) => {
  520. if (_inheritLocale) {
  521. _locale.value = val;
  522. _context.locale = val;
  523. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  524. }
  525. });
  526. watch(__root.fallbackLocale, (val) => {
  527. if (_inheritLocale) {
  528. _fallbackLocale.value = val;
  529. _context.fallbackLocale = val;
  530. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  531. }
  532. });
  533. }
  534. // define composition API!
  535. const composer = {
  536. id: composerID,
  537. locale,
  538. fallbackLocale,
  539. get inheritLocale() {
  540. return _inheritLocale;
  541. },
  542. set inheritLocale(val) {
  543. _inheritLocale = val;
  544. if (val && __root) {
  545. _locale.value = __root.locale.value;
  546. _fallbackLocale.value = __root.fallbackLocale.value;
  547. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  548. }
  549. },
  550. get availableLocales() {
  551. return Object.keys(_messages.value).sort();
  552. },
  553. messages,
  554. datetimeFormats,
  555. numberFormats,
  556. get modifiers() {
  557. return _modifiers;
  558. },
  559. get pluralRules() {
  560. return _pluralRules || {};
  561. },
  562. get isGlobal() {
  563. return _isGlobal;
  564. },
  565. get missingWarn() {
  566. return _missingWarn;
  567. },
  568. set missingWarn(val) {
  569. _missingWarn = val;
  570. _context.missingWarn = _missingWarn;
  571. },
  572. get fallbackWarn() {
  573. return _fallbackWarn;
  574. },
  575. set fallbackWarn(val) {
  576. _fallbackWarn = val;
  577. _context.fallbackWarn = _fallbackWarn;
  578. },
  579. get fallbackRoot() {
  580. return _fallbackRoot;
  581. },
  582. set fallbackRoot(val) {
  583. _fallbackRoot = val;
  584. },
  585. get fallbackFormat() {
  586. return _fallbackFormat;
  587. },
  588. set fallbackFormat(val) {
  589. _fallbackFormat = val;
  590. _context.fallbackFormat = _fallbackFormat;
  591. },
  592. get warnHtmlMessage() {
  593. return _warnHtmlMessage;
  594. },
  595. set warnHtmlMessage(val) {
  596. _warnHtmlMessage = val;
  597. _context.warnHtmlMessage = val;
  598. },
  599. get escapeParameter() {
  600. return _escapeParameter;
  601. },
  602. set escapeParameter(val) {
  603. _escapeParameter = val;
  604. _context.escapeParameter = val;
  605. },
  606. t,
  607. rt,
  608. d,
  609. n,
  610. te,
  611. tm,
  612. getLocaleMessage,
  613. setLocaleMessage,
  614. mergeLocaleMessage,
  615. getDateTimeFormat,
  616. setDateTimeFormat,
  617. mergeDateTimeFormat,
  618. getNumberFormat,
  619. setNumberFormat,
  620. mergeNumberFormat,
  621. getPostTranslationHandler,
  622. setPostTranslationHandler,
  623. getMissingHandler,
  624. setMissingHandler,
  625. [TransrateVNodeSymbol]: transrateVNode,
  626. [NumberPartsSymbol]: numberParts,
  627. [DatetimePartsSymbol]: datetimeParts,
  628. [SetPluralRulesSymbol]: setPluralRules,
  629. [InejctWithOption]: options.__injectWithOption // eslint-disable-line @typescript-eslint/no-explicit-any
  630. };
  631. // for vue-devtools timeline event
  632. if ((process.env.NODE_ENV !== 'production')) {
  633. composer[EnableEmitter] = (emitter) => {
  634. _context.__v_emitter = emitter;
  635. };
  636. composer[DisableEmitter] = () => {
  637. _context.__v_emitter = undefined;
  638. };
  639. }
  640. return composer;
  641. }
  642. /**
  643. * Convert to I18n Composer Options from VueI18n Options
  644. *
  645. * @internal
  646. */
  647. function convertComposerOptions(options) {
  648. const locale = isString(options.locale) ? options.locale : 'en-US';
  649. const fallbackLocale = isString(options.fallbackLocale) ||
  650. isArray(options.fallbackLocale) ||
  651. isPlainObject(options.fallbackLocale) ||
  652. options.fallbackLocale === false
  653. ? options.fallbackLocale
  654. : locale;
  655. const missing = isFunction(options.missing) ? options.missing : undefined;
  656. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  657. isRegExp(options.silentTranslationWarn)
  658. ? !options.silentTranslationWarn
  659. : true;
  660. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  661. isRegExp(options.silentFallbackWarn)
  662. ? !options.silentFallbackWarn
  663. : true;
  664. const fallbackRoot = isBoolean(options.fallbackRoot)
  665. ? options.fallbackRoot
  666. : true;
  667. const fallbackFormat = !!options.formatFallbackMessages;
  668. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  669. const pluralizationRules = options.pluralizationRules;
  670. const postTranslation = isFunction(options.postTranslation)
  671. ? options.postTranslation
  672. : undefined;
  673. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  674. ? options.warnHtmlInMessage !== 'off'
  675. : true;
  676. const escapeParameter = !!options.escapeParameterHtml;
  677. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  678. if ((process.env.NODE_ENV !== 'production') && options.formatter) {
  679. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  680. }
  681. if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {
  682. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  683. }
  684. let messages = options.messages;
  685. if (isPlainObject(options.sharedMessages)) {
  686. const sharedMessages = options.sharedMessages;
  687. const locales = Object.keys(sharedMessages);
  688. messages = locales.reduce((messages, locale) => {
  689. const message = messages[locale] || (messages[locale] = {});
  690. assign(message, sharedMessages[locale]);
  691. return messages;
  692. }, (messages || {}));
  693. }
  694. const { __i18n, __root, __injectWithOption } = options;
  695. const datetimeFormats = options.datetimeFormats;
  696. const numberFormats = options.numberFormats;
  697. const flatJson = options.flatJson;
  698. return {
  699. locale,
  700. fallbackLocale,
  701. messages,
  702. flatJson,
  703. datetimeFormats,
  704. numberFormats,
  705. missing,
  706. missingWarn,
  707. fallbackWarn,
  708. fallbackRoot,
  709. fallbackFormat,
  710. modifiers,
  711. pluralRules: pluralizationRules,
  712. postTranslation,
  713. warnHtmlMessage,
  714. escapeParameter,
  715. inheritLocale,
  716. __i18n,
  717. __root,
  718. __injectWithOption
  719. };
  720. }
  721. /**
  722. * create VueI18n interface factory
  723. *
  724. * @internal
  725. */
  726. function createVueI18n(options = {}) {
  727. const composer = createComposer(convertComposerOptions(options));
  728. // defines VueI18n
  729. const vueI18n = {
  730. // id
  731. id: composer.id,
  732. // locale
  733. get locale() {
  734. return composer.locale.value;
  735. },
  736. set locale(val) {
  737. composer.locale.value = val;
  738. },
  739. // fallbackLocale
  740. get fallbackLocale() {
  741. return composer.fallbackLocale.value;
  742. },
  743. set fallbackLocale(val) {
  744. composer.fallbackLocale.value = val;
  745. },
  746. // messages
  747. get messages() {
  748. return composer.messages.value;
  749. },
  750. // datetimeFormats
  751. get datetimeFormats() {
  752. return composer.datetimeFormats.value;
  753. },
  754. // numberFormats
  755. get numberFormats() {
  756. return composer.numberFormats.value;
  757. },
  758. // availableLocales
  759. get availableLocales() {
  760. return composer.availableLocales;
  761. },
  762. // formatter
  763. get formatter() {
  764. (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  765. // dummy
  766. return {
  767. interpolate() {
  768. return [];
  769. }
  770. };
  771. },
  772. set formatter(val) {
  773. (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  774. },
  775. // missing
  776. get missing() {
  777. return composer.getMissingHandler();
  778. },
  779. set missing(handler) {
  780. composer.setMissingHandler(handler);
  781. },
  782. // silentTranslationWarn
  783. get silentTranslationWarn() {
  784. return isBoolean(composer.missingWarn)
  785. ? !composer.missingWarn
  786. : composer.missingWarn;
  787. },
  788. set silentTranslationWarn(val) {
  789. composer.missingWarn = isBoolean(val) ? !val : val;
  790. },
  791. // silentFallbackWarn
  792. get silentFallbackWarn() {
  793. return isBoolean(composer.fallbackWarn)
  794. ? !composer.fallbackWarn
  795. : composer.fallbackWarn;
  796. },
  797. set silentFallbackWarn(val) {
  798. composer.fallbackWarn = isBoolean(val) ? !val : val;
  799. },
  800. // modifiers
  801. get modifiers() {
  802. return composer.modifiers;
  803. },
  804. // formatFallbackMessages
  805. get formatFallbackMessages() {
  806. return composer.fallbackFormat;
  807. },
  808. set formatFallbackMessages(val) {
  809. composer.fallbackFormat = val;
  810. },
  811. // postTranslation
  812. get postTranslation() {
  813. return composer.getPostTranslationHandler();
  814. },
  815. set postTranslation(handler) {
  816. composer.setPostTranslationHandler(handler);
  817. },
  818. // sync
  819. get sync() {
  820. return composer.inheritLocale;
  821. },
  822. set sync(val) {
  823. composer.inheritLocale = val;
  824. },
  825. // warnInHtmlMessage
  826. get warnHtmlInMessage() {
  827. return composer.warnHtmlMessage ? 'warn' : 'off';
  828. },
  829. set warnHtmlInMessage(val) {
  830. composer.warnHtmlMessage = val !== 'off';
  831. },
  832. // escapeParameterHtml
  833. get escapeParameterHtml() {
  834. return composer.escapeParameter;
  835. },
  836. set escapeParameterHtml(val) {
  837. composer.escapeParameter = val;
  838. },
  839. // preserveDirectiveContent
  840. get preserveDirectiveContent() {
  841. (process.env.NODE_ENV !== 'production') &&
  842. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  843. return true;
  844. },
  845. set preserveDirectiveContent(val) {
  846. (process.env.NODE_ENV !== 'production') &&
  847. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  848. },
  849. // pluralizationRules
  850. get pluralizationRules() {
  851. return composer.pluralRules || {};
  852. },
  853. // for internal
  854. __composer: composer,
  855. // t
  856. t(...args) {
  857. const [arg1, arg2, arg3] = args;
  858. const options = {};
  859. let list = null;
  860. let named = null;
  861. if (!isString(arg1)) {
  862. throw createI18nError(15 /* INVALID_ARGUMENT */);
  863. }
  864. const key = arg1;
  865. if (isString(arg2)) {
  866. options.locale = arg2;
  867. }
  868. else if (isArray(arg2)) {
  869. list = arg2;
  870. }
  871. else if (isPlainObject(arg2)) {
  872. named = arg2;
  873. }
  874. if (isArray(arg3)) {
  875. list = arg3;
  876. }
  877. else if (isPlainObject(arg3)) {
  878. named = arg3;
  879. }
  880. return composer.t(key, list || named || {}, options);
  881. },
  882. rt(...args) {
  883. return composer.rt(...args);
  884. },
  885. // tc
  886. tc(...args) {
  887. const [arg1, arg2, arg3] = args;
  888. const options = { plural: 1 };
  889. let list = null;
  890. let named = null;
  891. if (!isString(arg1)) {
  892. throw createI18nError(15 /* INVALID_ARGUMENT */);
  893. }
  894. const key = arg1;
  895. if (isString(arg2)) {
  896. options.locale = arg2;
  897. }
  898. else if (isNumber(arg2)) {
  899. options.plural = arg2;
  900. }
  901. else if (isArray(arg2)) {
  902. list = arg2;
  903. }
  904. else if (isPlainObject(arg2)) {
  905. named = arg2;
  906. }
  907. if (isString(arg3)) {
  908. options.locale = arg3;
  909. }
  910. else if (isArray(arg3)) {
  911. list = arg3;
  912. }
  913. else if (isPlainObject(arg3)) {
  914. named = arg3;
  915. }
  916. return composer.t(key, list || named || {}, options);
  917. },
  918. // te
  919. te(key, locale) {
  920. return composer.te(key, locale);
  921. },
  922. // tm
  923. tm(key) {
  924. return composer.tm(key);
  925. },
  926. // getLocaleMessage
  927. getLocaleMessage(locale) {
  928. return composer.getLocaleMessage(locale);
  929. },
  930. // setLocaleMessage
  931. setLocaleMessage(locale, message) {
  932. composer.setLocaleMessage(locale, message);
  933. },
  934. // mergeLocaleMessage
  935. mergeLocaleMessage(locale, message) {
  936. composer.mergeLocaleMessage(locale, message);
  937. },
  938. // d
  939. d(...args) {
  940. return composer.d(...args);
  941. },
  942. // getDateTimeFormat
  943. getDateTimeFormat(locale) {
  944. return composer.getDateTimeFormat(locale);
  945. },
  946. // setDateTimeFormat
  947. setDateTimeFormat(locale, format) {
  948. composer.setDateTimeFormat(locale, format);
  949. },
  950. // mergeDateTimeFormat
  951. mergeDateTimeFormat(locale, format) {
  952. composer.mergeDateTimeFormat(locale, format);
  953. },
  954. // n
  955. n(...args) {
  956. return composer.n(...args);
  957. },
  958. // getNumberFormat
  959. getNumberFormat(locale) {
  960. return composer.getNumberFormat(locale);
  961. },
  962. // setNumberFormat
  963. setNumberFormat(locale, format) {
  964. composer.setNumberFormat(locale, format);
  965. },
  966. // mergeNumberFormat
  967. mergeNumberFormat(locale, format) {
  968. composer.mergeNumberFormat(locale, format);
  969. },
  970. // getChoiceIndex
  971. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  972. getChoiceIndex(choice, choicesLength) {
  973. (process.env.NODE_ENV !== 'production') &&
  974. warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
  975. return -1;
  976. },
  977. // for internal
  978. __onComponentInstanceCreated(target) {
  979. const { componentInstanceCreatedListener } = options;
  980. if (componentInstanceCreatedListener) {
  981. componentInstanceCreatedListener(target, vueI18n);
  982. }
  983. }
  984. };
  985. // for vue-devtools timeline event
  986. if ((process.env.NODE_ENV !== 'production')) {
  987. vueI18n.__enableEmitter = (emitter) => {
  988. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  989. const __composer = composer;
  990. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  991. };
  992. vueI18n.__disableEmitter = () => {
  993. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  994. const __composer = composer;
  995. __composer[DisableEmitter] && __composer[DisableEmitter]();
  996. };
  997. }
  998. return vueI18n;
  999. }
  1000. const baseFormatProps = {
  1001. tag: {
  1002. type: [String, Object]
  1003. },
  1004. locale: {
  1005. type: String
  1006. },
  1007. scope: {
  1008. type: String,
  1009. validator: (val) => val === 'parent' || val === 'global',
  1010. default: 'parent'
  1011. },
  1012. i18n: {
  1013. type: Object
  1014. }
  1015. };
  1016. /**
  1017. * Translation Component
  1018. *
  1019. * @remarks
  1020. * See the following items for property about details
  1021. *
  1022. * @VueI18nSee [TranslationProps](component#translationprops)
  1023. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1024. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  1025. *
  1026. * @example
  1027. * ```html
  1028. * <div id="app">
  1029. * <!-- ... -->
  1030. * <i18n path="term" tag="label" for="tos">
  1031. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  1032. * </i18n>
  1033. * <!-- ... -->
  1034. * </div>
  1035. * ```
  1036. * ```js
  1037. * import { createApp } from 'vue'
  1038. * import { createI18n } from 'vue-i18n'
  1039. *
  1040. * const messages = {
  1041. * en: {
  1042. * tos: 'Term of Service',
  1043. * term: 'I accept xxx {0}.'
  1044. * },
  1045. * ja: {
  1046. * tos: '利用規約',
  1047. * term: '私は xxx の{0}に同意します。'
  1048. * }
  1049. * }
  1050. *
  1051. * const i18n = createI18n({
  1052. * locale: 'en',
  1053. * messages
  1054. * })
  1055. *
  1056. * const app = createApp({
  1057. * data: {
  1058. * url: '/term'
  1059. * }
  1060. * }).use(i18n).mount('#app')
  1061. * ```
  1062. *
  1063. * @VueI18nComponent
  1064. */
  1065. const Translation = {
  1066. /* eslint-disable */
  1067. name: 'i18n-t',
  1068. props: assign({
  1069. keypath: {
  1070. type: String,
  1071. required: true
  1072. },
  1073. plural: {
  1074. type: [Number, String],
  1075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1076. validator: (val) => isNumber(val) || !isNaN(val)
  1077. }
  1078. }, baseFormatProps),
  1079. /* eslint-enable */
  1080. setup(props, context) {
  1081. const { slots, attrs } = context;
  1082. const i18n = props.i18n ||
  1083. useI18n({
  1084. useScope: props.scope,
  1085. __useComponent: true
  1086. });
  1087. const keys = Object.keys(slots).filter(key => key !== '_');
  1088. return () => {
  1089. const options = {};
  1090. if (props.locale) {
  1091. options.locale = props.locale;
  1092. }
  1093. if (props.plural !== undefined) {
  1094. options.plural = isString(props.plural) ? +props.plural : props.plural;
  1095. }
  1096. const arg = getInterpolateArg(context, keys);
  1097. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1098. const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
  1099. const assignedAttrs = assign({}, attrs);
  1100. // prettier-ignore
  1101. return isString(props.tag)
  1102. ? h(props.tag, assignedAttrs, children)
  1103. : isObject(props.tag)
  1104. ? h(props.tag, assignedAttrs, children)
  1105. : h(Fragment, assignedAttrs, children);
  1106. };
  1107. }
  1108. };
  1109. function getInterpolateArg({ slots }, keys) {
  1110. if (keys.length === 1 && keys[0] === 'default') {
  1111. // default slot only
  1112. return slots.default ? slots.default() : [];
  1113. }
  1114. else {
  1115. // named slots
  1116. return keys.reduce((arg, key) => {
  1117. const slot = slots[key];
  1118. if (slot) {
  1119. arg[key] = slot();
  1120. }
  1121. return arg;
  1122. }, {});
  1123. }
  1124. }
  1125. function renderFormatter(props, context, slotKeys, partFormatter) {
  1126. const { slots, attrs } = context;
  1127. return () => {
  1128. const options = { part: true };
  1129. let overrides = {};
  1130. if (props.locale) {
  1131. options.locale = props.locale;
  1132. }
  1133. if (isString(props.format)) {
  1134. options.key = props.format;
  1135. }
  1136. else if (isObject(props.format)) {
  1137. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1138. if (isString(props.format.key)) {
  1139. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1140. options.key = props.format.key;
  1141. }
  1142. // Filter out number format options only
  1143. overrides = Object.keys(props.format).reduce((options, prop) => {
  1144. return slotKeys.includes(prop)
  1145. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  1146. : options;
  1147. }, {});
  1148. }
  1149. const parts = partFormatter(...[props.value, options, overrides]);
  1150. let children = [options.key];
  1151. if (isArray(parts)) {
  1152. children = parts.map((part, index) => {
  1153. const slot = slots[part.type];
  1154. return slot
  1155. ? slot({ [part.type]: part.value, index, parts })
  1156. : [part.value];
  1157. });
  1158. }
  1159. else if (isString(parts)) {
  1160. children = [parts];
  1161. }
  1162. const assignedAttrs = assign({}, attrs);
  1163. // prettier-ignore
  1164. return isString(props.tag)
  1165. ? h(props.tag, assignedAttrs, children)
  1166. : isObject(props.tag)
  1167. ? h(props.tag, assignedAttrs, children)
  1168. : h(Fragment, assignedAttrs, children);
  1169. };
  1170. }
  1171. const NUMBER_FORMAT_KEYS = [
  1172. 'localeMatcher',
  1173. 'style',
  1174. 'unit',
  1175. 'unitDisplay',
  1176. 'currency',
  1177. 'currencyDisplay',
  1178. 'useGrouping',
  1179. 'numberingSystem',
  1180. 'minimumIntegerDigits',
  1181. 'minimumFractionDigits',
  1182. 'maximumFractionDigits',
  1183. 'minimumSignificantDigits',
  1184. 'maximumSignificantDigits',
  1185. 'notation',
  1186. 'formatMatcher'
  1187. ];
  1188. /**
  1189. * Number Format Component
  1190. *
  1191. * @remarks
  1192. * See the following items for property about details
  1193. *
  1194. * @VueI18nSee [FormattableProps](component#formattableprops)
  1195. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1196. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  1197. *
  1198. * @VueI18nDanger
  1199. * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
  1200. *
  1201. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  1202. *
  1203. * @VueI18nComponent
  1204. */
  1205. const NumberFormat = {
  1206. /* eslint-disable */
  1207. name: 'i18n-n',
  1208. props: assign({
  1209. value: {
  1210. type: Number,
  1211. required: true
  1212. },
  1213. format: {
  1214. type: [String, Object]
  1215. }
  1216. }, baseFormatProps),
  1217. /* eslint-enable */
  1218. setup(props, context) {
  1219. const i18n = props.i18n ||
  1220. useI18n({ useScope: 'parent', __useComponent: true });
  1221. return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
  1222. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1223. i18n[NumberPartsSymbol](...args));
  1224. }
  1225. };
  1226. const DATETIME_FORMAT_KEYS = [
  1227. 'dateStyle',
  1228. 'timeStyle',
  1229. 'fractionalSecondDigits',
  1230. 'calendar',
  1231. 'dayPeriod',
  1232. 'numberingSystem',
  1233. 'localeMatcher',
  1234. 'timeZone',
  1235. 'hour12',
  1236. 'hourCycle',
  1237. 'formatMatcher',
  1238. 'weekday',
  1239. 'era',
  1240. 'year',
  1241. 'month',
  1242. 'day',
  1243. 'hour',
  1244. 'minute',
  1245. 'second',
  1246. 'timeZoneName'
  1247. ];
  1248. /**
  1249. * Datetime Format Component
  1250. *
  1251. * @remarks
  1252. * See the following items for property about details
  1253. *
  1254. * @VueI18nSee [FormattableProps](component#formattableprops)
  1255. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1256. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  1257. *
  1258. * @VueI18nDanger
  1259. * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
  1260. *
  1261. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  1262. *
  1263. * @VueI18nComponent
  1264. */
  1265. const DatetimeFormat = {
  1266. /* eslint-disable */
  1267. name: 'i18n-d',
  1268. props: assign({
  1269. value: {
  1270. type: [Number, Date],
  1271. required: true
  1272. },
  1273. format: {
  1274. type: [String, Object]
  1275. }
  1276. }, baseFormatProps),
  1277. /* eslint-enable */
  1278. setup(props, context) {
  1279. const i18n = props.i18n ||
  1280. useI18n({ useScope: 'parent', __useComponent: true });
  1281. return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
  1282. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1283. i18n[DatetimePartsSymbol](...args));
  1284. }
  1285. };
  1286. function getComposer$2(i18n, instance) {
  1287. const i18nInternal = i18n;
  1288. if (i18n.mode === 'composition') {
  1289. return (i18nInternal.__getInstance(instance) || i18n.global);
  1290. }
  1291. else {
  1292. const vueI18n = i18nInternal.__getInstance(instance);
  1293. return vueI18n != null
  1294. ? vueI18n.__composer
  1295. : i18n.global.__composer;
  1296. }
  1297. }
  1298. function vTDirective(i18n) {
  1299. const bind = (el, { instance, value, modifiers }) => {
  1300. /* istanbul ignore if */
  1301. if (!instance || !instance.$) {
  1302. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  1303. }
  1304. const composer = getComposer$2(i18n, instance.$);
  1305. if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {
  1306. warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
  1307. }
  1308. const parsedValue = parseValue(value);
  1309. el.textContent = composer.t(...makeParams(parsedValue));
  1310. };
  1311. return {
  1312. beforeMount: bind,
  1313. beforeUpdate: bind
  1314. };
  1315. }
  1316. function parseValue(value) {
  1317. if (isString(value)) {
  1318. return { path: value };
  1319. }
  1320. else if (isPlainObject(value)) {
  1321. if (!('path' in value)) {
  1322. throw createI18nError(19 /* REQUIRED_VALUE */, 'path');
  1323. }
  1324. return value;
  1325. }
  1326. else {
  1327. throw createI18nError(20 /* INVALID_VALUE */);
  1328. }
  1329. }
  1330. function makeParams(value) {
  1331. const { path, locale, args, choice, plural } = value;
  1332. const options = {};
  1333. const named = args || {};
  1334. if (isString(locale)) {
  1335. options.locale = locale;
  1336. }
  1337. if (isNumber(choice)) {
  1338. options.plural = choice;
  1339. }
  1340. if (isNumber(plural)) {
  1341. options.plural = plural;
  1342. }
  1343. return [path, named, options];
  1344. }
  1345. function apply(app, i18n, ...options) {
  1346. const pluginOptions = isPlainObject(options[0])
  1347. ? options[0]
  1348. : {};
  1349. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  1350. const globalInstall = isBoolean(pluginOptions.globalInstall)
  1351. ? pluginOptions.globalInstall
  1352. : true;
  1353. if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {
  1354. warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
  1355. name: Translation.name
  1356. }));
  1357. }
  1358. if (globalInstall) {
  1359. // install components
  1360. app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
  1361. app.component(NumberFormat.name, NumberFormat);
  1362. app.component(DatetimeFormat.name, DatetimeFormat);
  1363. }
  1364. // install directive
  1365. app.directive('t', vTDirective(i18n));
  1366. }
  1367. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  1368. let devtoolsApi;
  1369. async function enableDevTools(app, i18n) {
  1370. return new Promise((resolve, reject) => {
  1371. try {
  1372. setupDevtoolsPlugin({
  1373. id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
  1374. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
  1375. packageName: 'vue-i18n',
  1376. homepage: 'https://vue-i18n.intlify.dev',
  1377. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  1378. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  1379. app
  1380. }, api => {
  1381. devtoolsApi = api;
  1382. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  1383. updateComponentTreeTags(componentInstance, treeNode, i18n);
  1384. });
  1385. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  1386. if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) {
  1387. if (i18n.mode === 'legacy') {
  1388. // ignore global scope on legacy mode
  1389. if (componentInstance.vnode.el.__VUE_I18N__ !==
  1390. i18n.global.__composer) {
  1391. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  1392. }
  1393. }
  1394. else {
  1395. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  1396. }
  1397. }
  1398. });
  1399. api.addInspector({
  1400. id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
  1401. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
  1402. icon: 'language',
  1403. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
  1404. });
  1405. api.on.getInspectorTree(payload => {
  1406. if (payload.app === app &&
  1407. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  1408. registerScope(payload, i18n);
  1409. }
  1410. });
  1411. api.on.getInspectorState(payload => {
  1412. if (payload.app === app &&
  1413. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  1414. inspectScope(payload, i18n);
  1415. }
  1416. });
  1417. api.on.editInspectorState(payload => {
  1418. if (payload.app === app &&
  1419. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  1420. editScope(payload, i18n);
  1421. }
  1422. });
  1423. api.addTimelineLayer({
  1424. id: "vue-i18n-timeline" /* TIMELINE */,
  1425. label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
  1426. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
  1427. });
  1428. resolve(true);
  1429. });
  1430. }
  1431. catch (e) {
  1432. console.error(e);
  1433. reject(false);
  1434. }
  1435. });
  1436. }
  1437. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  1438. treeNode, i18n) {
  1439. // prettier-ignore
  1440. const global = i18n.mode === 'composition'
  1441. ? i18n.global
  1442. : i18n.global.__composer;
  1443. if (instance && instance.vnode.el.__VUE_I18N__) {
  1444. // add custom tags local scope only
  1445. if (instance.vnode.el.__VUE_I18N__ !== global) {
  1446. const label = instance.type.name || instance.type.displayName || instance.type.__file;
  1447. const tag = {
  1448. label: `i18n (${label} Scope)`,
  1449. textColor: 0x000000,
  1450. backgroundColor: 0xffcd19
  1451. };
  1452. treeNode.tags.push(tag);
  1453. }
  1454. }
  1455. }
  1456. function inspectComposer(instanceData, composer) {
  1457. const type = VUE_I18N_COMPONENT_TYPES;
  1458. instanceData.state.push({
  1459. type,
  1460. key: 'locale',
  1461. editable: true,
  1462. value: composer.locale.value
  1463. });
  1464. instanceData.state.push({
  1465. type,
  1466. key: 'availableLocales',
  1467. editable: false,
  1468. value: composer.availableLocales
  1469. });
  1470. instanceData.state.push({
  1471. type,
  1472. key: 'fallbackLocale',
  1473. editable: true,
  1474. value: composer.fallbackLocale.value
  1475. });
  1476. instanceData.state.push({
  1477. type,
  1478. key: 'inheritLocale',
  1479. editable: true,
  1480. value: composer.inheritLocale
  1481. });
  1482. instanceData.state.push({
  1483. type,
  1484. key: 'messages',
  1485. editable: false,
  1486. value: getLocaleMessageValue(composer.messages.value)
  1487. });
  1488. instanceData.state.push({
  1489. type,
  1490. key: 'datetimeFormats',
  1491. editable: false,
  1492. value: composer.datetimeFormats.value
  1493. });
  1494. instanceData.state.push({
  1495. type,
  1496. key: 'numberFormats',
  1497. editable: false,
  1498. value: composer.numberFormats.value
  1499. });
  1500. }
  1501. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1502. function getLocaleMessageValue(messages) {
  1503. const value = {};
  1504. Object.keys(messages).forEach((key) => {
  1505. const v = messages[key];
  1506. if (isFunction(v) && 'source' in v) {
  1507. value[key] = getMessageFunctionDetails(v);
  1508. }
  1509. else if (isObject(v)) {
  1510. value[key] = getLocaleMessageValue(v);
  1511. }
  1512. else {
  1513. value[key] = v;
  1514. }
  1515. });
  1516. return value;
  1517. }
  1518. const ESC = {
  1519. '<': '&lt;',
  1520. '>': '&gt;',
  1521. '"': '&quot;',
  1522. '&': '&amp;'
  1523. };
  1524. function escape(s) {
  1525. return s.replace(/[<>"&]/g, escapeChar);
  1526. }
  1527. function escapeChar(a) {
  1528. return ESC[a] || a;
  1529. }
  1530. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1531. function getMessageFunctionDetails(func) {
  1532. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  1533. return {
  1534. _custom: {
  1535. type: 'function',
  1536. display: `<span>ƒ</span> ${argString}`
  1537. }
  1538. };
  1539. }
  1540. function registerScope(payload, i18n) {
  1541. payload.rootNodes.push({
  1542. id: 'global',
  1543. label: 'Global Scope'
  1544. });
  1545. // prettier-ignore
  1546. const global = i18n.mode === 'composition'
  1547. ? i18n.global
  1548. : i18n.global.__composer;
  1549. for (const [keyInstance, instance] of i18n.__instances) {
  1550. // prettier-ignore
  1551. const composer = i18n.mode === 'composition'
  1552. ? instance
  1553. : instance.__composer;
  1554. if (global === composer) {
  1555. continue;
  1556. }
  1557. const label = keyInstance.type.name ||
  1558. keyInstance.type.displayName ||
  1559. keyInstance.type.__file;
  1560. payload.rootNodes.push({
  1561. id: composer.id.toString(),
  1562. label: `${label} Scope`
  1563. });
  1564. }
  1565. }
  1566. function getComposer$1(nodeId, i18n) {
  1567. if (nodeId === 'global') {
  1568. return i18n.mode === 'composition'
  1569. ? i18n.global
  1570. : i18n.global.__composer;
  1571. }
  1572. else {
  1573. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  1574. if (instance) {
  1575. return i18n.mode === 'composition'
  1576. ? instance
  1577. : instance.__composer;
  1578. }
  1579. else {
  1580. return null;
  1581. }
  1582. }
  1583. }
  1584. function inspectScope(payload, i18n) {
  1585. const composer = getComposer$1(payload.nodeId, i18n);
  1586. if (composer) {
  1587. payload.state = makeScopeInspectState(composer);
  1588. }
  1589. }
  1590. function makeScopeInspectState(composer) {
  1591. const state = {};
  1592. const localeType = 'Locale related info';
  1593. const localeStates = [
  1594. {
  1595. type: localeType,
  1596. key: 'locale',
  1597. editable: true,
  1598. value: composer.locale.value
  1599. },
  1600. {
  1601. type: localeType,
  1602. key: 'fallbackLocale',
  1603. editable: true,
  1604. value: composer.fallbackLocale.value
  1605. },
  1606. {
  1607. type: localeType,
  1608. key: 'availableLocales',
  1609. editable: false,
  1610. value: composer.availableLocales
  1611. },
  1612. {
  1613. type: localeType,
  1614. key: 'inheritLocale',
  1615. editable: true,
  1616. value: composer.inheritLocale
  1617. }
  1618. ];
  1619. state[localeType] = localeStates;
  1620. const localeMessagesType = 'Locale messages info';
  1621. const localeMessagesStates = [
  1622. {
  1623. type: localeMessagesType,
  1624. key: 'messages',
  1625. editable: false,
  1626. value: getLocaleMessageValue(composer.messages.value)
  1627. }
  1628. ];
  1629. state[localeMessagesType] = localeMessagesStates;
  1630. const datetimeFormatsType = 'Datetime formats info';
  1631. const datetimeFormatsStates = [
  1632. {
  1633. type: datetimeFormatsType,
  1634. key: 'datetimeFormats',
  1635. editable: false,
  1636. value: composer.datetimeFormats.value
  1637. }
  1638. ];
  1639. state[datetimeFormatsType] = datetimeFormatsStates;
  1640. const numberFormatsType = 'Datetime formats info';
  1641. const numberFormatsStates = [
  1642. {
  1643. type: numberFormatsType,
  1644. key: 'numberFormats',
  1645. editable: false,
  1646. value: composer.numberFormats.value
  1647. }
  1648. ];
  1649. state[numberFormatsType] = numberFormatsStates;
  1650. return state;
  1651. }
  1652. function addTimelineEvent(event, payload) {
  1653. if (devtoolsApi) {
  1654. let groupId;
  1655. if (payload && 'groupId' in payload) {
  1656. groupId = payload.groupId;
  1657. delete payload.groupId;
  1658. }
  1659. devtoolsApi.addTimelineEvent({
  1660. layerId: "vue-i18n-timeline" /* TIMELINE */,
  1661. event: {
  1662. title: event,
  1663. groupId,
  1664. time: Date.now(),
  1665. meta: {},
  1666. data: payload || {},
  1667. logType: event === "compile-error" /* COMPILE_ERROR */
  1668. ? 'error'
  1669. : event === "fallback" /* FALBACK */ ||
  1670. event === "missing" /* MISSING */
  1671. ? 'warning'
  1672. : 'default'
  1673. }
  1674. });
  1675. }
  1676. }
  1677. function editScope(payload, i18n) {
  1678. const composer = getComposer$1(payload.nodeId, i18n);
  1679. if (composer) {
  1680. const [field] = payload.path;
  1681. if (field === 'locale' && isString(payload.state.value)) {
  1682. composer.locale.value = payload.state.value;
  1683. }
  1684. else if (field === 'fallbackLocale' &&
  1685. (isString(payload.state.value) ||
  1686. isArray(payload.state.value) ||
  1687. isObject(payload.state.value))) {
  1688. composer.fallbackLocale.value = payload.state.value;
  1689. }
  1690. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  1691. composer.inheritLocale = payload.state.value;
  1692. }
  1693. }
  1694. }
  1695. // supports compatibility for legacy vue-i18n APIs
  1696. function defineMixin(vuei18n, composer, i18n) {
  1697. return {
  1698. beforeCreate() {
  1699. const instance = getCurrentInstance();
  1700. /* istanbul ignore if */
  1701. if (!instance) {
  1702. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  1703. }
  1704. const options = this.$options;
  1705. if (options.i18n) {
  1706. const optionsI18n = options.i18n;
  1707. if (options.__i18n) {
  1708. optionsI18n.__i18n = options.__i18n;
  1709. }
  1710. optionsI18n.__root = composer;
  1711. if (this === this.$root) {
  1712. this.$i18n = mergeToRoot(vuei18n, optionsI18n);
  1713. }
  1714. else {
  1715. optionsI18n.__injectWithOption = true;
  1716. this.$i18n = createVueI18n(optionsI18n);
  1717. }
  1718. }
  1719. else if (options.__i18n) {
  1720. if (this === this.$root) {
  1721. this.$i18n = mergeToRoot(vuei18n, options);
  1722. }
  1723. else {
  1724. this.$i18n = createVueI18n({
  1725. __i18n: options.__i18n,
  1726. __injectWithOption: true,
  1727. __root: composer
  1728. });
  1729. }
  1730. }
  1731. else {
  1732. // set global
  1733. this.$i18n = vuei18n;
  1734. }
  1735. vuei18n.__onComponentInstanceCreated(this.$i18n);
  1736. i18n.__setInstance(instance, this.$i18n);
  1737. // defines vue-i18n legacy APIs
  1738. this.$t = (...args) => this.$i18n.t(...args);
  1739. this.$rt = (...args) => this.$i18n.rt(...args);
  1740. this.$tc = (...args) => this.$i18n.tc(...args);
  1741. this.$te = (key, locale) => this.$i18n.te(key, locale);
  1742. this.$d = (...args) => this.$i18n.d(...args);
  1743. this.$n = (...args) => this.$i18n.n(...args);
  1744. this.$tm = (key) => this.$i18n.tm(key);
  1745. },
  1746. mounted() {
  1747. /* istanbul ignore if */
  1748. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) {
  1749. this.$el.__VUE_I18N__ = this.$i18n.__composer;
  1750. const emitter = (this.__v_emitter = createEmitter());
  1751. const _vueI18n = this.$i18n;
  1752. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  1753. emitter.on('*', addTimelineEvent);
  1754. }
  1755. },
  1756. beforeUnmount() {
  1757. const instance = getCurrentInstance();
  1758. /* istanbul ignore if */
  1759. if (!instance) {
  1760. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  1761. }
  1762. /* istanbul ignore if */
  1763. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) {
  1764. if (this.__v_emitter) {
  1765. this.__v_emitter.off('*', addTimelineEvent);
  1766. delete this.__v_emitter;
  1767. }
  1768. const _vueI18n = this.$i18n;
  1769. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  1770. delete this.$el.__VUE_I18N__;
  1771. }
  1772. delete this.$t;
  1773. delete this.$rt;
  1774. delete this.$tc;
  1775. delete this.$te;
  1776. delete this.$d;
  1777. delete this.$n;
  1778. delete this.$tm;
  1779. i18n.__deleteInstance(instance);
  1780. delete this.$i18n;
  1781. }
  1782. };
  1783. }
  1784. function mergeToRoot(root, options) {
  1785. root.locale = options.locale || root.locale;
  1786. root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
  1787. root.missing = options.missing || root.missing;
  1788. root.silentTranslationWarn =
  1789. options.silentTranslationWarn || root.silentFallbackWarn;
  1790. root.silentFallbackWarn =
  1791. options.silentFallbackWarn || root.silentFallbackWarn;
  1792. root.formatFallbackMessages =
  1793. options.formatFallbackMessages || root.formatFallbackMessages;
  1794. root.postTranslation = options.postTranslation || root.postTranslation;
  1795. root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
  1796. root.escapeParameterHtml =
  1797. options.escapeParameterHtml || root.escapeParameterHtml;
  1798. root.sync = options.sync || root.sync;
  1799. root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
  1800. const messages = getLocaleMessages(root.locale, {
  1801. messages: options.messages,
  1802. __i18n: options.__i18n
  1803. });
  1804. Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
  1805. if (options.datetimeFormats) {
  1806. Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  1807. }
  1808. if (options.numberFormats) {
  1809. Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
  1810. }
  1811. return root;
  1812. }
  1813. /**
  1814. * Vue I18n factory
  1815. *
  1816. * @param options - An options, see the {@link I18nOptions}
  1817. *
  1818. * @returns {@link I18n} instance
  1819. *
  1820. * @remarks
  1821. * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
  1822. *
  1823. * If you use composition API mode, you need to specify {@link ComposerOptions}.
  1824. *
  1825. * @VueI18nSee [Getting Started](../guide/)
  1826. * @VueI18nSee [Composition API](../guide/advanced/composition)
  1827. *
  1828. * @example
  1829. * case: for Legacy API
  1830. * ```js
  1831. * import { createApp } from 'vue'
  1832. * import { createI18n } from 'vue-i18n'
  1833. *
  1834. * // call with I18n option
  1835. * const i18n = createI18n({
  1836. * locale: 'ja',
  1837. * messages: {
  1838. * en: { ... },
  1839. * ja: { ... }
  1840. * }
  1841. * })
  1842. *
  1843. * const App = {
  1844. * // ...
  1845. * }
  1846. *
  1847. * const app = createApp(App)
  1848. *
  1849. * // install!
  1850. * app.use(i18n)
  1851. * app.mount('#app')
  1852. * ```
  1853. *
  1854. * @example
  1855. * case: for composition API
  1856. * ```js
  1857. * import { createApp } from 'vue'
  1858. * import { createI18n, useI18n } from 'vue-i18n'
  1859. *
  1860. * // call with I18n option
  1861. * const i18n = createI18n({
  1862. * legacy: false, // you must specify 'legacy: false' option
  1863. * locale: 'ja',
  1864. * messages: {
  1865. * en: { ... },
  1866. * ja: { ... }
  1867. * }
  1868. * })
  1869. *
  1870. * const App = {
  1871. * setup() {
  1872. * // ...
  1873. * const { t } = useI18n({ ... })
  1874. * return { ... , t }
  1875. * }
  1876. * }
  1877. *
  1878. * const app = createApp(App)
  1879. *
  1880. * // install!
  1881. * app.use(i18n)
  1882. * app.mount('#app')
  1883. * ```
  1884. *
  1885. * @VueI18nGeneral
  1886. */
  1887. function createI18n(options = {}) {
  1888. // prettier-ignore
  1889. const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)
  1890. ? options.legacy
  1891. : __VUE_I18N_LEGACY_API__;
  1892. const __globalInjection = !!options.globalInjection;
  1893. const __instances = new Map();
  1894. // prettier-ignore
  1895. const __global = __VUE_I18N_LEGACY_API__ && __legacyMode
  1896. ? createVueI18n(options)
  1897. : createComposer(options);
  1898. const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');
  1899. const i18n = {
  1900. // mode
  1901. get mode() {
  1902. // prettier-ignore
  1903. return __VUE_I18N_LEGACY_API__
  1904. ? __legacyMode
  1905. ? 'legacy'
  1906. : 'composition'
  1907. : 'composition';
  1908. },
  1909. // install plugin
  1910. async install(app, ...options) {
  1911. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) {
  1912. app.__VUE_I18N__ = i18n;
  1913. }
  1914. // setup global provider
  1915. app.__VUE_I18N_SYMBOL__ = symbol;
  1916. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  1917. // global method and properties injection for Composition API
  1918. if (!__legacyMode && __globalInjection) {
  1919. injectGlobalFields(app, i18n.global);
  1920. }
  1921. // install built-in components and directive
  1922. if (__VUE_I18N_FULL_INSTALL__) {
  1923. apply(app, i18n, ...options);
  1924. }
  1925. // setup mixin for Legacy API
  1926. if (__VUE_I18N_LEGACY_API__ && __legacyMode) {
  1927. app.mixin(defineMixin(__global, __global.__composer, i18n));
  1928. }
  1929. // setup vue-devtools plugin
  1930. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) && !false) {
  1931. const ret = await enableDevTools(app, i18n);
  1932. if (!ret) {
  1933. throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
  1934. }
  1935. const emitter = createEmitter();
  1936. if (__legacyMode) {
  1937. const _vueI18n = __global;
  1938. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  1939. }
  1940. else {
  1941. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1942. const _composer = __global;
  1943. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  1944. }
  1945. emitter.on('*', addTimelineEvent);
  1946. }
  1947. },
  1948. // global accessor
  1949. get global() {
  1950. return __global;
  1951. },
  1952. // @internal
  1953. __instances,
  1954. // @internal
  1955. __getInstance(component) {
  1956. return __instances.get(component) || null;
  1957. },
  1958. // @internal
  1959. __setInstance(component, instance) {
  1960. __instances.set(component, instance);
  1961. },
  1962. // @internal
  1963. __deleteInstance(component) {
  1964. __instances.delete(component);
  1965. }
  1966. };
  1967. return i18n;
  1968. }
  1969. /**
  1970. * Use Composition API for Vue I18n
  1971. *
  1972. * @param options - An options, see {@link UseI18nOptions}
  1973. *
  1974. * @returns {@link Composer} instance
  1975. *
  1976. * @remarks
  1977. * This function is mainly used by `setup`.
  1978. *
  1979. * If options are specified, Composer instance is created for each component and you can be localized on the component.
  1980. *
  1981. * If options are not specified, you can be localized using the global Composer.
  1982. *
  1983. * @example
  1984. * case: Component resource base localization
  1985. * ```html
  1986. * <template>
  1987. * <form>
  1988. * <label>{{ t('language') }}</label>
  1989. * <select v-model="locale">
  1990. * <option value="en">en</option>
  1991. * <option value="ja">ja</option>
  1992. * </select>
  1993. * </form>
  1994. * <p>message: {{ t('hello') }}</p>
  1995. * </template>
  1996. *
  1997. * <script>
  1998. * import { useI18n } from 'vue-i18n'
  1999. *
  2000. * export default {
  2001. * setup() {
  2002. * const { t, locale } = useI18n({
  2003. * locale: 'ja',
  2004. * messages: {
  2005. * en: { ... },
  2006. * ja: { ... }
  2007. * }
  2008. * })
  2009. * // Something to do ...
  2010. *
  2011. * return { ..., t, locale }
  2012. * }
  2013. * }
  2014. * </script>
  2015. * ```
  2016. *
  2017. * @VueI18nComposition
  2018. */
  2019. function useI18n(options = {}) {
  2020. const instance = getCurrentInstance();
  2021. if (instance == null) {
  2022. throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */);
  2023. }
  2024. if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
  2025. throw createI18nError(17 /* NOT_INSLALLED */);
  2026. }
  2027. const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
  2028. /* istanbul ignore if */
  2029. if (!i18n) {
  2030. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  2031. }
  2032. // prettier-ignore
  2033. const global = i18n.mode === 'composition'
  2034. ? i18n.global
  2035. : i18n.global.__composer;
  2036. // prettier-ignore
  2037. const scope = isEmptyObject(options)
  2038. ? ('__i18n' in instance.type)
  2039. ? 'local'
  2040. : 'global'
  2041. : !options.useScope
  2042. ? 'local'
  2043. : options.useScope;
  2044. if (scope === 'global') {
  2045. let messages = isObject(options.messages) ? options.messages : {};
  2046. if ('__i18nGlobal' in instance.type) {
  2047. messages = getLocaleMessages(global.locale.value, {
  2048. messages,
  2049. __i18n: instance.type.__i18nGlobal
  2050. });
  2051. }
  2052. // merge locale messages
  2053. const locales = Object.keys(messages);
  2054. if (locales.length) {
  2055. locales.forEach(locale => {
  2056. global.mergeLocaleMessage(locale, messages[locale]);
  2057. });
  2058. }
  2059. // merge datetime formats
  2060. if (isObject(options.datetimeFormats)) {
  2061. const locales = Object.keys(options.datetimeFormats);
  2062. if (locales.length) {
  2063. locales.forEach(locale => {
  2064. global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  2065. });
  2066. }
  2067. }
  2068. // merge number formats
  2069. if (isObject(options.numberFormats)) {
  2070. const locales = Object.keys(options.numberFormats);
  2071. if (locales.length) {
  2072. locales.forEach(locale => {
  2073. global.mergeNumberFormat(locale, options.numberFormats[locale]);
  2074. });
  2075. }
  2076. }
  2077. return global;
  2078. }
  2079. if (scope === 'parent') {
  2080. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2081. let composer = getComposer(i18n, instance, options.__useComponent);
  2082. if (composer == null) {
  2083. if ((process.env.NODE_ENV !== 'production')) {
  2084. warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
  2085. }
  2086. composer = global;
  2087. }
  2088. return composer;
  2089. }
  2090. // scope 'local' case
  2091. if (i18n.mode === 'legacy') {
  2092. throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
  2093. }
  2094. const i18nInternal = i18n;
  2095. let composer = i18nInternal.__getInstance(instance);
  2096. if (composer == null) {
  2097. const type = instance.type;
  2098. const composerOptions = assign({}, options);
  2099. if (type.__i18n) {
  2100. composerOptions.__i18n = type.__i18n;
  2101. }
  2102. if (global) {
  2103. composerOptions.__root = global;
  2104. }
  2105. composer = createComposer(composerOptions);
  2106. setupLifeCycle(i18nInternal, instance, composer);
  2107. i18nInternal.__setInstance(instance, composer);
  2108. }
  2109. return composer;
  2110. }
  2111. function getComposer(i18n, target, useComponent = false) {
  2112. let composer = null;
  2113. const root = target.root;
  2114. let current = target.parent;
  2115. while (current != null) {
  2116. const i18nInternal = i18n;
  2117. if (i18n.mode === 'composition') {
  2118. composer = i18nInternal.__getInstance(current);
  2119. }
  2120. else {
  2121. const vueI18n = i18nInternal.__getInstance(current);
  2122. if (vueI18n != null) {
  2123. composer = vueI18n
  2124. .__composer;
  2125. }
  2126. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2127. if (useComponent && composer && !composer[InejctWithOption]) {
  2128. composer = null;
  2129. }
  2130. }
  2131. if (composer != null) {
  2132. break;
  2133. }
  2134. if (root === current) {
  2135. break;
  2136. }
  2137. current = current.parent;
  2138. }
  2139. return composer;
  2140. }
  2141. function setupLifeCycle(i18n, target, composer) {
  2142. let emitter = null;
  2143. onMounted(() => {
  2144. // inject composer instance to DOM for intlify-devtools
  2145. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) &&
  2146. !false &&
  2147. target.vnode.el) {
  2148. target.vnode.el.__VUE_I18N__ = composer;
  2149. emitter = createEmitter();
  2150. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2151. const _composer = composer;
  2152. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  2153. emitter.on('*', addTimelineEvent);
  2154. }
  2155. }, target);
  2156. onUnmounted(() => {
  2157. // remove composer instance from DOM for intlify-devtools
  2158. if (((process.env.NODE_ENV !== 'production') || __VUE_I18N_PROD_DEVTOOLS__) &&
  2159. !false &&
  2160. target.vnode.el &&
  2161. target.vnode.el.__VUE_I18N__) {
  2162. emitter && emitter.off('*', addTimelineEvent);
  2163. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2164. const _composer = composer;
  2165. _composer[DisableEmitter] && _composer[DisableEmitter]();
  2166. delete target.vnode.el.__VUE_I18N__;
  2167. }
  2168. i18n.__deleteInstance(target);
  2169. }, target);
  2170. }
  2171. const globalExportProps = [
  2172. 'locale',
  2173. 'fallbackLocale',
  2174. 'availableLocales'
  2175. ];
  2176. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm'];
  2177. function injectGlobalFields(app, composer) {
  2178. const i18n = Object.create(null);
  2179. globalExportProps.forEach(prop => {
  2180. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  2181. if (!desc) {
  2182. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  2183. }
  2184. const wrap = isRef(desc.value) // check computed props
  2185. ? {
  2186. get() {
  2187. return desc.value.value;
  2188. },
  2189. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2190. set(val) {
  2191. desc.value.value = val;
  2192. }
  2193. }
  2194. : {
  2195. get() {
  2196. return desc.get && desc.get();
  2197. }
  2198. };
  2199. Object.defineProperty(i18n, prop, wrap);
  2200. });
  2201. app.config.globalProperties.$i18n = i18n;
  2202. globalExportMethods.forEach(method => {
  2203. const desc = Object.getOwnPropertyDescriptor(composer, method);
  2204. if (!desc || !desc.value) {
  2205. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  2206. }
  2207. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  2208. });
  2209. }
  2210. {
  2211. initFeatureFlags();
  2212. }
  2213. // NOTE: experimental !!
  2214. if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
  2215. const target = getGlobalThis();
  2216. target.__INTLIFY__ = true;
  2217. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  2218. }
  2219. if ((process.env.NODE_ENV !== 'production')) ;
  2220. export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };