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

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