e9e67708c29d02a6c363de3f5fde98df5fa71d43cde58a15c6312d1d626397e18e3533539296c11f30cde299788d764e2b770f00e01a4ac9a7f17f5f267212 107 KB

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