vue-i18n.esm-bundler.js 99 KB

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