vue-i18n.mjs 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  1. /*!
  2. * vue-i18n v9.13.1
  3. * (c) 2024 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { getGlobalThis, incrementer, format, makeSymbol, isPlainObject, isArray, deepCopy, isString, hasOwn, isObject, warn, warnOnce, isBoolean, isRegExp, isFunction, inBrowser, assign, isNumber, createEmitter, isEmptyObject } from '@intlify/shared';
  7. import { CoreWarnCodes, CoreErrorCodes, createCompileError, DEFAULT_LOCALE, updateFallbackLocale, setFallbackContext, createCoreContext, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, getFallbackContext, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, isMessageAST, isMessageFunction, fallbackWithLocaleChain, NUMBER_FORMAT_OPTIONS_KEYS, DATETIME_FORMAT_OPTIONS_KEYS, registerMessageCompiler, compile, compileToFunction, registerMessageResolver, resolveValue, registerLocaleFallbacker, setDevToolsHook } from '@intlify/core-base';
  8. import { createVNode, Text, computed, watch, getCurrentInstance, ref, shallowRef, Fragment, defineComponent, h, effectScope, inject, onMounted, onUnmounted, onBeforeMount, isRef } from 'vue';
  9. import { setupDevtoolsPlugin } from '@vue/devtools-api';
  10. /**
  11. * Vue I18n Version
  12. *
  13. * @remarks
  14. * Semver format. Same format as the package.json `version` field.
  15. *
  16. * @VueI18nGeneral
  17. */
  18. const VERSION = '9.13.1';
  19. /**
  20. * This is only called in esm-bundler builds.
  21. * istanbul-ignore-next
  22. */
  23. function initFeatureFlags() {
  24. if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {
  25. getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;
  26. }
  27. if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {
  28. getGlobalThis().__VUE_I18N_LEGACY_API__ = true;
  29. }
  30. if (typeof __INTLIFY_JIT_COMPILATION__ !== 'boolean') {
  31. getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;
  32. }
  33. if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {
  34. getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;
  35. }
  36. if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
  37. getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
  38. }
  39. }
  40. const code$1 = CoreWarnCodes.__EXTEND_POINT__;
  41. const inc$1 = incrementer(code$1);
  42. const I18nWarnCodes = {
  43. FALLBACK_TO_ROOT: code$1, // 9
  44. NOT_SUPPORTED_PRESERVE: inc$1(), // 10
  45. NOT_SUPPORTED_FORMATTER: inc$1(), // 11
  46. NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(), // 12
  47. NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(), // 13
  48. COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(), // 14
  49. NOT_FOUND_PARENT_SCOPE: inc$1(), // 15
  50. IGNORE_OBJ_FLATTEN: inc$1(), // 16
  51. NOTICE_DROP_ALLOW_COMPOSITION: inc$1(), // 17
  52. NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG: inc$1() // 18
  53. };
  54. const warnMessages = {
  55. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  56. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
  57. [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
  58. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
  59. [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
  60. [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  61. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  62. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  63. [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`,
  64. [I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG]: `'translateExistCompatible' option will be dropped in the next major version.`
  65. };
  66. function getWarnMessage(code, ...args) {
  67. return format(warnMessages[code], ...args);
  68. }
  69. const code = CoreErrorCodes.__EXTEND_POINT__;
  70. const inc = incrementer(code);
  71. const I18nErrorCodes = {
  72. // composer module errors
  73. UNEXPECTED_RETURN_TYPE: code, // 24
  74. // legacy module errors
  75. INVALID_ARGUMENT: inc(), // 25
  76. // i18n module errors
  77. MUST_BE_CALL_SETUP_TOP: inc(), // 26
  78. NOT_INSTALLED: inc(), // 27
  79. NOT_AVAILABLE_IN_LEGACY_MODE: inc(), // 28
  80. // directive module errors
  81. REQUIRED_VALUE: inc(), // 29
  82. INVALID_VALUE: inc(), // 30
  83. // vue-devtools errors
  84. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(), // 31
  85. NOT_INSTALLED_WITH_PROVIDE: inc(), // 32
  86. // unexpected error
  87. UNEXPECTED_ERROR: inc(), // 33
  88. // not compatible legacy vue-i18n constructor
  89. NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(), // 34
  90. // bridge support vue 2.x only
  91. BRIDGE_SUPPORT_VUE_2_ONLY: inc(), // 35
  92. // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``
  93. MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(), // 36
  94. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  95. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(), // 37
  96. // for enhancement
  97. __EXTEND_POINT__: inc() // 38
  98. };
  99. function createI18nError(code, ...args) {
  100. return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);
  101. }
  102. const errorMessages = {
  103. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  104. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  105. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  106. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  107. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  108. [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
  109. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  110. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  111. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  112. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  113. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  114. [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',
  115. [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',
  116. [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'
  117. };
  118. const TranslateVNodeSymbol =
  119. /* #__PURE__*/ makeSymbol('__translateVNode');
  120. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  121. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  122. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  123. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  124. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  125. makeSymbol('__intlifyMeta');
  126. const InejctWithOptionSymbol =
  127. /* #__PURE__*/ makeSymbol('__injectWithOption');
  128. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  129. const __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';
  130. /* eslint-disable @typescript-eslint/no-explicit-any */
  131. /**
  132. * Transform flat json in obj to normal json in obj
  133. */
  134. function handleFlatJson(obj) {
  135. // check obj
  136. if (!isObject(obj)) {
  137. return obj;
  138. }
  139. for (const key in obj) {
  140. // check key
  141. if (!hasOwn(obj, key)) {
  142. continue;
  143. }
  144. // handle for normal json
  145. if (!key.includes('.')) {
  146. // recursive process value if value is also a object
  147. if (isObject(obj[key])) {
  148. handleFlatJson(obj[key]);
  149. }
  150. }
  151. // handle for flat json, transform to normal json
  152. else {
  153. // go to the last object
  154. const subKeys = key.split('.');
  155. const lastIndex = subKeys.length - 1;
  156. let currentObj = obj;
  157. let hasStringValue = false;
  158. for (let i = 0; i < lastIndex; i++) {
  159. if (!(subKeys[i] in currentObj)) {
  160. currentObj[subKeys[i]] = {};
  161. }
  162. if (!isObject(currentObj[subKeys[i]])) {
  163. (process.env.NODE_ENV !== 'production') &&
  164. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  165. key: subKeys[i]
  166. }));
  167. hasStringValue = true;
  168. break;
  169. }
  170. currentObj = currentObj[subKeys[i]];
  171. }
  172. // update last object value, delete old property
  173. if (!hasStringValue) {
  174. currentObj[subKeys[lastIndex]] = obj[key];
  175. delete obj[key];
  176. }
  177. // recursive process value if value is also a object
  178. if (isObject(currentObj[subKeys[lastIndex]])) {
  179. handleFlatJson(currentObj[subKeys[lastIndex]]);
  180. }
  181. }
  182. }
  183. return obj;
  184. }
  185. function getLocaleMessages(locale, options) {
  186. const { messages, __i18n, messageResolver, flatJson } = options;
  187. // prettier-ignore
  188. const ret = (isPlainObject(messages)
  189. ? messages
  190. : isArray(__i18n)
  191. ? {}
  192. : { [locale]: {} });
  193. // merge locale messages of i18n custom block
  194. if (isArray(__i18n)) {
  195. __i18n.forEach(custom => {
  196. if ('locale' in custom && 'resource' in custom) {
  197. const { locale, resource } = custom;
  198. if (locale) {
  199. ret[locale] = ret[locale] || {};
  200. deepCopy(resource, ret[locale]);
  201. }
  202. else {
  203. deepCopy(resource, ret);
  204. }
  205. }
  206. else {
  207. isString(custom) && deepCopy(JSON.parse(custom), ret);
  208. }
  209. });
  210. }
  211. // handle messages for flat json
  212. if (messageResolver == null && flatJson) {
  213. for (const key in ret) {
  214. if (hasOwn(ret, key)) {
  215. handleFlatJson(ret[key]);
  216. }
  217. }
  218. }
  219. return ret;
  220. }
  221. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  222. function getComponentOptions(instance) {
  223. return instance.type ;
  224. }
  225. function adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
  226. ) {
  227. let messages = isObject(options.messages) ? options.messages : {};
  228. if ('__i18nGlobal' in componentOptions) {
  229. messages = getLocaleMessages(gl.locale.value, {
  230. messages,
  231. __i18n: componentOptions.__i18nGlobal
  232. });
  233. }
  234. // merge locale messages
  235. const locales = Object.keys(messages);
  236. if (locales.length) {
  237. locales.forEach(locale => {
  238. gl.mergeLocaleMessage(locale, messages[locale]);
  239. });
  240. }
  241. {
  242. // merge datetime formats
  243. if (isObject(options.datetimeFormats)) {
  244. const locales = Object.keys(options.datetimeFormats);
  245. if (locales.length) {
  246. locales.forEach(locale => {
  247. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  248. });
  249. }
  250. }
  251. // merge number formats
  252. if (isObject(options.numberFormats)) {
  253. const locales = Object.keys(options.numberFormats);
  254. if (locales.length) {
  255. locales.forEach(locale => {
  256. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  257. });
  258. }
  259. }
  260. }
  261. }
  262. function createTextNode(key) {
  263. return createVNode(Text, null, key, 0)
  264. ;
  265. }
  266. /* eslint-enable @typescript-eslint/no-explicit-any */
  267. /* eslint-disable @typescript-eslint/no-explicit-any */
  268. // extend VNode interface
  269. const DEVTOOLS_META = '__INTLIFY_META__';
  270. const NOOP_RETURN_ARRAY = () => [];
  271. const NOOP_RETURN_FALSE = () => false;
  272. let composerID = 0;
  273. function defineCoreMissingHandler(missing) {
  274. return ((ctx, locale, key, type) => {
  275. return missing(locale, key, getCurrentInstance() || undefined, type);
  276. });
  277. }
  278. // for Intlify DevTools
  279. /* #__NO_SIDE_EFFECTS__ */
  280. const getMetaInfo = () => {
  281. const instance = getCurrentInstance();
  282. let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
  283. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  284. ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
  285. : null;
  286. };
  287. /**
  288. * Create composer interface factory
  289. *
  290. * @internal
  291. */
  292. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  293. function createComposer(options = {}, VueI18nLegacy) {
  294. const { __root, __injectWithOption } = options;
  295. const _isGlobal = __root === undefined;
  296. const flatJson = options.flatJson;
  297. const _ref = inBrowser ? ref : shallowRef;
  298. const translateExistCompatible = !!options.translateExistCompatible;
  299. if ((process.env.NODE_ENV !== 'production')) {
  300. if (translateExistCompatible && !false) {
  301. warnOnce(getWarnMessage(I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG));
  302. }
  303. }
  304. let _inheritLocale = isBoolean(options.inheritLocale)
  305. ? options.inheritLocale
  306. : true;
  307. const _locale = _ref(
  308. // prettier-ignore
  309. __root && _inheritLocale
  310. ? __root.locale.value
  311. : isString(options.locale)
  312. ? options.locale
  313. : DEFAULT_LOCALE);
  314. const _fallbackLocale = _ref(
  315. // prettier-ignore
  316. __root && _inheritLocale
  317. ? __root.fallbackLocale.value
  318. : isString(options.fallbackLocale) ||
  319. isArray(options.fallbackLocale) ||
  320. isPlainObject(options.fallbackLocale) ||
  321. options.fallbackLocale === false
  322. ? options.fallbackLocale
  323. : _locale.value);
  324. const _messages = _ref(getLocaleMessages(_locale.value, options));
  325. // prettier-ignore
  326. const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)
  327. ? options.datetimeFormats
  328. : { [_locale.value]: {} })
  329. ;
  330. // prettier-ignore
  331. const _numberFormats = _ref(isPlainObject(options.numberFormats)
  332. ? options.numberFormats
  333. : { [_locale.value]: {} })
  334. ;
  335. // warning suppress options
  336. // prettier-ignore
  337. let _missingWarn = __root
  338. ? __root.missingWarn
  339. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  340. ? options.missingWarn
  341. : true;
  342. // prettier-ignore
  343. let _fallbackWarn = __root
  344. ? __root.fallbackWarn
  345. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  346. ? options.fallbackWarn
  347. : true;
  348. // prettier-ignore
  349. let _fallbackRoot = __root
  350. ? __root.fallbackRoot
  351. : isBoolean(options.fallbackRoot)
  352. ? options.fallbackRoot
  353. : true;
  354. // configure fall back to root
  355. let _fallbackFormat = !!options.fallbackFormat;
  356. // runtime missing
  357. let _missing = isFunction(options.missing) ? options.missing : null;
  358. let _runtimeMissing = isFunction(options.missing)
  359. ? defineCoreMissingHandler(options.missing)
  360. : null;
  361. // postTranslation handler
  362. let _postTranslation = isFunction(options.postTranslation)
  363. ? options.postTranslation
  364. : null;
  365. // prettier-ignore
  366. let _warnHtmlMessage = __root
  367. ? __root.warnHtmlMessage
  368. : isBoolean(options.warnHtmlMessage)
  369. ? options.warnHtmlMessage
  370. : true;
  371. let _escapeParameter = !!options.escapeParameter;
  372. // custom linked modifiers
  373. // prettier-ignore
  374. const _modifiers = __root
  375. ? __root.modifiers
  376. : isPlainObject(options.modifiers)
  377. ? options.modifiers
  378. : {};
  379. // pluralRules
  380. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  381. // runtime context
  382. // eslint-disable-next-line prefer-const
  383. let _context;
  384. const getCoreContext = () => {
  385. _isGlobal && setFallbackContext(null);
  386. const ctxOptions = {
  387. version: VERSION,
  388. locale: _locale.value,
  389. fallbackLocale: _fallbackLocale.value,
  390. messages: _messages.value,
  391. modifiers: _modifiers,
  392. pluralRules: _pluralRules,
  393. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  394. missingWarn: _missingWarn,
  395. fallbackWarn: _fallbackWarn,
  396. fallbackFormat: _fallbackFormat,
  397. unresolving: true,
  398. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  399. warnHtmlMessage: _warnHtmlMessage,
  400. escapeParameter: _escapeParameter,
  401. messageResolver: options.messageResolver,
  402. messageCompiler: options.messageCompiler,
  403. __meta: { framework: 'vue' }
  404. };
  405. {
  406. ctxOptions.datetimeFormats = _datetimeFormats.value;
  407. ctxOptions.numberFormats = _numberFormats.value;
  408. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  409. ? _context.__datetimeFormatters
  410. : undefined;
  411. ctxOptions.__numberFormatters = isPlainObject(_context)
  412. ? _context.__numberFormatters
  413. : undefined;
  414. }
  415. if ((process.env.NODE_ENV !== 'production')) {
  416. ctxOptions.__v_emitter = isPlainObject(_context)
  417. ? _context.__v_emitter
  418. : undefined;
  419. }
  420. const ctx = createCoreContext(ctxOptions);
  421. _isGlobal && setFallbackContext(ctx);
  422. return ctx;
  423. };
  424. _context = getCoreContext();
  425. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  426. // track reactivity
  427. function trackReactivityValues() {
  428. return [
  429. _locale.value,
  430. _fallbackLocale.value,
  431. _messages.value,
  432. _datetimeFormats.value,
  433. _numberFormats.value
  434. ]
  435. ;
  436. }
  437. // locale
  438. const locale = computed({
  439. get: () => _locale.value,
  440. set: val => {
  441. _locale.value = val;
  442. _context.locale = _locale.value;
  443. }
  444. });
  445. // fallbackLocale
  446. const fallbackLocale = computed({
  447. get: () => _fallbackLocale.value,
  448. set: val => {
  449. _fallbackLocale.value = val;
  450. _context.fallbackLocale = _fallbackLocale.value;
  451. updateFallbackLocale(_context, _locale.value, val);
  452. }
  453. });
  454. // messages
  455. const messages = computed(() => _messages.value);
  456. // datetimeFormats
  457. const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);
  458. // numberFormats
  459. const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);
  460. // getPostTranslationHandler
  461. function getPostTranslationHandler() {
  462. return isFunction(_postTranslation) ? _postTranslation : null;
  463. }
  464. // setPostTranslationHandler
  465. function setPostTranslationHandler(handler) {
  466. _postTranslation = handler;
  467. _context.postTranslation = handler;
  468. }
  469. // getMissingHandler
  470. function getMissingHandler() {
  471. return _missing;
  472. }
  473. // setMissingHandler
  474. function setMissingHandler(handler) {
  475. if (handler !== null) {
  476. _runtimeMissing = defineCoreMissingHandler(handler);
  477. }
  478. _missing = handler;
  479. _context.missing = _runtimeMissing;
  480. }
  481. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  482. ) {
  483. return type !== 'translate' || !arg.resolvedMessage;
  484. }
  485. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  486. trackReactivityValues(); // track reactive dependency
  487. // NOTE: experimental !!
  488. let ret;
  489. try {
  490. if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
  491. setAdditionalMeta(getMetaInfo());
  492. }
  493. if (!_isGlobal) {
  494. _context.fallbackContext = __root
  495. ? getFallbackContext()
  496. : undefined;
  497. }
  498. ret = fn(_context);
  499. }
  500. finally {
  501. if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
  502. setAdditionalMeta(null);
  503. }
  504. if (!_isGlobal) {
  505. _context.fallbackContext = undefined;
  506. }
  507. }
  508. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  509. isNumber(ret) &&
  510. ret === NOT_REOSLVED) ||
  511. (warnType === 'translate exists' && !ret) // for `te`
  512. ) {
  513. const [key, arg2] = argumentParser();
  514. if ((process.env.NODE_ENV !== 'production') &&
  515. __root &&
  516. isString(key) &&
  517. isResolvedTranslateMessage(warnType, arg2)) {
  518. if (_fallbackRoot &&
  519. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  520. isTranslateMissingWarn(_missingWarn, key))) {
  521. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  522. key,
  523. type: warnType
  524. }));
  525. }
  526. // for vue-devtools timeline event
  527. if ((process.env.NODE_ENV !== 'production')) {
  528. const { __v_emitter: emitter } = _context;
  529. if (emitter && _fallbackRoot) {
  530. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  531. type: warnType,
  532. key,
  533. to: 'global',
  534. groupId: `${warnType}:${key}`
  535. });
  536. }
  537. }
  538. }
  539. return __root && _fallbackRoot
  540. ? fallbackSuccess(__root)
  541. : fallbackFail(key);
  542. }
  543. else if (successCondition(ret)) {
  544. return ret;
  545. }
  546. else {
  547. /* istanbul ignore next */
  548. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  549. }
  550. };
  551. // t
  552. function t(...args) {
  553. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  554. }
  555. // rt
  556. function rt(...args) {
  557. const [arg1, arg2, arg3] = args;
  558. if (arg3 && !isObject(arg3)) {
  559. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  560. }
  561. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  562. }
  563. // d
  564. function d(...args) {
  565. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  566. }
  567. // n
  568. function n(...args) {
  569. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  570. }
  571. // for custom processor
  572. function normalize(values) {
  573. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  574. ? createTextNode(String(val))
  575. : val);
  576. }
  577. const interpolate = (val) => val;
  578. const processor = {
  579. normalize,
  580. interpolate,
  581. type: 'vnode'
  582. };
  583. // translateVNode, using for `i18n-t` component
  584. function translateVNode(...args) {
  585. return wrapWithDeps(context => {
  586. let ret;
  587. const _context = context;
  588. try {
  589. _context.processor = processor;
  590. ret = Reflect.apply(translate, null, [_context, ...args]);
  591. }
  592. finally {
  593. _context.processor = null;
  594. }
  595. return ret;
  596. }, () => parseTranslateArgs(...args), 'translate',
  597. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  598. root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  599. }
  600. // numberParts, using for `i18n-n` component
  601. function numberParts(...args) {
  602. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
  603. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  604. root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  605. }
  606. // datetimeParts, using for `i18n-d` component
  607. function datetimeParts(...args) {
  608. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
  609. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  610. root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  611. }
  612. function setPluralRules(rules) {
  613. _pluralRules = rules;
  614. _context.pluralRules = _pluralRules;
  615. }
  616. // te
  617. function te(key, locale) {
  618. return wrapWithDeps(() => {
  619. if (!key) {
  620. return false;
  621. }
  622. const targetLocale = isString(locale) ? locale : _locale.value;
  623. const message = getLocaleMessage(targetLocale);
  624. const resolved = _context.messageResolver(message, key);
  625. return !translateExistCompatible
  626. ? isMessageAST(resolved) ||
  627. isMessageFunction(resolved) ||
  628. isString(resolved)
  629. : resolved != null;
  630. }, () => [key], 'translate exists', root => {
  631. return Reflect.apply(root.te, root, [key, locale]);
  632. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  633. }
  634. function resolveMessages(key) {
  635. let messages = null;
  636. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  637. for (let i = 0; i < locales.length; i++) {
  638. const targetLocaleMessages = _messages.value[locales[i]] || {};
  639. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  640. if (messageValue != null) {
  641. messages = messageValue;
  642. break;
  643. }
  644. }
  645. return messages;
  646. }
  647. // tm
  648. function tm(key) {
  649. const messages = resolveMessages(key);
  650. // prettier-ignore
  651. return messages != null
  652. ? messages
  653. : __root
  654. ? __root.tm(key) || {}
  655. : {};
  656. }
  657. // getLocaleMessage
  658. function getLocaleMessage(locale) {
  659. return (_messages.value[locale] || {});
  660. }
  661. // setLocaleMessage
  662. function setLocaleMessage(locale, message) {
  663. if (flatJson) {
  664. const _message = { [locale]: message };
  665. for (const key in _message) {
  666. if (hasOwn(_message, key)) {
  667. handleFlatJson(_message[key]);
  668. }
  669. }
  670. message = _message[locale];
  671. }
  672. _messages.value[locale] = message;
  673. _context.messages = _messages.value;
  674. }
  675. // mergeLocaleMessage
  676. function mergeLocaleMessage(locale, message) {
  677. _messages.value[locale] = _messages.value[locale] || {};
  678. const _message = { [locale]: message };
  679. if (flatJson) {
  680. for (const key in _message) {
  681. if (hasOwn(_message, key)) {
  682. handleFlatJson(_message[key]);
  683. }
  684. }
  685. }
  686. message = _message[locale];
  687. deepCopy(message, _messages.value[locale]);
  688. _context.messages = _messages.value;
  689. }
  690. // getDateTimeFormat
  691. function getDateTimeFormat(locale) {
  692. return _datetimeFormats.value[locale] || {};
  693. }
  694. // setDateTimeFormat
  695. function setDateTimeFormat(locale, format) {
  696. _datetimeFormats.value[locale] = format;
  697. _context.datetimeFormats = _datetimeFormats.value;
  698. clearDateTimeFormat(_context, locale, format);
  699. }
  700. // mergeDateTimeFormat
  701. function mergeDateTimeFormat(locale, format) {
  702. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  703. _context.datetimeFormats = _datetimeFormats.value;
  704. clearDateTimeFormat(_context, locale, format);
  705. }
  706. // getNumberFormat
  707. function getNumberFormat(locale) {
  708. return _numberFormats.value[locale] || {};
  709. }
  710. // setNumberFormat
  711. function setNumberFormat(locale, format) {
  712. _numberFormats.value[locale] = format;
  713. _context.numberFormats = _numberFormats.value;
  714. clearNumberFormat(_context, locale, format);
  715. }
  716. // mergeNumberFormat
  717. function mergeNumberFormat(locale, format) {
  718. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  719. _context.numberFormats = _numberFormats.value;
  720. clearNumberFormat(_context, locale, format);
  721. }
  722. // for debug
  723. composerID++;
  724. // watch root locale & fallbackLocale
  725. if (__root && inBrowser) {
  726. watch(__root.locale, (val) => {
  727. if (_inheritLocale) {
  728. _locale.value = val;
  729. _context.locale = val;
  730. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  731. }
  732. });
  733. watch(__root.fallbackLocale, (val) => {
  734. if (_inheritLocale) {
  735. _fallbackLocale.value = val;
  736. _context.fallbackLocale = val;
  737. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  738. }
  739. });
  740. }
  741. // define basic composition API!
  742. const composer = {
  743. id: composerID,
  744. locale,
  745. fallbackLocale,
  746. get inheritLocale() {
  747. return _inheritLocale;
  748. },
  749. set inheritLocale(val) {
  750. _inheritLocale = val;
  751. if (val && __root) {
  752. _locale.value = __root.locale.value;
  753. _fallbackLocale.value = __root.fallbackLocale.value;
  754. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  755. }
  756. },
  757. get availableLocales() {
  758. return Object.keys(_messages.value).sort();
  759. },
  760. messages,
  761. get modifiers() {
  762. return _modifiers;
  763. },
  764. get pluralRules() {
  765. return _pluralRules || {};
  766. },
  767. get isGlobal() {
  768. return _isGlobal;
  769. },
  770. get missingWarn() {
  771. return _missingWarn;
  772. },
  773. set missingWarn(val) {
  774. _missingWarn = val;
  775. _context.missingWarn = _missingWarn;
  776. },
  777. get fallbackWarn() {
  778. return _fallbackWarn;
  779. },
  780. set fallbackWarn(val) {
  781. _fallbackWarn = val;
  782. _context.fallbackWarn = _fallbackWarn;
  783. },
  784. get fallbackRoot() {
  785. return _fallbackRoot;
  786. },
  787. set fallbackRoot(val) {
  788. _fallbackRoot = val;
  789. },
  790. get fallbackFormat() {
  791. return _fallbackFormat;
  792. },
  793. set fallbackFormat(val) {
  794. _fallbackFormat = val;
  795. _context.fallbackFormat = _fallbackFormat;
  796. },
  797. get warnHtmlMessage() {
  798. return _warnHtmlMessage;
  799. },
  800. set warnHtmlMessage(val) {
  801. _warnHtmlMessage = val;
  802. _context.warnHtmlMessage = val;
  803. },
  804. get escapeParameter() {
  805. return _escapeParameter;
  806. },
  807. set escapeParameter(val) {
  808. _escapeParameter = val;
  809. _context.escapeParameter = val;
  810. },
  811. t,
  812. getLocaleMessage,
  813. setLocaleMessage,
  814. mergeLocaleMessage,
  815. getPostTranslationHandler,
  816. setPostTranslationHandler,
  817. getMissingHandler,
  818. setMissingHandler,
  819. [SetPluralRulesSymbol]: setPluralRules
  820. };
  821. {
  822. composer.datetimeFormats = datetimeFormats;
  823. composer.numberFormats = numberFormats;
  824. composer.rt = rt;
  825. composer.te = te;
  826. composer.tm = tm;
  827. composer.d = d;
  828. composer.n = n;
  829. composer.getDateTimeFormat = getDateTimeFormat;
  830. composer.setDateTimeFormat = setDateTimeFormat;
  831. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  832. composer.getNumberFormat = getNumberFormat;
  833. composer.setNumberFormat = setNumberFormat;
  834. composer.mergeNumberFormat = mergeNumberFormat;
  835. composer[InejctWithOptionSymbol] = __injectWithOption;
  836. composer[TranslateVNodeSymbol] = translateVNode;
  837. composer[DatetimePartsSymbol] = datetimeParts;
  838. composer[NumberPartsSymbol] = numberParts;
  839. }
  840. // for vue-devtools timeline event
  841. if ((process.env.NODE_ENV !== 'production')) {
  842. composer[EnableEmitter] = (emitter) => {
  843. _context.__v_emitter = emitter;
  844. };
  845. composer[DisableEmitter] = () => {
  846. _context.__v_emitter = undefined;
  847. };
  848. }
  849. return composer;
  850. }
  851. /* eslint-enable @typescript-eslint/no-explicit-any */
  852. /* eslint-disable @typescript-eslint/no-explicit-any */
  853. /**
  854. * Convert to I18n Composer Options from VueI18n Options
  855. *
  856. * @internal
  857. */
  858. function convertComposerOptions(options) {
  859. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  860. const fallbackLocale = isString(options.fallbackLocale) ||
  861. isArray(options.fallbackLocale) ||
  862. isPlainObject(options.fallbackLocale) ||
  863. options.fallbackLocale === false
  864. ? options.fallbackLocale
  865. : locale;
  866. const missing = isFunction(options.missing) ? options.missing : undefined;
  867. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  868. isRegExp(options.silentTranslationWarn)
  869. ? !options.silentTranslationWarn
  870. : true;
  871. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  872. isRegExp(options.silentFallbackWarn)
  873. ? !options.silentFallbackWarn
  874. : true;
  875. const fallbackRoot = isBoolean(options.fallbackRoot)
  876. ? options.fallbackRoot
  877. : true;
  878. const fallbackFormat = !!options.formatFallbackMessages;
  879. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  880. const pluralizationRules = options.pluralizationRules;
  881. const postTranslation = isFunction(options.postTranslation)
  882. ? options.postTranslation
  883. : undefined;
  884. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  885. ? options.warnHtmlInMessage !== 'off'
  886. : true;
  887. const escapeParameter = !!options.escapeParameterHtml;
  888. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  889. if ((process.env.NODE_ENV !== 'production') && options.formatter) {
  890. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  891. }
  892. if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {
  893. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  894. }
  895. let messages = options.messages;
  896. if (isPlainObject(options.sharedMessages)) {
  897. const sharedMessages = options.sharedMessages;
  898. const locales = Object.keys(sharedMessages);
  899. messages = locales.reduce((messages, locale) => {
  900. const message = messages[locale] || (messages[locale] = {});
  901. assign(message, sharedMessages[locale]);
  902. return messages;
  903. }, (messages || {}));
  904. }
  905. const { __i18n, __root, __injectWithOption } = options;
  906. const datetimeFormats = options.datetimeFormats;
  907. const numberFormats = options.numberFormats;
  908. const flatJson = options.flatJson;
  909. const translateExistCompatible = options
  910. .translateExistCompatible;
  911. return {
  912. locale,
  913. fallbackLocale,
  914. messages,
  915. flatJson,
  916. datetimeFormats,
  917. numberFormats,
  918. missing,
  919. missingWarn,
  920. fallbackWarn,
  921. fallbackRoot,
  922. fallbackFormat,
  923. modifiers,
  924. pluralRules: pluralizationRules,
  925. postTranslation,
  926. warnHtmlMessage,
  927. escapeParameter,
  928. messageResolver: options.messageResolver,
  929. inheritLocale,
  930. translateExistCompatible,
  931. __i18n,
  932. __root,
  933. __injectWithOption
  934. };
  935. }
  936. /**
  937. * create VueI18n interface factory
  938. *
  939. * @internal
  940. */
  941. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  942. function createVueI18n(options = {}, VueI18nLegacy) {
  943. {
  944. const composer = createComposer(convertComposerOptions(options));
  945. const { __extender } = options;
  946. // defines VueI18n
  947. const vueI18n = {
  948. // id
  949. id: composer.id,
  950. // locale
  951. get locale() {
  952. return composer.locale.value;
  953. },
  954. set locale(val) {
  955. composer.locale.value = val;
  956. },
  957. // fallbackLocale
  958. get fallbackLocale() {
  959. return composer.fallbackLocale.value;
  960. },
  961. set fallbackLocale(val) {
  962. composer.fallbackLocale.value = val;
  963. },
  964. // messages
  965. get messages() {
  966. return composer.messages.value;
  967. },
  968. // datetimeFormats
  969. get datetimeFormats() {
  970. return composer.datetimeFormats.value;
  971. },
  972. // numberFormats
  973. get numberFormats() {
  974. return composer.numberFormats.value;
  975. },
  976. // availableLocales
  977. get availableLocales() {
  978. return composer.availableLocales;
  979. },
  980. // formatter
  981. get formatter() {
  982. (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  983. // dummy
  984. return {
  985. interpolate() {
  986. return [];
  987. }
  988. };
  989. },
  990. set formatter(val) {
  991. (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  992. },
  993. // missing
  994. get missing() {
  995. return composer.getMissingHandler();
  996. },
  997. set missing(handler) {
  998. composer.setMissingHandler(handler);
  999. },
  1000. // silentTranslationWarn
  1001. get silentTranslationWarn() {
  1002. return isBoolean(composer.missingWarn)
  1003. ? !composer.missingWarn
  1004. : composer.missingWarn;
  1005. },
  1006. set silentTranslationWarn(val) {
  1007. composer.missingWarn = isBoolean(val) ? !val : val;
  1008. },
  1009. // silentFallbackWarn
  1010. get silentFallbackWarn() {
  1011. return isBoolean(composer.fallbackWarn)
  1012. ? !composer.fallbackWarn
  1013. : composer.fallbackWarn;
  1014. },
  1015. set silentFallbackWarn(val) {
  1016. composer.fallbackWarn = isBoolean(val) ? !val : val;
  1017. },
  1018. // modifiers
  1019. get modifiers() {
  1020. return composer.modifiers;
  1021. },
  1022. // formatFallbackMessages
  1023. get formatFallbackMessages() {
  1024. return composer.fallbackFormat;
  1025. },
  1026. set formatFallbackMessages(val) {
  1027. composer.fallbackFormat = val;
  1028. },
  1029. // postTranslation
  1030. get postTranslation() {
  1031. return composer.getPostTranslationHandler();
  1032. },
  1033. set postTranslation(handler) {
  1034. composer.setPostTranslationHandler(handler);
  1035. },
  1036. // sync
  1037. get sync() {
  1038. return composer.inheritLocale;
  1039. },
  1040. set sync(val) {
  1041. composer.inheritLocale = val;
  1042. },
  1043. // warnInHtmlMessage
  1044. get warnHtmlInMessage() {
  1045. return composer.warnHtmlMessage ? 'warn' : 'off';
  1046. },
  1047. set warnHtmlInMessage(val) {
  1048. composer.warnHtmlMessage = val !== 'off';
  1049. },
  1050. // escapeParameterHtml
  1051. get escapeParameterHtml() {
  1052. return composer.escapeParameter;
  1053. },
  1054. set escapeParameterHtml(val) {
  1055. composer.escapeParameter = val;
  1056. },
  1057. // preserveDirectiveContent
  1058. get preserveDirectiveContent() {
  1059. (process.env.NODE_ENV !== 'production') &&
  1060. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  1061. return true;
  1062. },
  1063. set preserveDirectiveContent(val) {
  1064. (process.env.NODE_ENV !== 'production') &&
  1065. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  1066. },
  1067. // pluralizationRules
  1068. get pluralizationRules() {
  1069. return composer.pluralRules || {};
  1070. },
  1071. // for internal
  1072. __composer: composer,
  1073. // t
  1074. t(...args) {
  1075. const [arg1, arg2, arg3] = args;
  1076. const options = {};
  1077. let list = null;
  1078. let named = null;
  1079. if (!isString(arg1)) {
  1080. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  1081. }
  1082. const key = arg1;
  1083. if (isString(arg2)) {
  1084. options.locale = arg2;
  1085. }
  1086. else if (isArray(arg2)) {
  1087. list = arg2;
  1088. }
  1089. else if (isPlainObject(arg2)) {
  1090. named = arg2;
  1091. }
  1092. if (isArray(arg3)) {
  1093. list = arg3;
  1094. }
  1095. else if (isPlainObject(arg3)) {
  1096. named = arg3;
  1097. }
  1098. // return composer.t(key, (list || named || {}) as any, options)
  1099. return Reflect.apply(composer.t, composer, [
  1100. key,
  1101. (list || named || {}),
  1102. options
  1103. ]);
  1104. },
  1105. rt(...args) {
  1106. return Reflect.apply(composer.rt, composer, [...args]);
  1107. },
  1108. // tc
  1109. tc(...args) {
  1110. const [arg1, arg2, arg3] = args;
  1111. const options = { plural: 1 };
  1112. let list = null;
  1113. let named = null;
  1114. if (!isString(arg1)) {
  1115. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  1116. }
  1117. const key = arg1;
  1118. if (isString(arg2)) {
  1119. options.locale = arg2;
  1120. }
  1121. else if (isNumber(arg2)) {
  1122. options.plural = arg2;
  1123. }
  1124. else if (isArray(arg2)) {
  1125. list = arg2;
  1126. }
  1127. else if (isPlainObject(arg2)) {
  1128. named = arg2;
  1129. }
  1130. if (isString(arg3)) {
  1131. options.locale = arg3;
  1132. }
  1133. else if (isArray(arg3)) {
  1134. list = arg3;
  1135. }
  1136. else if (isPlainObject(arg3)) {
  1137. named = arg3;
  1138. }
  1139. // return composer.t(key, (list || named || {}) as any, options)
  1140. return Reflect.apply(composer.t, composer, [
  1141. key,
  1142. (list || named || {}),
  1143. options
  1144. ]);
  1145. },
  1146. // te
  1147. te(key, locale) {
  1148. return composer.te(key, locale);
  1149. },
  1150. // tm
  1151. tm(key) {
  1152. return composer.tm(key);
  1153. },
  1154. // getLocaleMessage
  1155. getLocaleMessage(locale) {
  1156. return composer.getLocaleMessage(locale);
  1157. },
  1158. // setLocaleMessage
  1159. setLocaleMessage(locale, message) {
  1160. composer.setLocaleMessage(locale, message);
  1161. },
  1162. // mergeLocaleMessage
  1163. mergeLocaleMessage(locale, message) {
  1164. composer.mergeLocaleMessage(locale, message);
  1165. },
  1166. // d
  1167. d(...args) {
  1168. return Reflect.apply(composer.d, composer, [...args]);
  1169. },
  1170. // getDateTimeFormat
  1171. getDateTimeFormat(locale) {
  1172. return composer.getDateTimeFormat(locale);
  1173. },
  1174. // setDateTimeFormat
  1175. setDateTimeFormat(locale, format) {
  1176. composer.setDateTimeFormat(locale, format);
  1177. },
  1178. // mergeDateTimeFormat
  1179. mergeDateTimeFormat(locale, format) {
  1180. composer.mergeDateTimeFormat(locale, format);
  1181. },
  1182. // n
  1183. n(...args) {
  1184. return Reflect.apply(composer.n, composer, [...args]);
  1185. },
  1186. // getNumberFormat
  1187. getNumberFormat(locale) {
  1188. return composer.getNumberFormat(locale);
  1189. },
  1190. // setNumberFormat
  1191. setNumberFormat(locale, format) {
  1192. composer.setNumberFormat(locale, format);
  1193. },
  1194. // mergeNumberFormat
  1195. mergeNumberFormat(locale, format) {
  1196. composer.mergeNumberFormat(locale, format);
  1197. },
  1198. // getChoiceIndex
  1199. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  1200. getChoiceIndex(choice, choicesLength) {
  1201. (process.env.NODE_ENV !== 'production') &&
  1202. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
  1203. return -1;
  1204. }
  1205. };
  1206. vueI18n.__extender = __extender;
  1207. // for vue-devtools timeline event
  1208. if ((process.env.NODE_ENV !== 'production')) {
  1209. vueI18n.__enableEmitter = (emitter) => {
  1210. const __composer = composer;
  1211. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  1212. };
  1213. vueI18n.__disableEmitter = () => {
  1214. const __composer = composer;
  1215. __composer[DisableEmitter] && __composer[DisableEmitter]();
  1216. };
  1217. }
  1218. return vueI18n;
  1219. }
  1220. }
  1221. /* eslint-enable @typescript-eslint/no-explicit-any */
  1222. const baseFormatProps = {
  1223. tag: {
  1224. type: [String, Object]
  1225. },
  1226. locale: {
  1227. type: String
  1228. },
  1229. scope: {
  1230. type: String,
  1231. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  1232. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  1233. default: 'parent' /* ComponentI18nScope */
  1234. },
  1235. i18n: {
  1236. type: Object
  1237. }
  1238. };
  1239. function getInterpolateArg(
  1240. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1241. { slots }, // SetupContext,
  1242. keys) {
  1243. if (keys.length === 1 && keys[0] === 'default') {
  1244. // default slot with list
  1245. const ret = slots.default ? slots.default() : [];
  1246. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1247. return ret.reduce((slot, current) => {
  1248. return [
  1249. ...slot,
  1250. // prettier-ignore
  1251. ...(current.type === Fragment ? current.children : [current]
  1252. )
  1253. ];
  1254. }, []);
  1255. }
  1256. else {
  1257. // named slots
  1258. return keys.reduce((arg, key) => {
  1259. const slot = slots[key];
  1260. if (slot) {
  1261. arg[key] = slot();
  1262. }
  1263. return arg;
  1264. }, {});
  1265. }
  1266. }
  1267. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1268. function getFragmentableTag(tag) {
  1269. return Fragment ;
  1270. }
  1271. const TranslationImpl = /*#__PURE__*/ defineComponent({
  1272. /* eslint-disable */
  1273. name: 'i18n-t',
  1274. props: assign({
  1275. keypath: {
  1276. type: String,
  1277. required: true
  1278. },
  1279. plural: {
  1280. type: [Number, String],
  1281. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1282. validator: (val) => isNumber(val) || !isNaN(val)
  1283. }
  1284. }, baseFormatProps),
  1285. /* eslint-enable */
  1286. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1287. setup(props, context) {
  1288. const { slots, attrs } = context;
  1289. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  1290. const i18n = props.i18n ||
  1291. useI18n({
  1292. useScope: props.scope,
  1293. __useComponent: true
  1294. });
  1295. return () => {
  1296. const keys = Object.keys(slots).filter(key => key !== '_');
  1297. const options = {};
  1298. if (props.locale) {
  1299. options.locale = props.locale;
  1300. }
  1301. if (props.plural !== undefined) {
  1302. options.plural = isString(props.plural) ? +props.plural : props.plural;
  1303. }
  1304. const arg = getInterpolateArg(context, keys);
  1305. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1306. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  1307. const assignedAttrs = assign({}, attrs);
  1308. const tag = isString(props.tag) || isObject(props.tag)
  1309. ? props.tag
  1310. : getFragmentableTag();
  1311. return h(tag, assignedAttrs, children);
  1312. };
  1313. }
  1314. });
  1315. /**
  1316. * export the public type for h/tsx inference
  1317. * also to avoid inline import() in generated d.ts files
  1318. */
  1319. /**
  1320. * Translation Component
  1321. *
  1322. * @remarks
  1323. * See the following items for property about details
  1324. *
  1325. * @VueI18nSee [TranslationProps](component#translationprops)
  1326. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1327. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  1328. *
  1329. * @example
  1330. * ```html
  1331. * <div id="app">
  1332. * <!-- ... -->
  1333. * <i18n keypath="term" tag="label" for="tos">
  1334. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  1335. * </i18n>
  1336. * <!-- ... -->
  1337. * </div>
  1338. * ```
  1339. * ```js
  1340. * import { createApp } from 'vue'
  1341. * import { createI18n } from 'vue-i18n'
  1342. *
  1343. * const messages = {
  1344. * en: {
  1345. * tos: 'Term of Service',
  1346. * term: 'I accept xxx {0}.'
  1347. * },
  1348. * ja: {
  1349. * tos: '利用規約',
  1350. * term: '私は xxx の{0}に同意します。'
  1351. * }
  1352. * }
  1353. *
  1354. * const i18n = createI18n({
  1355. * locale: 'en',
  1356. * messages
  1357. * })
  1358. *
  1359. * const app = createApp({
  1360. * data: {
  1361. * url: '/term'
  1362. * }
  1363. * }).use(i18n).mount('#app')
  1364. * ```
  1365. *
  1366. * @VueI18nComponent
  1367. */
  1368. const Translation = TranslationImpl;
  1369. const I18nT = Translation;
  1370. function isVNode(target) {
  1371. return isArray(target) && !isString(target[0]);
  1372. }
  1373. function renderFormatter(props, context, slotKeys, partFormatter) {
  1374. const { slots, attrs } = context;
  1375. return () => {
  1376. const options = { part: true };
  1377. let overrides = {};
  1378. if (props.locale) {
  1379. options.locale = props.locale;
  1380. }
  1381. if (isString(props.format)) {
  1382. options.key = props.format;
  1383. }
  1384. else if (isObject(props.format)) {
  1385. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1386. if (isString(props.format.key)) {
  1387. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1388. options.key = props.format.key;
  1389. }
  1390. // Filter out number format options only
  1391. overrides = Object.keys(props.format).reduce((options, prop) => {
  1392. return slotKeys.includes(prop)
  1393. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  1394. : options;
  1395. }, {});
  1396. }
  1397. const parts = partFormatter(...[props.value, options, overrides]);
  1398. let children = [options.key];
  1399. if (isArray(parts)) {
  1400. children = parts.map((part, index) => {
  1401. const slot = slots[part.type];
  1402. const node = slot
  1403. ? slot({ [part.type]: part.value, index, parts })
  1404. : [part.value];
  1405. if (isVNode(node)) {
  1406. node[0].key = `${part.type}-${index}`;
  1407. }
  1408. return node;
  1409. });
  1410. }
  1411. else if (isString(parts)) {
  1412. children = [parts];
  1413. }
  1414. const assignedAttrs = assign({}, attrs);
  1415. const tag = isString(props.tag) || isObject(props.tag)
  1416. ? props.tag
  1417. : getFragmentableTag();
  1418. return h(tag, assignedAttrs, children);
  1419. };
  1420. }
  1421. const NumberFormatImpl = /*#__PURE__*/ defineComponent({
  1422. /* eslint-disable */
  1423. name: 'i18n-n',
  1424. props: assign({
  1425. value: {
  1426. type: Number,
  1427. required: true
  1428. },
  1429. format: {
  1430. type: [String, Object]
  1431. }
  1432. }, baseFormatProps),
  1433. /* eslint-enable */
  1434. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1435. setup(props, context) {
  1436. const i18n = props.i18n ||
  1437. useI18n({
  1438. useScope: props.scope,
  1439. __useComponent: true
  1440. });
  1441. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  1442. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1443. i18n[NumberPartsSymbol](...args));
  1444. }
  1445. });
  1446. /**
  1447. * export the public type for h/tsx inference
  1448. * also to avoid inline import() in generated d.ts files
  1449. */
  1450. /**
  1451. * Number Format Component
  1452. *
  1453. * @remarks
  1454. * See the following items for property about details
  1455. *
  1456. * @VueI18nSee [FormattableProps](component#formattableprops)
  1457. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1458. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  1459. *
  1460. * @VueI18nDanger
  1461. * 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)
  1462. *
  1463. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  1464. *
  1465. * @VueI18nComponent
  1466. */
  1467. const NumberFormat = NumberFormatImpl;
  1468. const I18nN = NumberFormat;
  1469. const DatetimeFormatImpl = /* #__PURE__*/ defineComponent({
  1470. /* eslint-disable */
  1471. name: 'i18n-d',
  1472. props: assign({
  1473. value: {
  1474. type: [Number, Date],
  1475. required: true
  1476. },
  1477. format: {
  1478. type: [String, Object]
  1479. }
  1480. }, baseFormatProps),
  1481. /* eslint-enable */
  1482. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1483. setup(props, context) {
  1484. const i18n = props.i18n ||
  1485. useI18n({
  1486. useScope: props.scope,
  1487. __useComponent: true
  1488. });
  1489. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  1490. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1491. i18n[DatetimePartsSymbol](...args));
  1492. }
  1493. });
  1494. /**
  1495. * Datetime Format Component
  1496. *
  1497. * @remarks
  1498. * See the following items for property about details
  1499. *
  1500. * @VueI18nSee [FormattableProps](component#formattableprops)
  1501. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  1502. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  1503. *
  1504. * @VueI18nDanger
  1505. * 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)
  1506. *
  1507. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  1508. *
  1509. * @VueI18nComponent
  1510. */
  1511. const DatetimeFormat = DatetimeFormatImpl;
  1512. const I18nD = DatetimeFormat;
  1513. function getComposer$2(i18n, instance) {
  1514. const i18nInternal = i18n;
  1515. if (i18n.mode === 'composition') {
  1516. return (i18nInternal.__getInstance(instance) || i18n.global);
  1517. }
  1518. else {
  1519. const vueI18n = i18nInternal.__getInstance(instance);
  1520. return vueI18n != null
  1521. ? vueI18n.__composer
  1522. : i18n.global.__composer;
  1523. }
  1524. }
  1525. function vTDirective(i18n) {
  1526. const _process = (binding) => {
  1527. const { instance, modifiers, value } = binding;
  1528. /* istanbul ignore if */
  1529. if (!instance || !instance.$) {
  1530. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  1531. }
  1532. const composer = getComposer$2(i18n, instance.$);
  1533. if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {
  1534. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
  1535. }
  1536. const parsedValue = parseValue(value);
  1537. return [
  1538. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  1539. composer
  1540. ];
  1541. };
  1542. const register = (el, binding) => {
  1543. const [textContent, composer] = _process(binding);
  1544. if (inBrowser && i18n.global === composer) {
  1545. // global scope only
  1546. el.__i18nWatcher = watch(composer.locale, () => {
  1547. binding.instance && binding.instance.$forceUpdate();
  1548. });
  1549. }
  1550. el.__composer = composer;
  1551. el.textContent = textContent;
  1552. };
  1553. const unregister = (el) => {
  1554. if (inBrowser && el.__i18nWatcher) {
  1555. el.__i18nWatcher();
  1556. el.__i18nWatcher = undefined;
  1557. delete el.__i18nWatcher;
  1558. }
  1559. if (el.__composer) {
  1560. el.__composer = undefined;
  1561. delete el.__composer;
  1562. }
  1563. };
  1564. const update = (el, { value }) => {
  1565. if (el.__composer) {
  1566. const composer = el.__composer;
  1567. const parsedValue = parseValue(value);
  1568. el.textContent = Reflect.apply(composer.t, composer, [
  1569. ...makeParams(parsedValue)
  1570. ]);
  1571. }
  1572. };
  1573. const getSSRProps = (binding) => {
  1574. const [textContent] = _process(binding);
  1575. return { textContent };
  1576. };
  1577. return {
  1578. created: register,
  1579. unmounted: unregister,
  1580. beforeUpdate: update,
  1581. getSSRProps
  1582. };
  1583. }
  1584. function parseValue(value) {
  1585. if (isString(value)) {
  1586. return { path: value };
  1587. }
  1588. else if (isPlainObject(value)) {
  1589. if (!('path' in value)) {
  1590. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  1591. }
  1592. return value;
  1593. }
  1594. else {
  1595. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  1596. }
  1597. }
  1598. function makeParams(value) {
  1599. const { path, locale, args, choice, plural } = value;
  1600. const options = {};
  1601. const named = args || {};
  1602. if (isString(locale)) {
  1603. options.locale = locale;
  1604. }
  1605. if (isNumber(choice)) {
  1606. options.plural = choice;
  1607. }
  1608. if (isNumber(plural)) {
  1609. options.plural = plural;
  1610. }
  1611. return [path, named, options];
  1612. }
  1613. function apply(app, i18n, ...options) {
  1614. const pluginOptions = isPlainObject(options[0])
  1615. ? options[0]
  1616. : {};
  1617. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  1618. const globalInstall = isBoolean(pluginOptions.globalInstall)
  1619. ? pluginOptions.globalInstall
  1620. : true;
  1621. if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {
  1622. warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
  1623. name: Translation.name
  1624. }));
  1625. }
  1626. if (globalInstall) {
  1627. [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));
  1628. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  1629. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  1630. }
  1631. // install directive
  1632. {
  1633. app.directive('t', vTDirective(i18n));
  1634. }
  1635. }
  1636. const VueDevToolsLabels = {
  1637. ["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',
  1638. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',
  1639. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'
  1640. };
  1641. const VueDevToolsPlaceholders = {
  1642. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  1643. };
  1644. const VueDevToolsTimelineColors = {
  1645. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19
  1646. };
  1647. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  1648. let devtoolsApi;
  1649. async function enableDevTools(app, i18n) {
  1650. return new Promise((resolve, reject) => {
  1651. try {
  1652. setupDevtoolsPlugin({
  1653. id: "vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */,
  1654. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */],
  1655. packageName: 'vue-i18n',
  1656. homepage: 'https://vue-i18n.intlify.dev',
  1657. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  1658. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  1659. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  1660. }, api => {
  1661. devtoolsApi = api;
  1662. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  1663. updateComponentTreeTags(componentInstance, treeNode, i18n);
  1664. });
  1665. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  1666. if (componentInstance.vnode.el &&
  1667. componentInstance.vnode.el.__VUE_I18N__ &&
  1668. instanceData) {
  1669. if (i18n.mode === 'legacy') {
  1670. // ignore global scope on legacy mode
  1671. if (componentInstance.vnode.el.__VUE_I18N__ !==
  1672. i18n.global.__composer) {
  1673. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  1674. }
  1675. }
  1676. else {
  1677. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  1678. }
  1679. }
  1680. });
  1681. api.addInspector({
  1682. id: "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,
  1683. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],
  1684. icon: 'language',
  1685. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]
  1686. });
  1687. api.on.getInspectorTree(payload => {
  1688. if (payload.app === app &&
  1689. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  1690. registerScope(payload, i18n);
  1691. }
  1692. });
  1693. const roots = new Map();
  1694. api.on.getInspectorState(async (payload) => {
  1695. if (payload.app === app &&
  1696. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  1697. api.unhighlightElement();
  1698. inspectScope(payload, i18n);
  1699. if (payload.nodeId === 'global') {
  1700. if (!roots.has(payload.app)) {
  1701. const [root] = await api.getComponentInstances(payload.app);
  1702. roots.set(payload.app, root);
  1703. }
  1704. api.highlightElement(roots.get(payload.app));
  1705. }
  1706. else {
  1707. const instance = getComponentInstance(payload.nodeId, i18n);
  1708. instance && api.highlightElement(instance);
  1709. }
  1710. }
  1711. });
  1712. api.on.editInspectorState(payload => {
  1713. if (payload.app === app &&
  1714. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  1715. editScope(payload, i18n);
  1716. }
  1717. });
  1718. api.addTimelineLayer({
  1719. id: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  1720. label: VueDevToolsLabels["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */],
  1721. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]
  1722. });
  1723. resolve(true);
  1724. });
  1725. }
  1726. catch (e) {
  1727. console.error(e);
  1728. reject(false);
  1729. }
  1730. });
  1731. }
  1732. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1733. function getI18nScopeLable(instance) {
  1734. return (instance.type.name ||
  1735. instance.type.displayName ||
  1736. instance.type.__file ||
  1737. 'Anonymous');
  1738. }
  1739. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  1740. treeNode, i18n) {
  1741. // prettier-ignore
  1742. const global = i18n.mode === 'composition'
  1743. ? i18n.global
  1744. : i18n.global.__composer;
  1745. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  1746. // add custom tags local scope only
  1747. if (instance.vnode.el.__VUE_I18N__ !== global) {
  1748. const tag = {
  1749. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  1750. textColor: 0x000000,
  1751. backgroundColor: 0xffcd19
  1752. };
  1753. treeNode.tags.push(tag);
  1754. }
  1755. }
  1756. }
  1757. function inspectComposer(instanceData, composer) {
  1758. const type = VUE_I18N_COMPONENT_TYPES;
  1759. instanceData.state.push({
  1760. type,
  1761. key: 'locale',
  1762. editable: true,
  1763. value: composer.locale.value
  1764. });
  1765. instanceData.state.push({
  1766. type,
  1767. key: 'availableLocales',
  1768. editable: false,
  1769. value: composer.availableLocales
  1770. });
  1771. instanceData.state.push({
  1772. type,
  1773. key: 'fallbackLocale',
  1774. editable: true,
  1775. value: composer.fallbackLocale.value
  1776. });
  1777. instanceData.state.push({
  1778. type,
  1779. key: 'inheritLocale',
  1780. editable: true,
  1781. value: composer.inheritLocale
  1782. });
  1783. instanceData.state.push({
  1784. type,
  1785. key: 'messages',
  1786. editable: false,
  1787. value: getLocaleMessageValue(composer.messages.value)
  1788. });
  1789. {
  1790. instanceData.state.push({
  1791. type,
  1792. key: 'datetimeFormats',
  1793. editable: false,
  1794. value: composer.datetimeFormats.value
  1795. });
  1796. instanceData.state.push({
  1797. type,
  1798. key: 'numberFormats',
  1799. editable: false,
  1800. value: composer.numberFormats.value
  1801. });
  1802. }
  1803. }
  1804. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1805. function getLocaleMessageValue(messages) {
  1806. const value = {};
  1807. Object.keys(messages).forEach((key) => {
  1808. const v = messages[key];
  1809. if (isFunction(v) && 'source' in v) {
  1810. value[key] = getMessageFunctionDetails(v);
  1811. }
  1812. else if (isMessageAST(v) && v.loc && v.loc.source) {
  1813. value[key] = v.loc.source;
  1814. }
  1815. else if (isObject(v)) {
  1816. value[key] = getLocaleMessageValue(v);
  1817. }
  1818. else {
  1819. value[key] = v;
  1820. }
  1821. });
  1822. return value;
  1823. }
  1824. const ESC = {
  1825. '<': '&lt;',
  1826. '>': '&gt;',
  1827. '"': '&quot;',
  1828. '&': '&amp;'
  1829. };
  1830. function escape(s) {
  1831. return s.replace(/[<>"&]/g, escapeChar);
  1832. }
  1833. function escapeChar(a) {
  1834. return ESC[a] || a;
  1835. }
  1836. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1837. function getMessageFunctionDetails(func) {
  1838. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  1839. return {
  1840. _custom: {
  1841. type: 'function',
  1842. display: `<span>ƒ</span> ${argString}`
  1843. }
  1844. };
  1845. }
  1846. function registerScope(payload, i18n) {
  1847. payload.rootNodes.push({
  1848. id: 'global',
  1849. label: 'Global Scope'
  1850. });
  1851. // prettier-ignore
  1852. const global = i18n.mode === 'composition'
  1853. ? i18n.global
  1854. : i18n.global.__composer;
  1855. for (const [keyInstance, instance] of i18n.__instances) {
  1856. // prettier-ignore
  1857. const composer = i18n.mode === 'composition'
  1858. ? instance
  1859. : instance.__composer;
  1860. if (global === composer) {
  1861. continue;
  1862. }
  1863. payload.rootNodes.push({
  1864. id: composer.id.toString(),
  1865. label: `${getI18nScopeLable(keyInstance)} Scope`
  1866. });
  1867. }
  1868. }
  1869. function getComponentInstance(nodeId, i18n) {
  1870. let instance = null;
  1871. if (nodeId !== 'global') {
  1872. for (const [component, composer] of i18n.__instances.entries()) {
  1873. if (composer.id.toString() === nodeId) {
  1874. instance = component;
  1875. break;
  1876. }
  1877. }
  1878. }
  1879. return instance;
  1880. }
  1881. function getComposer$1(nodeId, i18n) {
  1882. if (nodeId === 'global') {
  1883. return i18n.mode === 'composition'
  1884. ? i18n.global
  1885. : i18n.global.__composer;
  1886. }
  1887. else {
  1888. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  1889. if (instance) {
  1890. return i18n.mode === 'composition'
  1891. ? instance
  1892. : instance.__composer;
  1893. }
  1894. else {
  1895. return null;
  1896. }
  1897. }
  1898. }
  1899. function inspectScope(payload, i18n
  1900. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1901. ) {
  1902. const composer = getComposer$1(payload.nodeId, i18n);
  1903. if (composer) {
  1904. // TODO:
  1905. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1906. payload.state = makeScopeInspectState(composer);
  1907. }
  1908. return null;
  1909. }
  1910. function makeScopeInspectState(composer) {
  1911. const state = {};
  1912. const localeType = 'Locale related info';
  1913. const localeStates = [
  1914. {
  1915. type: localeType,
  1916. key: 'locale',
  1917. editable: true,
  1918. value: composer.locale.value
  1919. },
  1920. {
  1921. type: localeType,
  1922. key: 'fallbackLocale',
  1923. editable: true,
  1924. value: composer.fallbackLocale.value
  1925. },
  1926. {
  1927. type: localeType,
  1928. key: 'availableLocales',
  1929. editable: false,
  1930. value: composer.availableLocales
  1931. },
  1932. {
  1933. type: localeType,
  1934. key: 'inheritLocale',
  1935. editable: true,
  1936. value: composer.inheritLocale
  1937. }
  1938. ];
  1939. state[localeType] = localeStates;
  1940. const localeMessagesType = 'Locale messages info';
  1941. const localeMessagesStates = [
  1942. {
  1943. type: localeMessagesType,
  1944. key: 'messages',
  1945. editable: false,
  1946. value: getLocaleMessageValue(composer.messages.value)
  1947. }
  1948. ];
  1949. state[localeMessagesType] = localeMessagesStates;
  1950. {
  1951. const datetimeFormatsType = 'Datetime formats info';
  1952. const datetimeFormatsStates = [
  1953. {
  1954. type: datetimeFormatsType,
  1955. key: 'datetimeFormats',
  1956. editable: false,
  1957. value: composer.datetimeFormats.value
  1958. }
  1959. ];
  1960. state[datetimeFormatsType] = datetimeFormatsStates;
  1961. const numberFormatsType = 'Datetime formats info';
  1962. const numberFormatsStates = [
  1963. {
  1964. type: numberFormatsType,
  1965. key: 'numberFormats',
  1966. editable: false,
  1967. value: composer.numberFormats.value
  1968. }
  1969. ];
  1970. state[numberFormatsType] = numberFormatsStates;
  1971. }
  1972. return state;
  1973. }
  1974. function addTimelineEvent(event, payload) {
  1975. if (devtoolsApi) {
  1976. let groupId;
  1977. if (payload && 'groupId' in payload) {
  1978. groupId = payload.groupId;
  1979. delete payload.groupId;
  1980. }
  1981. devtoolsApi.addTimelineEvent({
  1982. layerId: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  1983. event: {
  1984. title: event,
  1985. groupId,
  1986. time: Date.now(),
  1987. meta: {},
  1988. data: payload || {},
  1989. logType: event === "compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */
  1990. ? 'error'
  1991. : event === "fallback" /* VueDevToolsTimelineEvents.FALBACK */ ||
  1992. event === "missing" /* VueDevToolsTimelineEvents.MISSING */
  1993. ? 'warning'
  1994. : 'default'
  1995. }
  1996. });
  1997. }
  1998. }
  1999. function editScope(payload, i18n) {
  2000. const composer = getComposer$1(payload.nodeId, i18n);
  2001. if (composer) {
  2002. const [field] = payload.path;
  2003. if (field === 'locale' && isString(payload.state.value)) {
  2004. composer.locale.value = payload.state.value;
  2005. }
  2006. else if (field === 'fallbackLocale' &&
  2007. (isString(payload.state.value) ||
  2008. isArray(payload.state.value) ||
  2009. isObject(payload.state.value))) {
  2010. composer.fallbackLocale.value = payload.state.value;
  2011. }
  2012. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  2013. composer.inheritLocale = payload.state.value;
  2014. }
  2015. }
  2016. }
  2017. /**
  2018. * Supports compatibility for legacy vue-i18n APIs
  2019. * This mixin is used when we use vue-i18n@v9.x or later
  2020. */
  2021. function defineMixin(vuei18n, composer, i18n) {
  2022. return {
  2023. beforeCreate() {
  2024. const instance = getCurrentInstance();
  2025. /* istanbul ignore if */
  2026. if (!instance) {
  2027. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  2028. }
  2029. const options = this.$options;
  2030. if (options.i18n) {
  2031. const optionsI18n = options.i18n;
  2032. if (options.__i18n) {
  2033. optionsI18n.__i18n = options.__i18n;
  2034. }
  2035. optionsI18n.__root = composer;
  2036. if (this === this.$root) {
  2037. // merge option and gttach global
  2038. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  2039. }
  2040. else {
  2041. optionsI18n.__injectWithOption = true;
  2042. optionsI18n.__extender = i18n.__vueI18nExtend;
  2043. // atttach local VueI18n instance
  2044. this.$i18n = createVueI18n(optionsI18n);
  2045. // extend VueI18n instance
  2046. const _vueI18n = this.$i18n;
  2047. if (_vueI18n.__extender) {
  2048. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  2049. }
  2050. }
  2051. }
  2052. else if (options.__i18n) {
  2053. if (this === this.$root) {
  2054. // merge option and gttach global
  2055. this.$i18n = mergeToGlobal(vuei18n, options);
  2056. }
  2057. else {
  2058. // atttach local VueI18n instance
  2059. this.$i18n = createVueI18n({
  2060. __i18n: options.__i18n,
  2061. __injectWithOption: true,
  2062. __extender: i18n.__vueI18nExtend,
  2063. __root: composer
  2064. });
  2065. // extend VueI18n instance
  2066. const _vueI18n = this.$i18n;
  2067. if (_vueI18n.__extender) {
  2068. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  2069. }
  2070. }
  2071. }
  2072. else {
  2073. // attach global VueI18n instance
  2074. this.$i18n = vuei18n;
  2075. }
  2076. if (options.__i18nGlobal) {
  2077. adjustI18nResources(composer, options, options);
  2078. }
  2079. // defines vue-i18n legacy APIs
  2080. this.$t = (...args) => this.$i18n.t(...args);
  2081. this.$rt = (...args) => this.$i18n.rt(...args);
  2082. this.$tc = (...args) => this.$i18n.tc(...args);
  2083. this.$te = (key, locale) => this.$i18n.te(key, locale);
  2084. this.$d = (...args) => this.$i18n.d(...args);
  2085. this.$n = (...args) => this.$i18n.n(...args);
  2086. this.$tm = (key) => this.$i18n.tm(key);
  2087. i18n.__setInstance(instance, this.$i18n);
  2088. },
  2089. mounted() {
  2090. /* istanbul ignore if */
  2091. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
  2092. !false &&
  2093. this.$el &&
  2094. this.$i18n) {
  2095. const _vueI18n = this.$i18n;
  2096. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  2097. const emitter = (this.__v_emitter =
  2098. createEmitter());
  2099. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  2100. emitter.on('*', addTimelineEvent);
  2101. }
  2102. },
  2103. unmounted() {
  2104. const instance = getCurrentInstance();
  2105. /* istanbul ignore if */
  2106. if (!instance) {
  2107. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  2108. }
  2109. const _vueI18n = this.$i18n;
  2110. /* istanbul ignore if */
  2111. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
  2112. !false &&
  2113. this.$el &&
  2114. this.$el.__VUE_I18N__) {
  2115. if (this.__v_emitter) {
  2116. this.__v_emitter.off('*', addTimelineEvent);
  2117. delete this.__v_emitter;
  2118. }
  2119. if (this.$i18n) {
  2120. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  2121. delete this.$el.__VUE_I18N__;
  2122. }
  2123. }
  2124. delete this.$t;
  2125. delete this.$rt;
  2126. delete this.$tc;
  2127. delete this.$te;
  2128. delete this.$d;
  2129. delete this.$n;
  2130. delete this.$tm;
  2131. if (_vueI18n.__disposer) {
  2132. _vueI18n.__disposer();
  2133. delete _vueI18n.__disposer;
  2134. delete _vueI18n.__extender;
  2135. }
  2136. i18n.__deleteInstance(instance);
  2137. delete this.$i18n;
  2138. }
  2139. };
  2140. }
  2141. function mergeToGlobal(g, options) {
  2142. g.locale = options.locale || g.locale;
  2143. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  2144. g.missing = options.missing || g.missing;
  2145. g.silentTranslationWarn =
  2146. options.silentTranslationWarn || g.silentFallbackWarn;
  2147. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  2148. g.formatFallbackMessages =
  2149. options.formatFallbackMessages || g.formatFallbackMessages;
  2150. g.postTranslation = options.postTranslation || g.postTranslation;
  2151. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  2152. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  2153. g.sync = options.sync || g.sync;
  2154. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  2155. const messages = getLocaleMessages(g.locale, {
  2156. messages: options.messages,
  2157. __i18n: options.__i18n
  2158. });
  2159. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  2160. if (options.datetimeFormats) {
  2161. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  2162. }
  2163. if (options.numberFormats) {
  2164. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  2165. }
  2166. return g;
  2167. }
  2168. /**
  2169. * Injection key for {@link useI18n}
  2170. *
  2171. * @remarks
  2172. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  2173. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  2174. *
  2175. * @VueI18nGeneral
  2176. */
  2177. const I18nInjectionKey =
  2178. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  2179. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  2180. function createI18n(options = {}, VueI18nLegacy) {
  2181. // prettier-ignore
  2182. const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)
  2183. ? options.legacy
  2184. : __VUE_I18N_LEGACY_API__;
  2185. // prettier-ignore
  2186. const __globalInjection = isBoolean(options.globalInjection)
  2187. ? options.globalInjection
  2188. : true;
  2189. // prettier-ignore
  2190. const __allowComposition = __VUE_I18N_LEGACY_API__ && __legacyMode
  2191. ? !!options.allowComposition
  2192. : true;
  2193. const __instances = new Map();
  2194. const [globalScope, __global] = createGlobal(options, __legacyMode);
  2195. const symbol = /* #__PURE__*/ makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');
  2196. if ((process.env.NODE_ENV !== 'production')) {
  2197. if (__legacyMode && __allowComposition && !false) {
  2198. warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));
  2199. }
  2200. }
  2201. function __getInstance(component) {
  2202. return __instances.get(component) || null;
  2203. }
  2204. function __setInstance(component, instance) {
  2205. __instances.set(component, instance);
  2206. }
  2207. function __deleteInstance(component) {
  2208. __instances.delete(component);
  2209. }
  2210. {
  2211. const i18n = {
  2212. // mode
  2213. get mode() {
  2214. return __VUE_I18N_LEGACY_API__ && __legacyMode
  2215. ? 'legacy'
  2216. : 'composition';
  2217. },
  2218. // allowComposition
  2219. get allowComposition() {
  2220. return __allowComposition;
  2221. },
  2222. // install plugin
  2223. async install(app, ...options) {
  2224. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
  2225. !false) {
  2226. app.__VUE_I18N__ = i18n;
  2227. }
  2228. // setup global provider
  2229. app.__VUE_I18N_SYMBOL__ = symbol;
  2230. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  2231. // set composer & vuei18n extend hook options from plugin options
  2232. if (isPlainObject(options[0])) {
  2233. const opts = options[0];
  2234. i18n.__composerExtend =
  2235. opts.__composerExtend;
  2236. i18n.__vueI18nExtend =
  2237. opts.__vueI18nExtend;
  2238. }
  2239. // global method and properties injection for Composition API
  2240. let globalReleaseHandler = null;
  2241. if (!__legacyMode && __globalInjection) {
  2242. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  2243. }
  2244. // install built-in components and directive
  2245. if (__VUE_I18N_FULL_INSTALL__) {
  2246. apply(app, i18n, ...options);
  2247. }
  2248. // setup mixin for Legacy API
  2249. if (__VUE_I18N_LEGACY_API__ && __legacyMode) {
  2250. app.mixin(defineMixin(__global, __global.__composer, i18n));
  2251. }
  2252. // release global scope
  2253. const unmountApp = app.unmount;
  2254. app.unmount = () => {
  2255. globalReleaseHandler && globalReleaseHandler();
  2256. i18n.dispose();
  2257. unmountApp();
  2258. };
  2259. // setup vue-devtools plugin
  2260. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && !false) {
  2261. const ret = await enableDevTools(app, i18n);
  2262. if (!ret) {
  2263. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  2264. }
  2265. const emitter = createEmitter();
  2266. if (__legacyMode) {
  2267. const _vueI18n = __global;
  2268. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  2269. }
  2270. else {
  2271. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2272. const _composer = __global;
  2273. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  2274. }
  2275. emitter.on('*', addTimelineEvent);
  2276. }
  2277. },
  2278. // global accessor
  2279. get global() {
  2280. return __global;
  2281. },
  2282. dispose() {
  2283. globalScope.stop();
  2284. },
  2285. // @internal
  2286. __instances,
  2287. // @internal
  2288. __getInstance,
  2289. // @internal
  2290. __setInstance,
  2291. // @internal
  2292. __deleteInstance
  2293. };
  2294. return i18n;
  2295. }
  2296. }
  2297. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  2298. function useI18n(options = {}) {
  2299. const instance = getCurrentInstance();
  2300. if (instance == null) {
  2301. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  2302. }
  2303. if (!instance.isCE &&
  2304. instance.appContext.app != null &&
  2305. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  2306. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  2307. }
  2308. const i18n = getI18nInstance(instance);
  2309. const gl = getGlobalComposer(i18n);
  2310. const componentOptions = getComponentOptions(instance);
  2311. const scope = getScope(options, componentOptions);
  2312. if (__VUE_I18N_LEGACY_API__) {
  2313. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2314. if (i18n.mode === 'legacy' && !options.__useComponent) {
  2315. if (!i18n.allowComposition) {
  2316. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
  2317. }
  2318. return useI18nForLegacy(instance, scope, gl, options);
  2319. }
  2320. }
  2321. if (scope === 'global') {
  2322. adjustI18nResources(gl, options, componentOptions);
  2323. return gl;
  2324. }
  2325. if (scope === 'parent') {
  2326. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2327. let composer = getComposer(i18n, instance, options.__useComponent);
  2328. if (composer == null) {
  2329. if ((process.env.NODE_ENV !== 'production')) {
  2330. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  2331. }
  2332. composer = gl;
  2333. }
  2334. return composer;
  2335. }
  2336. const i18nInternal = i18n;
  2337. let composer = i18nInternal.__getInstance(instance);
  2338. if (composer == null) {
  2339. const composerOptions = assign({}, options);
  2340. if ('__i18n' in componentOptions) {
  2341. composerOptions.__i18n = componentOptions.__i18n;
  2342. }
  2343. if (gl) {
  2344. composerOptions.__root = gl;
  2345. }
  2346. composer = createComposer(composerOptions);
  2347. if (i18nInternal.__composerExtend) {
  2348. composer[DisposeSymbol] =
  2349. i18nInternal.__composerExtend(composer);
  2350. }
  2351. setupLifeCycle(i18nInternal, instance, composer);
  2352. i18nInternal.__setInstance(instance, composer);
  2353. }
  2354. return composer;
  2355. }
  2356. /**
  2357. * Cast to VueI18n legacy compatible type
  2358. *
  2359. * @remarks
  2360. * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
  2361. *
  2362. * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.
  2363. *
  2364. * @param i18n - An instance of {@link I18n}
  2365. * @returns A i18n instance which is casted to {@link VueI18n} type
  2366. *
  2367. * @VueI18nTip
  2368. * :new: provided by **vue-i18n-bridge only**
  2369. *
  2370. * @VueI18nGeneral
  2371. */
  2372. /* #__NO_SIDE_EFFECTS__ */
  2373. const castToVueI18n = (i18n
  2374. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2375. ) => {
  2376. if (!(__VUE_I18N_BRIDGE__ in i18n)) {
  2377. throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
  2378. }
  2379. return i18n;
  2380. };
  2381. function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
  2382. ) {
  2383. const scope = effectScope();
  2384. {
  2385. const obj = __VUE_I18N_LEGACY_API__ && legacyMode
  2386. ? scope.run(() => createVueI18n(options))
  2387. : scope.run(() => createComposer(options));
  2388. if (obj == null) {
  2389. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  2390. }
  2391. return [scope, obj];
  2392. }
  2393. }
  2394. function getI18nInstance(instance) {
  2395. {
  2396. const i18n = inject(!instance.isCE
  2397. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  2398. : I18nInjectionKey);
  2399. /* istanbul ignore if */
  2400. if (!i18n) {
  2401. throw createI18nError(!instance.isCE
  2402. ? I18nErrorCodes.UNEXPECTED_ERROR
  2403. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  2404. }
  2405. return i18n;
  2406. }
  2407. }
  2408. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2409. function getScope(options, componentOptions) {
  2410. // prettier-ignore
  2411. return isEmptyObject(options)
  2412. ? ('__i18n' in componentOptions)
  2413. ? 'local'
  2414. : 'global'
  2415. : !options.useScope
  2416. ? 'local'
  2417. : options.useScope;
  2418. }
  2419. function getGlobalComposer(i18n) {
  2420. // prettier-ignore
  2421. return i18n.mode === 'composition'
  2422. ? i18n.global
  2423. : i18n.global.__composer
  2424. ;
  2425. }
  2426. function getComposer(i18n, target, useComponent = false) {
  2427. let composer = null;
  2428. const root = target.root;
  2429. let current = getParentComponentInstance(target, useComponent);
  2430. while (current != null) {
  2431. const i18nInternal = i18n;
  2432. if (i18n.mode === 'composition') {
  2433. composer = i18nInternal.__getInstance(current);
  2434. }
  2435. else {
  2436. if (__VUE_I18N_LEGACY_API__) {
  2437. const vueI18n = i18nInternal.__getInstance(current);
  2438. if (vueI18n != null) {
  2439. composer = vueI18n
  2440. .__composer;
  2441. if (useComponent &&
  2442. composer &&
  2443. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  2444. ) {
  2445. composer = null;
  2446. }
  2447. }
  2448. }
  2449. }
  2450. if (composer != null) {
  2451. break;
  2452. }
  2453. if (root === current) {
  2454. break;
  2455. }
  2456. current = current.parent;
  2457. }
  2458. return composer;
  2459. }
  2460. function getParentComponentInstance(target, useComponent = false) {
  2461. if (target == null) {
  2462. return null;
  2463. }
  2464. {
  2465. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  2466. return !useComponent
  2467. ? target.parent
  2468. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  2469. }
  2470. }
  2471. function setupLifeCycle(i18n, target, composer) {
  2472. let emitter = null;
  2473. {
  2474. onMounted(() => {
  2475. // inject composer instance to DOM for intlify-devtools
  2476. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
  2477. !false &&
  2478. target.vnode.el) {
  2479. target.vnode.el.__VUE_I18N__ = composer;
  2480. emitter = createEmitter();
  2481. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2482. const _composer = composer;
  2483. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  2484. emitter.on('*', addTimelineEvent);
  2485. }
  2486. }, target);
  2487. onUnmounted(() => {
  2488. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2489. const _composer = composer;
  2490. // remove composer instance from DOM for intlify-devtools
  2491. if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&
  2492. !false &&
  2493. target.vnode.el &&
  2494. target.vnode.el.__VUE_I18N__) {
  2495. emitter && emitter.off('*', addTimelineEvent);
  2496. _composer[DisableEmitter] && _composer[DisableEmitter]();
  2497. delete target.vnode.el.__VUE_I18N__;
  2498. }
  2499. i18n.__deleteInstance(target);
  2500. // dispose extended resources
  2501. const dispose = _composer[DisposeSymbol];
  2502. if (dispose) {
  2503. dispose();
  2504. delete _composer[DisposeSymbol];
  2505. }
  2506. }, target);
  2507. }
  2508. }
  2509. function useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any
  2510. ) {
  2511. const isLocalScope = scope === 'local';
  2512. const _composer = shallowRef(null);
  2513. if (isLocalScope &&
  2514. instance.proxy &&
  2515. !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {
  2516. throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);
  2517. }
  2518. const _inheritLocale = isBoolean(options.inheritLocale)
  2519. ? options.inheritLocale
  2520. : !isString(options.locale);
  2521. const _locale = ref(
  2522. // prettier-ignore
  2523. !isLocalScope || _inheritLocale
  2524. ? root.locale.value
  2525. : isString(options.locale)
  2526. ? options.locale
  2527. : DEFAULT_LOCALE);
  2528. const _fallbackLocale = ref(
  2529. // prettier-ignore
  2530. !isLocalScope || _inheritLocale
  2531. ? root.fallbackLocale.value
  2532. : isString(options.fallbackLocale) ||
  2533. isArray(options.fallbackLocale) ||
  2534. isPlainObject(options.fallbackLocale) ||
  2535. options.fallbackLocale === false
  2536. ? options.fallbackLocale
  2537. : _locale.value);
  2538. const _messages = ref(getLocaleMessages(_locale.value, options));
  2539. // prettier-ignore
  2540. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  2541. ? options.datetimeFormats
  2542. : { [_locale.value]: {} });
  2543. // prettier-ignore
  2544. const _numberFormats = ref(isPlainObject(options.numberFormats)
  2545. ? options.numberFormats
  2546. : { [_locale.value]: {} });
  2547. // prettier-ignore
  2548. const _missingWarn = isLocalScope
  2549. ? root.missingWarn
  2550. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2551. ? options.missingWarn
  2552. : true;
  2553. // prettier-ignore
  2554. const _fallbackWarn = isLocalScope
  2555. ? root.fallbackWarn
  2556. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2557. ? options.fallbackWarn
  2558. : true;
  2559. // prettier-ignore
  2560. const _fallbackRoot = isLocalScope
  2561. ? root.fallbackRoot
  2562. : isBoolean(options.fallbackRoot)
  2563. ? options.fallbackRoot
  2564. : true;
  2565. // configure fall back to root
  2566. const _fallbackFormat = !!options.fallbackFormat;
  2567. // runtime missing
  2568. const _missing = isFunction(options.missing) ? options.missing : null;
  2569. // postTranslation handler
  2570. const _postTranslation = isFunction(options.postTranslation)
  2571. ? options.postTranslation
  2572. : null;
  2573. // prettier-ignore
  2574. const _warnHtmlMessage = isLocalScope
  2575. ? root.warnHtmlMessage
  2576. : isBoolean(options.warnHtmlMessage)
  2577. ? options.warnHtmlMessage
  2578. : true;
  2579. const _escapeParameter = !!options.escapeParameter;
  2580. // prettier-ignore
  2581. const _modifiers = isLocalScope
  2582. ? root.modifiers
  2583. : isPlainObject(options.modifiers)
  2584. ? options.modifiers
  2585. : {};
  2586. // pluralRules
  2587. const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);
  2588. // track reactivity
  2589. function trackReactivityValues() {
  2590. return [
  2591. _locale.value,
  2592. _fallbackLocale.value,
  2593. _messages.value,
  2594. _datetimeFormats.value,
  2595. _numberFormats.value
  2596. ];
  2597. }
  2598. // locale
  2599. const locale = computed({
  2600. get: () => {
  2601. return _composer.value ? _composer.value.locale.value : _locale.value;
  2602. },
  2603. set: val => {
  2604. if (_composer.value) {
  2605. _composer.value.locale.value = val;
  2606. }
  2607. _locale.value = val;
  2608. }
  2609. });
  2610. // fallbackLocale
  2611. const fallbackLocale = computed({
  2612. get: () => {
  2613. return _composer.value
  2614. ? _composer.value.fallbackLocale.value
  2615. : _fallbackLocale.value;
  2616. },
  2617. set: val => {
  2618. if (_composer.value) {
  2619. _composer.value.fallbackLocale.value = val;
  2620. }
  2621. _fallbackLocale.value = val;
  2622. }
  2623. });
  2624. // messages
  2625. const messages = computed(() => {
  2626. if (_composer.value) {
  2627. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2628. return _composer.value.messages.value;
  2629. }
  2630. else {
  2631. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2632. return _messages.value;
  2633. }
  2634. });
  2635. const datetimeFormats = computed(() => _datetimeFormats.value);
  2636. const numberFormats = computed(() => _numberFormats.value);
  2637. function getPostTranslationHandler() {
  2638. return _composer.value
  2639. ? _composer.value.getPostTranslationHandler()
  2640. : _postTranslation;
  2641. }
  2642. function setPostTranslationHandler(handler) {
  2643. if (_composer.value) {
  2644. _composer.value.setPostTranslationHandler(handler);
  2645. }
  2646. }
  2647. function getMissingHandler() {
  2648. return _composer.value ? _composer.value.getMissingHandler() : _missing;
  2649. }
  2650. function setMissingHandler(handler) {
  2651. if (_composer.value) {
  2652. _composer.value.setMissingHandler(handler);
  2653. }
  2654. }
  2655. function warpWithDeps(fn) {
  2656. trackReactivityValues();
  2657. return fn();
  2658. }
  2659. function t(...args) {
  2660. return _composer.value
  2661. ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))
  2662. : warpWithDeps(() => '');
  2663. }
  2664. function rt(...args) {
  2665. return _composer.value
  2666. ? Reflect.apply(_composer.value.rt, null, [...args])
  2667. : '';
  2668. }
  2669. function d(...args) {
  2670. return _composer.value
  2671. ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))
  2672. : warpWithDeps(() => '');
  2673. }
  2674. function n(...args) {
  2675. return _composer.value
  2676. ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))
  2677. : warpWithDeps(() => '');
  2678. }
  2679. function tm(key) {
  2680. return _composer.value ? _composer.value.tm(key) : {};
  2681. }
  2682. function te(key, locale) {
  2683. return _composer.value ? _composer.value.te(key, locale) : false;
  2684. }
  2685. function getLocaleMessage(locale) {
  2686. return _composer.value ? _composer.value.getLocaleMessage(locale) : {};
  2687. }
  2688. function setLocaleMessage(locale, message) {
  2689. if (_composer.value) {
  2690. _composer.value.setLocaleMessage(locale, message);
  2691. _messages.value[locale] = message;
  2692. }
  2693. }
  2694. function mergeLocaleMessage(locale, message) {
  2695. if (_composer.value) {
  2696. _composer.value.mergeLocaleMessage(locale, message);
  2697. }
  2698. }
  2699. function getDateTimeFormat(locale) {
  2700. return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};
  2701. }
  2702. function setDateTimeFormat(locale, format) {
  2703. if (_composer.value) {
  2704. _composer.value.setDateTimeFormat(locale, format);
  2705. _datetimeFormats.value[locale] = format;
  2706. }
  2707. }
  2708. function mergeDateTimeFormat(locale, format) {
  2709. if (_composer.value) {
  2710. _composer.value.mergeDateTimeFormat(locale, format);
  2711. }
  2712. }
  2713. function getNumberFormat(locale) {
  2714. return _composer.value ? _composer.value.getNumberFormat(locale) : {};
  2715. }
  2716. function setNumberFormat(locale, format) {
  2717. if (_composer.value) {
  2718. _composer.value.setNumberFormat(locale, format);
  2719. _numberFormats.value[locale] = format;
  2720. }
  2721. }
  2722. function mergeNumberFormat(locale, format) {
  2723. if (_composer.value) {
  2724. _composer.value.mergeNumberFormat(locale, format);
  2725. }
  2726. }
  2727. const wrapper = {
  2728. get id() {
  2729. return _composer.value ? _composer.value.id : -1;
  2730. },
  2731. locale,
  2732. fallbackLocale,
  2733. messages,
  2734. datetimeFormats,
  2735. numberFormats,
  2736. get inheritLocale() {
  2737. return _composer.value ? _composer.value.inheritLocale : _inheritLocale;
  2738. },
  2739. set inheritLocale(val) {
  2740. if (_composer.value) {
  2741. _composer.value.inheritLocale = val;
  2742. }
  2743. },
  2744. get availableLocales() {
  2745. return _composer.value
  2746. ? _composer.value.availableLocales
  2747. : Object.keys(_messages.value);
  2748. },
  2749. get modifiers() {
  2750. return (_composer.value ? _composer.value.modifiers : _modifiers);
  2751. },
  2752. get pluralRules() {
  2753. return (_composer.value ? _composer.value.pluralRules : _pluralRules);
  2754. },
  2755. get isGlobal() {
  2756. return _composer.value ? _composer.value.isGlobal : false;
  2757. },
  2758. get missingWarn() {
  2759. return _composer.value ? _composer.value.missingWarn : _missingWarn;
  2760. },
  2761. set missingWarn(val) {
  2762. if (_composer.value) {
  2763. _composer.value.missingWarn = val;
  2764. }
  2765. },
  2766. get fallbackWarn() {
  2767. return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;
  2768. },
  2769. set fallbackWarn(val) {
  2770. if (_composer.value) {
  2771. _composer.value.missingWarn = val;
  2772. }
  2773. },
  2774. get fallbackRoot() {
  2775. return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;
  2776. },
  2777. set fallbackRoot(val) {
  2778. if (_composer.value) {
  2779. _composer.value.fallbackRoot = val;
  2780. }
  2781. },
  2782. get fallbackFormat() {
  2783. return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;
  2784. },
  2785. set fallbackFormat(val) {
  2786. if (_composer.value) {
  2787. _composer.value.fallbackFormat = val;
  2788. }
  2789. },
  2790. get warnHtmlMessage() {
  2791. return _composer.value
  2792. ? _composer.value.warnHtmlMessage
  2793. : _warnHtmlMessage;
  2794. },
  2795. set warnHtmlMessage(val) {
  2796. if (_composer.value) {
  2797. _composer.value.warnHtmlMessage = val;
  2798. }
  2799. },
  2800. get escapeParameter() {
  2801. return _composer.value
  2802. ? _composer.value.escapeParameter
  2803. : _escapeParameter;
  2804. },
  2805. set escapeParameter(val) {
  2806. if (_composer.value) {
  2807. _composer.value.escapeParameter = val;
  2808. }
  2809. },
  2810. t,
  2811. getPostTranslationHandler,
  2812. setPostTranslationHandler,
  2813. getMissingHandler,
  2814. setMissingHandler,
  2815. rt,
  2816. d,
  2817. n,
  2818. tm,
  2819. te,
  2820. getLocaleMessage,
  2821. setLocaleMessage,
  2822. mergeLocaleMessage,
  2823. getDateTimeFormat,
  2824. setDateTimeFormat,
  2825. mergeDateTimeFormat,
  2826. getNumberFormat,
  2827. setNumberFormat,
  2828. mergeNumberFormat
  2829. };
  2830. function sync(composer) {
  2831. composer.locale.value = _locale.value;
  2832. composer.fallbackLocale.value = _fallbackLocale.value;
  2833. Object.keys(_messages.value).forEach(locale => {
  2834. composer.mergeLocaleMessage(locale, _messages.value[locale]);
  2835. });
  2836. Object.keys(_datetimeFormats.value).forEach(locale => {
  2837. composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);
  2838. });
  2839. Object.keys(_numberFormats.value).forEach(locale => {
  2840. composer.mergeNumberFormat(locale, _numberFormats.value[locale]);
  2841. });
  2842. composer.escapeParameter = _escapeParameter;
  2843. composer.fallbackFormat = _fallbackFormat;
  2844. composer.fallbackRoot = _fallbackRoot;
  2845. composer.fallbackWarn = _fallbackWarn;
  2846. composer.missingWarn = _missingWarn;
  2847. composer.warnHtmlMessage = _warnHtmlMessage;
  2848. }
  2849. onBeforeMount(() => {
  2850. if (instance.proxy == null || instance.proxy.$i18n == null) {
  2851. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);
  2852. }
  2853. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2854. const composer = (_composer.value = instance.proxy.$i18n
  2855. .__composer);
  2856. if (scope === 'global') {
  2857. _locale.value = composer.locale.value;
  2858. _fallbackLocale.value = composer.fallbackLocale.value;
  2859. _messages.value = composer.messages.value;
  2860. _datetimeFormats.value = composer.datetimeFormats.value;
  2861. _numberFormats.value = composer.numberFormats.value;
  2862. }
  2863. else if (isLocalScope) {
  2864. sync(composer);
  2865. }
  2866. });
  2867. return wrapper;
  2868. }
  2869. const globalExportProps = [
  2870. 'locale',
  2871. 'fallbackLocale',
  2872. 'availableLocales'
  2873. ];
  2874. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  2875. ;
  2876. function injectGlobalFields(app, composer) {
  2877. const i18n = Object.create(null);
  2878. globalExportProps.forEach(prop => {
  2879. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  2880. if (!desc) {
  2881. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  2882. }
  2883. const wrap = isRef(desc.value) // check computed props
  2884. ? {
  2885. get() {
  2886. return desc.value.value;
  2887. },
  2888. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2889. set(val) {
  2890. desc.value.value = val;
  2891. }
  2892. }
  2893. : {
  2894. get() {
  2895. return desc.get && desc.get();
  2896. }
  2897. };
  2898. Object.defineProperty(i18n, prop, wrap);
  2899. });
  2900. app.config.globalProperties.$i18n = i18n;
  2901. globalExportMethods.forEach(method => {
  2902. const desc = Object.getOwnPropertyDescriptor(composer, method);
  2903. if (!desc || !desc.value) {
  2904. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  2905. }
  2906. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  2907. });
  2908. const dispose = () => {
  2909. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2910. delete app.config.globalProperties.$i18n;
  2911. globalExportMethods.forEach(method => {
  2912. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2913. delete app.config.globalProperties[`$${method}`];
  2914. });
  2915. };
  2916. return dispose;
  2917. }
  2918. {
  2919. initFeatureFlags();
  2920. }
  2921. // register message compiler at vue-i18n
  2922. if (__INTLIFY_JIT_COMPILATION__) {
  2923. registerMessageCompiler(compile);
  2924. }
  2925. else {
  2926. registerMessageCompiler(compileToFunction);
  2927. }
  2928. // register message resolver at vue-i18n
  2929. registerMessageResolver(resolveValue);
  2930. // register fallback locale at vue-i18n
  2931. registerLocaleFallbacker(fallbackWithLocaleChain);
  2932. // NOTE: experimental !!
  2933. if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {
  2934. const target = getGlobalThis();
  2935. target.__INTLIFY__ = true;
  2936. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  2937. }
  2938. if ((process.env.NODE_ENV !== 'production')) ;
  2939. export { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, castToVueI18n, createI18n, useI18n, vTDirective };