vue-i18n.runtime.global.js 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750
  1. /*!
  2. * vue-i18n v9.1.9
  3. * (c) 2021 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. var VueI18n = (function (exports, vue) {
  7. 'use strict';
  8. /**
  9. * Original Utilities
  10. * written by kazuya kawaguchi
  11. */
  12. const inBrowser = typeof window !== 'undefined';
  13. let mark;
  14. let measure;
  15. {
  16. const perf = inBrowser && window.performance;
  17. if (perf &&
  18. perf.mark &&
  19. perf.measure &&
  20. perf.clearMarks &&
  21. perf.clearMeasures) {
  22. mark = (tag) => perf.mark(tag);
  23. measure = (name, startTag, endTag) => {
  24. perf.measure(name, startTag, endTag);
  25. perf.clearMarks(startTag);
  26. perf.clearMarks(endTag);
  27. };
  28. }
  29. }
  30. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  31. /* eslint-disable */
  32. function format(message, ...args) {
  33. if (args.length === 1 && isObject(args[0])) {
  34. args = args[0];
  35. }
  36. if (!args || !args.hasOwnProperty) {
  37. args = {};
  38. }
  39. return message.replace(RE_ARGS, (match, identifier) => {
  40. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  41. });
  42. }
  43. const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  44. const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
  45. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  46. const friendlyJSONstringify = (json) => JSON.stringify(json)
  47. .replace(/\u2028/g, '\\u2028')
  48. .replace(/\u2029/g, '\\u2029')
  49. .replace(/\u0027/g, '\\u0027');
  50. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  51. const isDate = (val) => toTypeString(val) === '[object Date]';
  52. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  53. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  54. function warn(msg, err) {
  55. if (typeof console !== 'undefined') {
  56. console.warn(`[intlify] ` + msg);
  57. /* istanbul ignore if */
  58. if (err) {
  59. console.warn(err.stack);
  60. }
  61. }
  62. }
  63. const assign = Object.assign;
  64. let _globalThis;
  65. const getGlobalThis = () => {
  66. // prettier-ignore
  67. return (_globalThis ||
  68. (_globalThis =
  69. typeof globalThis !== 'undefined'
  70. ? globalThis
  71. : typeof self !== 'undefined'
  72. ? self
  73. : typeof window !== 'undefined'
  74. ? window
  75. : typeof global !== 'undefined'
  76. ? global
  77. : {}));
  78. };
  79. function escapeHtml(rawText) {
  80. return rawText
  81. .replace(/</g, '&lt;')
  82. .replace(/>/g, '&gt;')
  83. .replace(/"/g, '&quot;')
  84. .replace(/'/g, '&apos;');
  85. }
  86. const hasOwnProperty = Object.prototype.hasOwnProperty;
  87. function hasOwn(obj, key) {
  88. return hasOwnProperty.call(obj, key);
  89. }
  90. /* eslint-enable */
  91. /**
  92. * Useful Utilities By Evan you
  93. * Modified by kazuya kawaguchi
  94. * MIT License
  95. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  96. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  97. */
  98. const isArray = Array.isArray;
  99. const isFunction = (val) => typeof val === 'function';
  100. const isString = (val) => typeof val === 'string';
  101. const isBoolean = (val) => typeof val === 'boolean';
  102. const isObject = (val) => // eslint-disable-line
  103. val !== null && typeof val === 'object';
  104. const objectToString = Object.prototype.toString;
  105. const toTypeString = (value) => objectToString.call(value);
  106. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  107. // for converting list and named values to displayed strings.
  108. const toDisplayString = (val) => {
  109. return val == null
  110. ? ''
  111. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  112. ? JSON.stringify(val, null, 2)
  113. : String(val);
  114. };
  115. const RANGE = 2;
  116. function generateCodeFrame(source, start = 0, end = source.length) {
  117. const lines = source.split(/\r?\n/);
  118. let count = 0;
  119. const res = [];
  120. for (let i = 0; i < lines.length; i++) {
  121. count += lines[i].length + 1;
  122. if (count >= start) {
  123. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  124. if (j < 0 || j >= lines.length)
  125. continue;
  126. const line = j + 1;
  127. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  128. const lineLength = lines[j].length;
  129. if (j === i) {
  130. // push underline
  131. const pad = start - (count - lineLength) + 1;
  132. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  133. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  134. }
  135. else if (j > i) {
  136. if (end > count) {
  137. const length = Math.max(Math.min(end - count, lineLength), 1);
  138. res.push(` | ` + '^'.repeat(length));
  139. }
  140. count += lineLength + 1;
  141. }
  142. }
  143. break;
  144. }
  145. }
  146. return res.join('\n');
  147. }
  148. /**
  149. * Event emitter, forked from the below:
  150. * - original repository url: https://github.com/developit/mitt
  151. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  152. * - author: Jason Miller (https://github.com/developit)
  153. * - license: MIT
  154. */
  155. /**
  156. * Create a event emitter
  157. *
  158. * @returns An event emitter
  159. */
  160. function createEmitter() {
  161. const events = new Map();
  162. const emitter = {
  163. events,
  164. on(event, handler) {
  165. const handlers = events.get(event);
  166. const added = handlers && handlers.push(handler);
  167. if (!added) {
  168. events.set(event, [handler]);
  169. }
  170. },
  171. off(event, handler) {
  172. const handlers = events.get(event);
  173. if (handlers) {
  174. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  175. }
  176. },
  177. emit(event, payload) {
  178. (events.get(event) || [])
  179. .slice()
  180. .map(handler => handler(payload));
  181. (events.get('*') || [])
  182. .slice()
  183. .map(handler => handler(event, payload));
  184. }
  185. };
  186. return emitter;
  187. }
  188. const pathStateMachine = [];
  189. pathStateMachine[0 /* BEFORE_PATH */] = {
  190. ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
  191. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  192. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  193. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  194. };
  195. pathStateMachine[1 /* IN_PATH */] = {
  196. ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
  197. ["." /* DOT */]: [2 /* BEFORE_IDENT */],
  198. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  199. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  200. };
  201. pathStateMachine[2 /* BEFORE_IDENT */] = {
  202. ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
  203. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  204. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
  205. };
  206. pathStateMachine[3 /* IN_IDENT */] = {
  207. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  208. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  209. ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
  210. ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
  211. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
  212. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
  213. };
  214. pathStateMachine[4 /* IN_SUB_PATH */] = {
  215. ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
  216. ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
  217. ["[" /* LEFT_BRACKET */]: [
  218. 4 /* IN_SUB_PATH */,
  219. 2 /* INC_SUB_PATH_DEPTH */
  220. ],
  221. ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
  222. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  223. ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
  224. };
  225. pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
  226. ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  227. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  228. ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
  229. };
  230. pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
  231. ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  232. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  233. ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
  234. };
  235. /**
  236. * Check if an expression is a literal value.
  237. */
  238. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  239. function isLiteral(exp) {
  240. return literalValueRE.test(exp);
  241. }
  242. /**
  243. * Strip quotes from a string
  244. */
  245. function stripQuotes(str) {
  246. const a = str.charCodeAt(0);
  247. const b = str.charCodeAt(str.length - 1);
  248. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  249. }
  250. /**
  251. * Determine the type of a character in a keypath.
  252. */
  253. function getPathCharType(ch) {
  254. if (ch === undefined || ch === null) {
  255. return "o" /* END_OF_FAIL */;
  256. }
  257. const code = ch.charCodeAt(0);
  258. switch (code) {
  259. case 0x5b: // [
  260. case 0x5d: // ]
  261. case 0x2e: // .
  262. case 0x22: // "
  263. case 0x27: // '
  264. return ch;
  265. case 0x5f: // _
  266. case 0x24: // $
  267. case 0x2d: // -
  268. return "i" /* IDENT */;
  269. case 0x09: // Tab (HT)
  270. case 0x0a: // Newline (LF)
  271. case 0x0d: // Return (CR)
  272. case 0xa0: // No-break space (NBSP)
  273. case 0xfeff: // Byte Order Mark (BOM)
  274. case 0x2028: // Line Separator (LS)
  275. case 0x2029: // Paragraph Separator (PS)
  276. return "w" /* WORKSPACE */;
  277. }
  278. return "i" /* IDENT */;
  279. }
  280. /**
  281. * Format a subPath, return its plain form if it is
  282. * a literal string or number. Otherwise prepend the
  283. * dynamic indicator (*).
  284. */
  285. function formatSubPath(path) {
  286. const trimmed = path.trim();
  287. // invalid leading 0
  288. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  289. return false;
  290. }
  291. return isLiteral(trimmed)
  292. ? stripQuotes(trimmed)
  293. : "*" /* ASTARISK */ + trimmed;
  294. }
  295. /**
  296. * Parse a string path into an array of segments
  297. */
  298. function parse(path) {
  299. const keys = [];
  300. let index = -1;
  301. let mode = 0 /* BEFORE_PATH */;
  302. let subPathDepth = 0;
  303. let c;
  304. let key; // eslint-disable-line
  305. let newChar;
  306. let type;
  307. let transition;
  308. let action;
  309. let typeMap;
  310. const actions = [];
  311. actions[0 /* APPEND */] = () => {
  312. if (key === undefined) {
  313. key = newChar;
  314. }
  315. else {
  316. key += newChar;
  317. }
  318. };
  319. actions[1 /* PUSH */] = () => {
  320. if (key !== undefined) {
  321. keys.push(key);
  322. key = undefined;
  323. }
  324. };
  325. actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
  326. actions[0 /* APPEND */]();
  327. subPathDepth++;
  328. };
  329. actions[3 /* PUSH_SUB_PATH */] = () => {
  330. if (subPathDepth > 0) {
  331. subPathDepth--;
  332. mode = 4 /* IN_SUB_PATH */;
  333. actions[0 /* APPEND */]();
  334. }
  335. else {
  336. subPathDepth = 0;
  337. if (key === undefined) {
  338. return false;
  339. }
  340. key = formatSubPath(key);
  341. if (key === false) {
  342. return false;
  343. }
  344. else {
  345. actions[1 /* PUSH */]();
  346. }
  347. }
  348. };
  349. function maybeUnescapeQuote() {
  350. const nextChar = path[index + 1];
  351. if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
  352. nextChar === "'" /* SINGLE_QUOTE */) ||
  353. (mode === 6 /* IN_DOUBLE_QUOTE */ &&
  354. nextChar === "\"" /* DOUBLE_QUOTE */)) {
  355. index++;
  356. newChar = '\\' + nextChar;
  357. actions[0 /* APPEND */]();
  358. return true;
  359. }
  360. }
  361. while (mode !== null) {
  362. index++;
  363. c = path[index];
  364. if (c === '\\' && maybeUnescapeQuote()) {
  365. continue;
  366. }
  367. type = getPathCharType(c);
  368. typeMap = pathStateMachine[mode];
  369. transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
  370. // check parse error
  371. if (transition === 8 /* ERROR */) {
  372. return;
  373. }
  374. mode = transition[0];
  375. if (transition[1] !== undefined) {
  376. action = actions[transition[1]];
  377. if (action) {
  378. newChar = c;
  379. if (action() === false) {
  380. return;
  381. }
  382. }
  383. }
  384. // check parse finish
  385. if (mode === 7 /* AFTER_PATH */) {
  386. return keys;
  387. }
  388. }
  389. }
  390. // path token cache
  391. const cache = new Map();
  392. function resolveValue(obj, path) {
  393. // check object
  394. if (!isObject(obj)) {
  395. return null;
  396. }
  397. // parse path
  398. let hit = cache.get(path);
  399. if (!hit) {
  400. hit = parse(path);
  401. if (hit) {
  402. cache.set(path, hit);
  403. }
  404. }
  405. // check hit
  406. if (!hit) {
  407. return null;
  408. }
  409. // resolve path value
  410. const len = hit.length;
  411. let last = obj;
  412. let i = 0;
  413. while (i < len) {
  414. const val = last[hit[i]];
  415. if (val === undefined) {
  416. return null;
  417. }
  418. last = val;
  419. i++;
  420. }
  421. return last;
  422. }
  423. /**
  424. * Transform flat json in obj to normal json in obj
  425. */
  426. function handleFlatJson(obj) {
  427. // check obj
  428. if (!isObject(obj)) {
  429. return obj;
  430. }
  431. for (const key in obj) {
  432. // check key
  433. if (!hasOwn(obj, key)) {
  434. continue;
  435. }
  436. // handle for normal json
  437. if (!key.includes("." /* DOT */)) {
  438. // recursive process value if value is also a object
  439. if (isObject(obj[key])) {
  440. handleFlatJson(obj[key]);
  441. }
  442. }
  443. // handle for flat json, transform to normal json
  444. else {
  445. // go to the last object
  446. const subKeys = key.split("." /* DOT */);
  447. const lastIndex = subKeys.length - 1;
  448. let currentObj = obj;
  449. for (let i = 0; i < lastIndex; i++) {
  450. if (!(subKeys[i] in currentObj)) {
  451. currentObj[subKeys[i]] = {};
  452. }
  453. currentObj = currentObj[subKeys[i]];
  454. }
  455. // update last object value, delete old property
  456. currentObj[subKeys[lastIndex]] = obj[key];
  457. delete obj[key];
  458. // recursive process value if value is also a object
  459. if (isObject(currentObj[subKeys[lastIndex]])) {
  460. handleFlatJson(currentObj[subKeys[lastIndex]]);
  461. }
  462. }
  463. }
  464. return obj;
  465. }
  466. const DEFAULT_MODIFIER = (str) => str;
  467. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  468. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  469. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
  470. const DEFAULT_INTERPOLATE = toDisplayString;
  471. function pluralDefault(choice, choicesLength) {
  472. choice = Math.abs(choice);
  473. if (choicesLength === 2) {
  474. // prettier-ignore
  475. return choice
  476. ? choice > 1
  477. ? 1
  478. : 0
  479. : 1;
  480. }
  481. return choice ? Math.min(choice, 2) : 0;
  482. }
  483. function getPluralIndex(options) {
  484. // prettier-ignore
  485. const index = isNumber(options.pluralIndex)
  486. ? options.pluralIndex
  487. : -1;
  488. // prettier-ignore
  489. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  490. ? isNumber(options.named.count)
  491. ? options.named.count
  492. : isNumber(options.named.n)
  493. ? options.named.n
  494. : index
  495. : index;
  496. }
  497. function normalizeNamed(pluralIndex, props) {
  498. if (!props.count) {
  499. props.count = pluralIndex;
  500. }
  501. if (!props.n) {
  502. props.n = pluralIndex;
  503. }
  504. }
  505. function createMessageContext(options = {}) {
  506. const locale = options.locale;
  507. const pluralIndex = getPluralIndex(options);
  508. const pluralRule = isObject(options.pluralRules) &&
  509. isString(locale) &&
  510. isFunction(options.pluralRules[locale])
  511. ? options.pluralRules[locale]
  512. : pluralDefault;
  513. const orgPluralRule = isObject(options.pluralRules) &&
  514. isString(locale) &&
  515. isFunction(options.pluralRules[locale])
  516. ? pluralDefault
  517. : undefined;
  518. const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  519. const _list = options.list || [];
  520. const list = (index) => _list[index];
  521. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  522. const _named = options.named || {};
  523. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  524. const named = (key) => _named[key];
  525. // TODO: need to design resolve message function?
  526. function message(key) {
  527. // prettier-ignore
  528. const msg = isFunction(options.messages)
  529. ? options.messages(key)
  530. : isObject(options.messages)
  531. ? options.messages[key]
  532. : false;
  533. return !msg
  534. ? options.parent
  535. ? options.parent.message(key) // resolve from parent messages
  536. : DEFAULT_MESSAGE
  537. : msg;
  538. }
  539. const _modifier = (name) => options.modifiers
  540. ? options.modifiers[name]
  541. : DEFAULT_MODIFIER;
  542. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  543. ? options.processor.normalize
  544. : DEFAULT_NORMALIZE;
  545. const interpolate = isPlainObject(options.processor) &&
  546. isFunction(options.processor.interpolate)
  547. ? options.processor.interpolate
  548. : DEFAULT_INTERPOLATE;
  549. const type = isPlainObject(options.processor) && isString(options.processor.type)
  550. ? options.processor.type
  551. : DEFAULT_MESSAGE_DATA_TYPE;
  552. const ctx = {
  553. ["list" /* LIST */]: list,
  554. ["named" /* NAMED */]: named,
  555. ["plural" /* PLURAL */]: plural,
  556. ["linked" /* LINKED */]: (key, modifier) => {
  557. // TODO: should check `key`
  558. const msg = message(key)(ctx);
  559. return isString(modifier) ? _modifier(modifier)(msg) : msg;
  560. },
  561. ["message" /* MESSAGE */]: message,
  562. ["type" /* TYPE */]: type,
  563. ["interpolate" /* INTERPOLATE */]: interpolate,
  564. ["normalize" /* NORMALIZE */]: normalize
  565. };
  566. return ctx;
  567. }
  568. /** @internal */
  569. const errorMessages$2 = {
  570. // tokenizer error messages
  571. [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
  572. [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
  573. [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
  574. [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
  575. [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
  576. [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
  577. [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
  578. [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
  579. [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
  580. [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
  581. // parser error messages
  582. [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
  583. [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`,
  584. [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`,
  585. [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
  586. };
  587. function createCompileError(code, loc, options = {}) {
  588. const { domain, messages, args } = options;
  589. const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
  590. ;
  591. const error = new SyntaxError(String(msg));
  592. error.code = code;
  593. if (loc) {
  594. error.location = loc;
  595. }
  596. error.domain = domain;
  597. return error;
  598. }
  599. const IntlifyDevToolsHooks = {
  600. I18nInit: 'i18n:init',
  601. FunctionTranslate: 'function:translate'
  602. };
  603. let devtools = null;
  604. function setDevToolsHook(hook) {
  605. devtools = hook;
  606. }
  607. function initI18nDevTools(i18n, version, meta) {
  608. // TODO: queue if devtools is undefined
  609. devtools &&
  610. devtools.emit(IntlifyDevToolsHooks.I18nInit, {
  611. timestamp: Date.now(),
  612. i18n,
  613. version,
  614. meta
  615. });
  616. }
  617. const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
  618. function createDevToolsHook(hook) {
  619. return (payloads) => devtools && devtools.emit(hook, payloads);
  620. }
  621. /** @internal */
  622. const warnMessages$1 = {
  623. [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
  624. [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
  625. [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  626. [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
  627. [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  628. [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
  629. };
  630. function getWarnMessage$1(code, ...args) {
  631. return format(warnMessages$1[code], ...args);
  632. }
  633. /**
  634. * Intlify core-base version
  635. * @internal
  636. */
  637. const VERSION$1 = '9.1.9';
  638. const NOT_REOSLVED = -1;
  639. const MISSING_RESOLVE_VALUE = '';
  640. function getDefaultLinkedModifiers() {
  641. return {
  642. upper: (val) => (isString(val) ? val.toUpperCase() : val),
  643. lower: (val) => (isString(val) ? val.toLowerCase() : val),
  644. // prettier-ignore
  645. capitalize: (val) => (isString(val)
  646. ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
  647. : val)
  648. };
  649. }
  650. let _compiler;
  651. // Additional Meta for Intlify DevTools
  652. let _additionalMeta = null;
  653. const setAdditionalMeta = /* #__PURE__*/ (meta) => {
  654. _additionalMeta = meta;
  655. };
  656. const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
  657. // ID for CoreContext
  658. let _cid = 0;
  659. function createCoreContext(options = {}) {
  660. // setup options
  661. const version = isString(options.version) ? options.version : VERSION$1;
  662. const locale = isString(options.locale) ? options.locale : 'en-US';
  663. const fallbackLocale = isArray(options.fallbackLocale) ||
  664. isPlainObject(options.fallbackLocale) ||
  665. isString(options.fallbackLocale) ||
  666. options.fallbackLocale === false
  667. ? options.fallbackLocale
  668. : locale;
  669. const messages = isPlainObject(options.messages)
  670. ? options.messages
  671. : { [locale]: {} };
  672. const datetimeFormats = isPlainObject(options.datetimeFormats)
  673. ? options.datetimeFormats
  674. : { [locale]: {} };
  675. const numberFormats = isPlainObject(options.numberFormats)
  676. ? options.numberFormats
  677. : { [locale]: {} };
  678. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  679. const pluralRules = options.pluralRules || {};
  680. const missing = isFunction(options.missing) ? options.missing : null;
  681. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  682. ? options.missingWarn
  683. : true;
  684. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  685. ? options.fallbackWarn
  686. : true;
  687. const fallbackFormat = !!options.fallbackFormat;
  688. const unresolving = !!options.unresolving;
  689. const postTranslation = isFunction(options.postTranslation)
  690. ? options.postTranslation
  691. : null;
  692. const processor = isPlainObject(options.processor) ? options.processor : null;
  693. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  694. ? options.warnHtmlMessage
  695. : true;
  696. const escapeParameter = !!options.escapeParameter;
  697. const messageCompiler = isFunction(options.messageCompiler)
  698. ? options.messageCompiler
  699. : _compiler;
  700. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  701. // setup internal options
  702. const internalOptions = options;
  703. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  704. ? internalOptions.__datetimeFormatters
  705. : new Map();
  706. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  707. ? internalOptions.__numberFormatters
  708. : new Map();
  709. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  710. _cid++;
  711. const context = {
  712. version,
  713. cid: _cid,
  714. locale,
  715. fallbackLocale,
  716. messages,
  717. datetimeFormats,
  718. numberFormats,
  719. modifiers,
  720. pluralRules,
  721. missing,
  722. missingWarn,
  723. fallbackWarn,
  724. fallbackFormat,
  725. unresolving,
  726. postTranslation,
  727. processor,
  728. warnHtmlMessage,
  729. escapeParameter,
  730. messageCompiler,
  731. onWarn,
  732. __datetimeFormatters,
  733. __numberFormatters,
  734. __meta
  735. };
  736. // for vue-devtools timeline event
  737. {
  738. context.__v_emitter =
  739. internalOptions.__v_emitter != null
  740. ? internalOptions.__v_emitter
  741. : undefined;
  742. }
  743. // NOTE: experimental !!
  744. {
  745. initI18nDevTools(context, version, __meta);
  746. }
  747. return context;
  748. }
  749. /** @internal */
  750. function isTranslateFallbackWarn(fallback, key) {
  751. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  752. }
  753. /** @internal */
  754. function isTranslateMissingWarn(missing, key) {
  755. return missing instanceof RegExp ? missing.test(key) : missing;
  756. }
  757. /** @internal */
  758. function handleMissing(context, key, locale, missingWarn, type) {
  759. const { missing, onWarn } = context;
  760. // for vue-devtools timeline event
  761. {
  762. const emitter = context.__v_emitter;
  763. if (emitter) {
  764. emitter.emit("missing" /* MISSING */, {
  765. locale,
  766. key,
  767. type,
  768. groupId: `${type}:${key}`
  769. });
  770. }
  771. }
  772. if (missing !== null) {
  773. const ret = missing(context, locale, key, type);
  774. return isString(ret) ? ret : key;
  775. }
  776. else {
  777. if (isTranslateMissingWarn(missingWarn, key)) {
  778. onWarn(getWarnMessage$1(0 /* NOT_FOUND_KEY */, { key, locale }));
  779. }
  780. return key;
  781. }
  782. }
  783. /** @internal */
  784. function getLocaleChain(ctx, fallback, start) {
  785. const context = ctx;
  786. if (!context.__localeChainCache) {
  787. context.__localeChainCache = new Map();
  788. }
  789. let chain = context.__localeChainCache.get(start);
  790. if (!chain) {
  791. chain = [];
  792. // first block defined by start
  793. let block = [start];
  794. // while any intervening block found
  795. while (isArray(block)) {
  796. block = appendBlockToChain(chain, block, fallback);
  797. }
  798. // prettier-ignore
  799. // last block defined by default
  800. const defaults = isArray(fallback)
  801. ? fallback
  802. : isPlainObject(fallback)
  803. ? fallback['default']
  804. ? fallback['default']
  805. : null
  806. : fallback;
  807. // convert defaults to array
  808. block = isString(defaults) ? [defaults] : defaults;
  809. if (isArray(block)) {
  810. appendBlockToChain(chain, block, false);
  811. }
  812. context.__localeChainCache.set(start, chain);
  813. }
  814. return chain;
  815. }
  816. function appendBlockToChain(chain, block, blocks) {
  817. let follow = true;
  818. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  819. const locale = block[i];
  820. if (isString(locale)) {
  821. follow = appendLocaleToChain(chain, block[i], blocks);
  822. }
  823. }
  824. return follow;
  825. }
  826. function appendLocaleToChain(chain, locale, blocks) {
  827. let follow;
  828. const tokens = locale.split('-');
  829. do {
  830. const target = tokens.join('-');
  831. follow = appendItemToChain(chain, target, blocks);
  832. tokens.splice(-1, 1);
  833. } while (tokens.length && follow === true);
  834. return follow;
  835. }
  836. function appendItemToChain(chain, target, blocks) {
  837. let follow = false;
  838. if (!chain.includes(target)) {
  839. follow = true;
  840. if (target) {
  841. follow = target[target.length - 1] !== '!';
  842. const locale = target.replace(/!/g, '');
  843. chain.push(locale);
  844. if ((isArray(blocks) || isPlainObject(blocks)) &&
  845. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  846. ) {
  847. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  848. follow = blocks[locale];
  849. }
  850. }
  851. }
  852. return follow;
  853. }
  854. /** @internal */
  855. function updateFallbackLocale(ctx, locale, fallback) {
  856. const context = ctx;
  857. context.__localeChainCache = new Map();
  858. getLocaleChain(ctx, fallback, locale);
  859. }
  860. function createCoreError(code) {
  861. return createCompileError(code, null, { messages: errorMessages$1 } );
  862. }
  863. /** @internal */
  864. const errorMessages$1 = {
  865. [14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
  866. [15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
  867. 'Make sure your Date represents a valid date.',
  868. [16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
  869. };
  870. const NOOP_MESSAGE_FUNCTION = () => '';
  871. const isMessageFunction = (val) => isFunction(val);
  872. // implementation of `translate` function
  873. function translate(context, ...args) {
  874. const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
  875. const [key, options] = parseTranslateArgs(...args);
  876. const missingWarn = isBoolean(options.missingWarn)
  877. ? options.missingWarn
  878. : context.missingWarn;
  879. const fallbackWarn = isBoolean(options.fallbackWarn)
  880. ? options.fallbackWarn
  881. : context.fallbackWarn;
  882. const escapeParameter = isBoolean(options.escapeParameter)
  883. ? options.escapeParameter
  884. : context.escapeParameter;
  885. const resolvedMessage = !!options.resolvedMessage;
  886. // prettier-ignore
  887. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  888. ? !isBoolean(options.default)
  889. ? options.default
  890. : key
  891. : fallbackFormat // default by `fallbackFormat` option
  892. ? key
  893. : '';
  894. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  895. const locale = isString(options.locale) ? options.locale : context.locale;
  896. // escape params
  897. escapeParameter && escapeParams(options);
  898. // resolve message format
  899. // eslint-disable-next-line prefer-const
  900. let [format, targetLocale, message] = !resolvedMessage
  901. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  902. : [
  903. key,
  904. locale,
  905. messages[locale] || {}
  906. ];
  907. // if you use default message, set it as message format!
  908. let cacheBaseKey = key;
  909. if (!resolvedMessage &&
  910. !(isString(format) || isMessageFunction(format))) {
  911. if (enableDefaultMsg) {
  912. format = defaultMsgOrKey;
  913. cacheBaseKey = format;
  914. }
  915. }
  916. // checking message format and target locale
  917. if (!resolvedMessage &&
  918. (!(isString(format) || isMessageFunction(format)) ||
  919. !isString(targetLocale))) {
  920. return unresolving ? NOT_REOSLVED : key;
  921. }
  922. if (isString(format) && context.messageCompiler == null) {
  923. warn(`The message format compilation is not supported in this build. ` +
  924. `Because message compiler isn't included. ` +
  925. `You need to pre-compilation all message format. ` +
  926. `So translate function return '${key}'.`);
  927. return key;
  928. }
  929. // setup compile error detecting
  930. let occurred = false;
  931. const errorDetector = () => {
  932. occurred = true;
  933. };
  934. // compile message format
  935. const msg = !isMessageFunction(format)
  936. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
  937. : format;
  938. // if occurred compile error, return the message format
  939. if (occurred) {
  940. return format;
  941. }
  942. // evaluate message with context
  943. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  944. const msgContext = createMessageContext(ctxOptions);
  945. const messaged = evaluateMessage(context, msg, msgContext);
  946. // if use post translation option, proceed it with handler
  947. const ret = postTranslation ? postTranslation(messaged) : messaged;
  948. // NOTE: experimental !!
  949. {
  950. // prettier-ignore
  951. const payloads = {
  952. timestamp: Date.now(),
  953. key: isString(key)
  954. ? key
  955. : isMessageFunction(format)
  956. ? format.key
  957. : '',
  958. locale: targetLocale || (isMessageFunction(format)
  959. ? format.locale
  960. : ''),
  961. format: isString(format)
  962. ? format
  963. : isMessageFunction(format)
  964. ? format.source
  965. : '',
  966. message: ret
  967. };
  968. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  969. translateDevTools(payloads);
  970. }
  971. return ret;
  972. }
  973. function escapeParams(options) {
  974. if (isArray(options.list)) {
  975. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  976. }
  977. else if (isObject(options.named)) {
  978. Object.keys(options.named).forEach(key => {
  979. if (isString(options.named[key])) {
  980. options.named[key] = escapeHtml(options.named[key]);
  981. }
  982. });
  983. }
  984. }
  985. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  986. const { messages, onWarn } = context;
  987. const locales = getLocaleChain(context, fallbackLocale, locale);
  988. let message = {};
  989. let targetLocale;
  990. let format = null;
  991. let from = locale;
  992. let to = null;
  993. const type = 'translate';
  994. for (let i = 0; i < locales.length; i++) {
  995. targetLocale = to = locales[i];
  996. if (locale !== targetLocale &&
  997. isTranslateFallbackWarn(fallbackWarn, key)) {
  998. onWarn(getWarnMessage$1(1 /* FALLBACK_TO_TRANSLATE */, {
  999. key,
  1000. target: targetLocale
  1001. }));
  1002. }
  1003. // for vue-devtools timeline event
  1004. if (locale !== targetLocale) {
  1005. const emitter = context.__v_emitter;
  1006. if (emitter) {
  1007. emitter.emit("fallback" /* FALBACK */, {
  1008. type,
  1009. key,
  1010. from,
  1011. to,
  1012. groupId: `${type}:${key}`
  1013. });
  1014. }
  1015. }
  1016. message =
  1017. messages[targetLocale] || {};
  1018. // for vue-devtools timeline event
  1019. let start = null;
  1020. let startTag;
  1021. let endTag;
  1022. if (inBrowser) {
  1023. start = window.performance.now();
  1024. startTag = 'intlify-message-resolve-start';
  1025. endTag = 'intlify-message-resolve-end';
  1026. mark && mark(startTag);
  1027. }
  1028. if ((format = resolveValue(message, key)) === null) {
  1029. // if null, resolve with object key path
  1030. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1031. }
  1032. // for vue-devtools timeline event
  1033. if (inBrowser) {
  1034. const end = window.performance.now();
  1035. const emitter = context.__v_emitter;
  1036. if (emitter && start && format) {
  1037. emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
  1038. type: "message-resolve" /* MESSAGE_RESOLVE */,
  1039. key,
  1040. message: format,
  1041. time: end - start,
  1042. groupId: `${type}:${key}`
  1043. });
  1044. }
  1045. if (startTag && endTag && mark && measure) {
  1046. mark(endTag);
  1047. measure('intlify message resolve', startTag, endTag);
  1048. }
  1049. }
  1050. if (isString(format) || isFunction(format))
  1051. break;
  1052. const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
  1053. if (missingRet !== key) {
  1054. format = missingRet;
  1055. }
  1056. from = to;
  1057. }
  1058. return [format, targetLocale, message];
  1059. }
  1060. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
  1061. const { messageCompiler, warnHtmlMessage } = context;
  1062. if (isMessageFunction(format)) {
  1063. const msg = format;
  1064. msg.locale = msg.locale || targetLocale;
  1065. msg.key = msg.key || key;
  1066. return msg;
  1067. }
  1068. // for vue-devtools timeline event
  1069. let start = null;
  1070. let startTag;
  1071. let endTag;
  1072. if (inBrowser) {
  1073. start = window.performance.now();
  1074. startTag = 'intlify-message-compilation-start';
  1075. endTag = 'intlify-message-compilation-end';
  1076. mark && mark(startTag);
  1077. }
  1078. const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
  1079. // for vue-devtools timeline event
  1080. if (inBrowser) {
  1081. const end = window.performance.now();
  1082. const emitter = context.__v_emitter;
  1083. if (emitter && start) {
  1084. emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
  1085. type: "message-compilation" /* MESSAGE_COMPILATION */,
  1086. message: format,
  1087. time: end - start,
  1088. groupId: `${'translate'}:${key}`
  1089. });
  1090. }
  1091. if (startTag && endTag && mark && measure) {
  1092. mark(endTag);
  1093. measure('intlify message compilation', startTag, endTag);
  1094. }
  1095. }
  1096. msg.locale = targetLocale;
  1097. msg.key = key;
  1098. msg.source = format;
  1099. return msg;
  1100. }
  1101. function evaluateMessage(context, msg, msgCtx) {
  1102. // for vue-devtools timeline event
  1103. let start = null;
  1104. let startTag;
  1105. let endTag;
  1106. if (inBrowser) {
  1107. start = window.performance.now();
  1108. startTag = 'intlify-message-evaluation-start';
  1109. endTag = 'intlify-message-evaluation-end';
  1110. mark && mark(startTag);
  1111. }
  1112. const messaged = msg(msgCtx);
  1113. // for vue-devtools timeline event
  1114. if (inBrowser) {
  1115. const end = window.performance.now();
  1116. const emitter = context.__v_emitter;
  1117. if (emitter && start) {
  1118. emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
  1119. type: "message-evaluation" /* MESSAGE_EVALUATION */,
  1120. value: messaged,
  1121. time: end - start,
  1122. groupId: `${'translate'}:${msg.key}`
  1123. });
  1124. }
  1125. if (startTag && endTag && mark && measure) {
  1126. mark(endTag);
  1127. measure('intlify message evaluation', startTag, endTag);
  1128. }
  1129. }
  1130. return messaged;
  1131. }
  1132. /** @internal */
  1133. function parseTranslateArgs(...args) {
  1134. const [arg1, arg2, arg3] = args;
  1135. const options = {};
  1136. if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
  1137. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1138. }
  1139. // prettier-ignore
  1140. const key = isNumber(arg1)
  1141. ? String(arg1)
  1142. : isMessageFunction(arg1)
  1143. ? arg1
  1144. : arg1;
  1145. if (isNumber(arg2)) {
  1146. options.plural = arg2;
  1147. }
  1148. else if (isString(arg2)) {
  1149. options.default = arg2;
  1150. }
  1151. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  1152. options.named = arg2;
  1153. }
  1154. else if (isArray(arg2)) {
  1155. options.list = arg2;
  1156. }
  1157. if (isNumber(arg3)) {
  1158. options.plural = arg3;
  1159. }
  1160. else if (isString(arg3)) {
  1161. options.default = arg3;
  1162. }
  1163. else if (isPlainObject(arg3)) {
  1164. assign(options, arg3);
  1165. }
  1166. return [key, options];
  1167. }
  1168. function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
  1169. return {
  1170. warnHtmlMessage,
  1171. onError: (err) => {
  1172. errorDetector && errorDetector(err);
  1173. {
  1174. const message = `Message compilation error: ${err.message}`;
  1175. const codeFrame = err.location &&
  1176. generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
  1177. const emitter = context
  1178. .__v_emitter;
  1179. if (emitter) {
  1180. emitter.emit("compile-error" /* COMPILE_ERROR */, {
  1181. message: source,
  1182. error: err.message,
  1183. start: err.location && err.location.start.offset,
  1184. end: err.location && err.location.end.offset,
  1185. groupId: `${'translate'}:${key}`
  1186. });
  1187. }
  1188. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1189. }
  1190. },
  1191. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  1192. };
  1193. }
  1194. function getMessageContextOptions(context, locale, message, options) {
  1195. const { modifiers, pluralRules } = context;
  1196. const resolveMessage = (key) => {
  1197. const val = resolveValue(message, key);
  1198. if (isString(val)) {
  1199. let occurred = false;
  1200. const errorDetector = () => {
  1201. occurred = true;
  1202. };
  1203. const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
  1204. return !occurred
  1205. ? msg
  1206. : NOOP_MESSAGE_FUNCTION;
  1207. }
  1208. else if (isMessageFunction(val)) {
  1209. return val;
  1210. }
  1211. else {
  1212. // TODO: should be implemented warning message
  1213. return NOOP_MESSAGE_FUNCTION;
  1214. }
  1215. };
  1216. const ctxOptions = {
  1217. locale,
  1218. modifiers,
  1219. pluralRules,
  1220. messages: resolveMessage
  1221. };
  1222. if (context.processor) {
  1223. ctxOptions.processor = context.processor;
  1224. }
  1225. if (options.list) {
  1226. ctxOptions.list = options.list;
  1227. }
  1228. if (options.named) {
  1229. ctxOptions.named = options.named;
  1230. }
  1231. if (isNumber(options.plural)) {
  1232. ctxOptions.pluralIndex = options.plural;
  1233. }
  1234. return ctxOptions;
  1235. }
  1236. const intlDefined = typeof Intl !== 'undefined';
  1237. const Availabilities = {
  1238. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1239. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1240. };
  1241. // implementation of `datetime` function
  1242. function datetime(context, ...args) {
  1243. const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
  1244. const { __datetimeFormatters } = context;
  1245. if (!Availabilities.dateTimeFormat) {
  1246. onWarn(getWarnMessage$1(4 /* CANNOT_FORMAT_DATE */));
  1247. return MISSING_RESOLVE_VALUE;
  1248. }
  1249. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1250. const missingWarn = isBoolean(options.missingWarn)
  1251. ? options.missingWarn
  1252. : context.missingWarn;
  1253. const fallbackWarn = isBoolean(options.fallbackWarn)
  1254. ? options.fallbackWarn
  1255. : context.fallbackWarn;
  1256. const part = !!options.part;
  1257. const locale = isString(options.locale) ? options.locale : context.locale;
  1258. const locales = getLocaleChain(context, fallbackLocale, locale);
  1259. if (!isString(key) || key === '') {
  1260. return new Intl.DateTimeFormat(locale).format(value);
  1261. }
  1262. // resolve format
  1263. let datetimeFormat = {};
  1264. let targetLocale;
  1265. let format = null;
  1266. let from = locale;
  1267. let to = null;
  1268. const type = 'datetime format';
  1269. for (let i = 0; i < locales.length; i++) {
  1270. targetLocale = to = locales[i];
  1271. if (locale !== targetLocale &&
  1272. isTranslateFallbackWarn(fallbackWarn, key)) {
  1273. onWarn(getWarnMessage$1(5 /* FALLBACK_TO_DATE_FORMAT */, {
  1274. key,
  1275. target: targetLocale
  1276. }));
  1277. }
  1278. // for vue-devtools timeline event
  1279. if (locale !== targetLocale) {
  1280. const emitter = context.__v_emitter;
  1281. if (emitter) {
  1282. emitter.emit("fallback" /* FALBACK */, {
  1283. type,
  1284. key,
  1285. from,
  1286. to,
  1287. groupId: `${type}:${key}`
  1288. });
  1289. }
  1290. }
  1291. datetimeFormat =
  1292. datetimeFormats[targetLocale] || {};
  1293. format = datetimeFormat[key];
  1294. if (isPlainObject(format))
  1295. break;
  1296. handleMissing(context, key, targetLocale, missingWarn, type);
  1297. from = to;
  1298. }
  1299. // checking format and target locale
  1300. if (!isPlainObject(format) || !isString(targetLocale)) {
  1301. return unresolving ? NOT_REOSLVED : key;
  1302. }
  1303. let id = `${targetLocale}__${key}`;
  1304. if (!isEmptyObject(overrides)) {
  1305. id = `${id}__${JSON.stringify(overrides)}`;
  1306. }
  1307. let formatter = __datetimeFormatters.get(id);
  1308. if (!formatter) {
  1309. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  1310. __datetimeFormatters.set(id, formatter);
  1311. }
  1312. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1313. }
  1314. /** @internal */
  1315. function parseDateTimeArgs(...args) {
  1316. const [arg1, arg2, arg3, arg4] = args;
  1317. let options = {};
  1318. let overrides = {};
  1319. let value;
  1320. if (isString(arg1)) {
  1321. // Only allow ISO strings - other date formats are often supported,
  1322. // but may cause different results in different browsers.
  1323. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
  1324. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  1325. }
  1326. value = new Date(arg1);
  1327. try {
  1328. // This will fail if the date is not valid
  1329. value.toISOString();
  1330. }
  1331. catch (e) {
  1332. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  1333. }
  1334. }
  1335. else if (isDate(arg1)) {
  1336. if (isNaN(arg1.getTime())) {
  1337. throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
  1338. }
  1339. value = arg1;
  1340. }
  1341. else if (isNumber(arg1)) {
  1342. value = arg1;
  1343. }
  1344. else {
  1345. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1346. }
  1347. if (isString(arg2)) {
  1348. options.key = arg2;
  1349. }
  1350. else if (isPlainObject(arg2)) {
  1351. options = arg2;
  1352. }
  1353. if (isString(arg3)) {
  1354. options.locale = arg3;
  1355. }
  1356. else if (isPlainObject(arg3)) {
  1357. overrides = arg3;
  1358. }
  1359. if (isPlainObject(arg4)) {
  1360. overrides = arg4;
  1361. }
  1362. return [options.key || '', value, options, overrides];
  1363. }
  1364. /** @internal */
  1365. function clearDateTimeFormat(ctx, locale, format) {
  1366. const context = ctx;
  1367. for (const key in format) {
  1368. const id = `${locale}__${key}`;
  1369. if (!context.__datetimeFormatters.has(id)) {
  1370. continue;
  1371. }
  1372. context.__datetimeFormatters.delete(id);
  1373. }
  1374. }
  1375. // implementation of `number` function
  1376. function number(context, ...args) {
  1377. const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
  1378. const { __numberFormatters } = context;
  1379. if (!Availabilities.numberFormat) {
  1380. onWarn(getWarnMessage$1(2 /* CANNOT_FORMAT_NUMBER */));
  1381. return MISSING_RESOLVE_VALUE;
  1382. }
  1383. const [key, value, options, overrides] = parseNumberArgs(...args);
  1384. const missingWarn = isBoolean(options.missingWarn)
  1385. ? options.missingWarn
  1386. : context.missingWarn;
  1387. const fallbackWarn = isBoolean(options.fallbackWarn)
  1388. ? options.fallbackWarn
  1389. : context.fallbackWarn;
  1390. const part = !!options.part;
  1391. const locale = isString(options.locale) ? options.locale : context.locale;
  1392. const locales = getLocaleChain(context, fallbackLocale, locale);
  1393. if (!isString(key) || key === '') {
  1394. return new Intl.NumberFormat(locale).format(value);
  1395. }
  1396. // resolve format
  1397. let numberFormat = {};
  1398. let targetLocale;
  1399. let format = null;
  1400. let from = locale;
  1401. let to = null;
  1402. const type = 'number format';
  1403. for (let i = 0; i < locales.length; i++) {
  1404. targetLocale = to = locales[i];
  1405. if (locale !== targetLocale &&
  1406. isTranslateFallbackWarn(fallbackWarn, key)) {
  1407. onWarn(getWarnMessage$1(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
  1408. key,
  1409. target: targetLocale
  1410. }));
  1411. }
  1412. // for vue-devtools timeline event
  1413. if (locale !== targetLocale) {
  1414. const emitter = context.__v_emitter;
  1415. if (emitter) {
  1416. emitter.emit("fallback" /* FALBACK */, {
  1417. type,
  1418. key,
  1419. from,
  1420. to,
  1421. groupId: `${type}:${key}`
  1422. });
  1423. }
  1424. }
  1425. numberFormat =
  1426. numberFormats[targetLocale] || {};
  1427. format = numberFormat[key];
  1428. if (isPlainObject(format))
  1429. break;
  1430. handleMissing(context, key, targetLocale, missingWarn, type);
  1431. from = to;
  1432. }
  1433. // checking format and target locale
  1434. if (!isPlainObject(format) || !isString(targetLocale)) {
  1435. return unresolving ? NOT_REOSLVED : key;
  1436. }
  1437. let id = `${targetLocale}__${key}`;
  1438. if (!isEmptyObject(overrides)) {
  1439. id = `${id}__${JSON.stringify(overrides)}`;
  1440. }
  1441. let formatter = __numberFormatters.get(id);
  1442. if (!formatter) {
  1443. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  1444. __numberFormatters.set(id, formatter);
  1445. }
  1446. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1447. }
  1448. /** @internal */
  1449. function parseNumberArgs(...args) {
  1450. const [arg1, arg2, arg3, arg4] = args;
  1451. let options = {};
  1452. let overrides = {};
  1453. if (!isNumber(arg1)) {
  1454. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1455. }
  1456. const value = arg1;
  1457. if (isString(arg2)) {
  1458. options.key = arg2;
  1459. }
  1460. else if (isPlainObject(arg2)) {
  1461. options = arg2;
  1462. }
  1463. if (isString(arg3)) {
  1464. options.locale = arg3;
  1465. }
  1466. else if (isPlainObject(arg3)) {
  1467. overrides = arg3;
  1468. }
  1469. if (isPlainObject(arg4)) {
  1470. overrides = arg4;
  1471. }
  1472. return [options.key || '', value, options, overrides];
  1473. }
  1474. /** @internal */
  1475. function clearNumberFormat(ctx, locale, format) {
  1476. const context = ctx;
  1477. for (const key in format) {
  1478. const id = `${locale}__${key}`;
  1479. if (!context.__numberFormatters.has(id)) {
  1480. continue;
  1481. }
  1482. context.__numberFormatters.delete(id);
  1483. }
  1484. }
  1485. /**
  1486. * Vue I18n Version
  1487. *
  1488. * @remarks
  1489. * Semver format. Same format as the package.json `version` field.
  1490. *
  1491. * @VueI18nGeneral
  1492. */
  1493. const VERSION = '9.1.9';
  1494. /**
  1495. * This is only called development env
  1496. * istanbul-ignore-next
  1497. */
  1498. function initDev() {
  1499. {
  1500. {
  1501. console.info(`You are running a development build of vue-i18n.\n` +
  1502. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  1503. }
  1504. }
  1505. }
  1506. const warnMessages = {
  1507. [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
  1508. [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`,
  1509. [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`,
  1510. [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`,
  1511. [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`,
  1512. [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  1513. [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
  1514. };
  1515. function getWarnMessage(code, ...args) {
  1516. return format(warnMessages[code], ...args);
  1517. }
  1518. function createI18nError(code, ...args) {
  1519. return createCompileError(code, null, { messages: errorMessages, args } );
  1520. }
  1521. const errorMessages = {
  1522. [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
  1523. [15 /* INVALID_ARGUMENT */]: 'Invalid argument',
  1524. [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
  1525. [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
  1526. [22 /* UNEXPECTED_ERROR */]: 'Unexpected error',
  1527. [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
  1528. [19 /* REQUIRED_VALUE */]: `Required in value: {0}`,
  1529. [20 /* INVALID_VALUE */]: `Invalid value`,
  1530. [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
  1531. };
  1532. const DEVTOOLS_META = '__INTLIFY_META__';
  1533. const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
  1534. const DatetimePartsSymbol = makeSymbol('__datetimeParts');
  1535. const NumberPartsSymbol = makeSymbol('__numberParts');
  1536. const EnableEmitter = makeSymbol('__enableEmitter');
  1537. const DisableEmitter = makeSymbol('__disableEmitter');
  1538. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  1539. const InejctWithOption = makeSymbol('__injectWithOption');
  1540. let composerID = 0;
  1541. function defineCoreMissingHandler(missing) {
  1542. return ((ctx, locale, key, type) => {
  1543. return missing(locale, key, vue.getCurrentInstance() || undefined, type);
  1544. });
  1545. }
  1546. function getLocaleMessages(locale, options) {
  1547. const { messages, __i18n } = options;
  1548. // prettier-ignore
  1549. const ret = isPlainObject(messages)
  1550. ? messages
  1551. : isArray(__i18n)
  1552. ? {}
  1553. : { [locale]: {} };
  1554. // merge locale messages of i18n custom block
  1555. if (isArray(__i18n)) {
  1556. __i18n.forEach(({ locale, resource }) => {
  1557. if (locale) {
  1558. ret[locale] = ret[locale] || {};
  1559. deepCopy(resource, ret[locale]);
  1560. }
  1561. else {
  1562. deepCopy(resource, ret);
  1563. }
  1564. });
  1565. }
  1566. // handle messages for flat json
  1567. if (options.flatJson) {
  1568. for (const key in ret) {
  1569. if (hasOwn(ret, key)) {
  1570. handleFlatJson(ret[key]);
  1571. }
  1572. }
  1573. }
  1574. return ret;
  1575. }
  1576. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  1577. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1578. function deepCopy(src, des) {
  1579. // src and des should both be objects, and non of then can be a array
  1580. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  1581. throw createI18nError(20 /* INVALID_VALUE */);
  1582. }
  1583. for (const key in src) {
  1584. if (hasOwn(src, key)) {
  1585. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  1586. // replace with src[key] when:
  1587. // src[key] or des[key] is not a object, or
  1588. // src[key] or des[key] is a array
  1589. des[key] = src[key];
  1590. }
  1591. else {
  1592. // src[key] and des[key] are both object, merge them
  1593. deepCopy(src[key], des[key]);
  1594. }
  1595. }
  1596. }
  1597. }
  1598. // for Intlify DevTools
  1599. const getMetaInfo = /* #__PURE__*/ () => {
  1600. const instance = vue.getCurrentInstance();
  1601. return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any
  1602. ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any
  1603. : null;
  1604. };
  1605. /**
  1606. * Create composer interface factory
  1607. *
  1608. * @internal
  1609. */
  1610. function createComposer(options = {}) {
  1611. const { __root } = options;
  1612. const _isGlobal = __root === undefined;
  1613. let _inheritLocale = isBoolean(options.inheritLocale)
  1614. ? options.inheritLocale
  1615. : true;
  1616. const _locale = vue.ref(
  1617. // prettier-ignore
  1618. __root && _inheritLocale
  1619. ? __root.locale.value
  1620. : isString(options.locale)
  1621. ? options.locale
  1622. : 'en-US');
  1623. const _fallbackLocale = vue.ref(
  1624. // prettier-ignore
  1625. __root && _inheritLocale
  1626. ? __root.fallbackLocale.value
  1627. : isString(options.fallbackLocale) ||
  1628. isArray(options.fallbackLocale) ||
  1629. isPlainObject(options.fallbackLocale) ||
  1630. options.fallbackLocale === false
  1631. ? options.fallbackLocale
  1632. : _locale.value);
  1633. const _messages = vue.ref(getLocaleMessages(_locale.value, options));
  1634. const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats)
  1635. ? options.datetimeFormats
  1636. : { [_locale.value]: {} });
  1637. const _numberFormats = vue.ref(isPlainObject(options.numberFormats)
  1638. ? options.numberFormats
  1639. : { [_locale.value]: {} });
  1640. // warning suppress options
  1641. // prettier-ignore
  1642. let _missingWarn = __root
  1643. ? __root.missingWarn
  1644. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1645. ? options.missingWarn
  1646. : true;
  1647. // prettier-ignore
  1648. let _fallbackWarn = __root
  1649. ? __root.fallbackWarn
  1650. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1651. ? options.fallbackWarn
  1652. : true;
  1653. // prettier-ignore
  1654. let _fallbackRoot = __root
  1655. ? __root.fallbackRoot
  1656. : isBoolean(options.fallbackRoot)
  1657. ? options.fallbackRoot
  1658. : true;
  1659. // configure fall back to root
  1660. let _fallbackFormat = !!options.fallbackFormat;
  1661. // runtime missing
  1662. let _missing = isFunction(options.missing) ? options.missing : null;
  1663. let _runtimeMissing = isFunction(options.missing)
  1664. ? defineCoreMissingHandler(options.missing)
  1665. : null;
  1666. // postTranslation handler
  1667. let _postTranslation = isFunction(options.postTranslation)
  1668. ? options.postTranslation
  1669. : null;
  1670. let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1671. ? options.warnHtmlMessage
  1672. : true;
  1673. let _escapeParameter = !!options.escapeParameter;
  1674. // custom linked modifiers
  1675. // prettier-ignore
  1676. const _modifiers = __root
  1677. ? __root.modifiers
  1678. : isPlainObject(options.modifiers)
  1679. ? options.modifiers
  1680. : {};
  1681. // pluralRules
  1682. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  1683. // runtime context
  1684. // eslint-disable-next-line prefer-const
  1685. let _context;
  1686. function getCoreContext() {
  1687. return createCoreContext({
  1688. version: VERSION,
  1689. locale: _locale.value,
  1690. fallbackLocale: _fallbackLocale.value,
  1691. messages: _messages.value,
  1692. datetimeFormats: _datetimeFormats.value,
  1693. numberFormats: _numberFormats.value,
  1694. modifiers: _modifiers,
  1695. pluralRules: _pluralRules,
  1696. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  1697. missingWarn: _missingWarn,
  1698. fallbackWarn: _fallbackWarn,
  1699. fallbackFormat: _fallbackFormat,
  1700. unresolving: true,
  1701. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  1702. warnHtmlMessage: _warnHtmlMessage,
  1703. escapeParameter: _escapeParameter,
  1704. __datetimeFormatters: isPlainObject(_context)
  1705. ? _context.__datetimeFormatters
  1706. : undefined,
  1707. __numberFormatters: isPlainObject(_context)
  1708. ? _context.__numberFormatters
  1709. : undefined,
  1710. __v_emitter: isPlainObject(_context)
  1711. ? _context.__v_emitter
  1712. : undefined,
  1713. __meta: { framework: 'vue' }
  1714. });
  1715. }
  1716. _context = getCoreContext();
  1717. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1718. // track reactivity
  1719. function trackReactivityValues() {
  1720. return [
  1721. _locale.value,
  1722. _fallbackLocale.value,
  1723. _messages.value,
  1724. _datetimeFormats.value,
  1725. _numberFormats.value
  1726. ];
  1727. }
  1728. // locale
  1729. const locale = vue.computed({
  1730. get: () => _locale.value,
  1731. set: val => {
  1732. _locale.value = val;
  1733. _context.locale = _locale.value;
  1734. }
  1735. });
  1736. // fallbackLocale
  1737. const fallbackLocale = vue.computed({
  1738. get: () => _fallbackLocale.value,
  1739. set: val => {
  1740. _fallbackLocale.value = val;
  1741. _context.fallbackLocale = _fallbackLocale.value;
  1742. updateFallbackLocale(_context, _locale.value, val);
  1743. }
  1744. });
  1745. // messages
  1746. const messages = vue.computed(() => _messages.value);
  1747. // datetimeFormats
  1748. const datetimeFormats = vue.computed(() => _datetimeFormats.value);
  1749. // numberFormats
  1750. const numberFormats = vue.computed(() => _numberFormats.value);
  1751. // getPostTranslationHandler
  1752. function getPostTranslationHandler() {
  1753. return isFunction(_postTranslation) ? _postTranslation : null;
  1754. }
  1755. // setPostTranslationHandler
  1756. function setPostTranslationHandler(handler) {
  1757. _postTranslation = handler;
  1758. _context.postTranslation = handler;
  1759. }
  1760. // getMissingHandler
  1761. function getMissingHandler() {
  1762. return _missing;
  1763. }
  1764. // setMissingHandler
  1765. function setMissingHandler(handler) {
  1766. if (handler !== null) {
  1767. _runtimeMissing = defineCoreMissingHandler(handler);
  1768. }
  1769. _missing = handler;
  1770. _context.missing = _runtimeMissing;
  1771. }
  1772. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  1773. ) {
  1774. return type !== 'translate' || !!arg.resolvedMessage === false;
  1775. }
  1776. function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
  1777. trackReactivityValues(); // track reactive dependency
  1778. // NOTE: experimental !!
  1779. let ret;
  1780. {
  1781. try {
  1782. setAdditionalMeta(getMetaInfo());
  1783. ret = fn(_context);
  1784. }
  1785. finally {
  1786. setAdditionalMeta(null);
  1787. }
  1788. }
  1789. if (isNumber(ret) && ret === NOT_REOSLVED) {
  1790. const [key, arg2] = argumentParser();
  1791. if (__root &&
  1792. isString(key) &&
  1793. isResolvedTranslateMessage(warnType, arg2)) {
  1794. if (_fallbackRoot &&
  1795. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  1796. isTranslateMissingWarn(_missingWarn, key))) {
  1797. warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
  1798. key,
  1799. type: warnType
  1800. }));
  1801. }
  1802. // for vue-devtools timeline event
  1803. {
  1804. const { __v_emitter: emitter } = _context;
  1805. if (emitter && _fallbackRoot) {
  1806. emitter.emit("fallback" /* FALBACK */, {
  1807. type: warnType,
  1808. key,
  1809. to: 'global',
  1810. groupId: `${warnType}:${key}`
  1811. });
  1812. }
  1813. }
  1814. }
  1815. return __root && _fallbackRoot
  1816. ? fallbackSuccess(__root)
  1817. : fallbackFail(key);
  1818. }
  1819. else if (successCondition(ret)) {
  1820. return ret;
  1821. }
  1822. else {
  1823. /* istanbul ignore next */
  1824. throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */);
  1825. }
  1826. }
  1827. // t
  1828. function t(...args) {
  1829. return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val));
  1830. }
  1831. // rt
  1832. function rt(...args) {
  1833. const [arg1, arg2, arg3] = args;
  1834. if (arg3 && !isObject(arg3)) {
  1835. throw createI18nError(15 /* INVALID_ARGUMENT */);
  1836. }
  1837. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  1838. }
  1839. // d
  1840. function d(...args) {
  1841. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  1842. }
  1843. // n
  1844. function n(...args) {
  1845. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  1846. }
  1847. // for custom processor
  1848. function normalize(values) {
  1849. return values.map(val => isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val);
  1850. }
  1851. const interpolate = (val) => val;
  1852. const processor = {
  1853. normalize,
  1854. interpolate,
  1855. type: 'vnode'
  1856. };
  1857. // transrateVNode, using for `i18n-t` component
  1858. function transrateVNode(...args) {
  1859. return wrapWithDeps(context => {
  1860. let ret;
  1861. const _context = context;
  1862. try {
  1863. _context.processor = processor;
  1864. ret = translate(_context, ...args);
  1865. }
  1866. finally {
  1867. _context.processor = null;
  1868. }
  1869. return ret;
  1870. }, () => parseTranslateArgs(...args), 'translate',
  1871. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1872. root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => isArray(val));
  1873. }
  1874. // numberParts, using for `i18n-n` component
  1875. function numberParts(...args) {
  1876. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format',
  1877. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1878. root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  1879. }
  1880. // datetimeParts, using for `i18n-d` component
  1881. function datetimeParts(...args) {
  1882. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format',
  1883. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1884. root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  1885. }
  1886. function setPluralRules(rules) {
  1887. _pluralRules = rules;
  1888. _context.pluralRules = _pluralRules;
  1889. }
  1890. // te
  1891. function te(key, locale) {
  1892. const targetLocale = isString(locale) ? locale : _locale.value;
  1893. const message = getLocaleMessage(targetLocale);
  1894. return resolveValue(message, key) !== null;
  1895. }
  1896. function resolveMessages(key) {
  1897. let messages = null;
  1898. const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value);
  1899. for (let i = 0; i < locales.length; i++) {
  1900. const targetLocaleMessages = _messages.value[locales[i]] || {};
  1901. const messageValue = resolveValue(targetLocaleMessages, key);
  1902. if (messageValue != null) {
  1903. messages = messageValue;
  1904. break;
  1905. }
  1906. }
  1907. return messages;
  1908. }
  1909. // tm
  1910. function tm(key) {
  1911. const messages = resolveMessages(key);
  1912. // prettier-ignore
  1913. return messages != null
  1914. ? messages
  1915. : __root
  1916. ? __root.tm(key) || {}
  1917. : {};
  1918. }
  1919. // getLocaleMessage
  1920. function getLocaleMessage(locale) {
  1921. return (_messages.value[locale] || {});
  1922. }
  1923. // setLocaleMessage
  1924. function setLocaleMessage(locale, message) {
  1925. _messages.value[locale] = message;
  1926. _context.messages = _messages.value;
  1927. }
  1928. // mergeLocaleMessage
  1929. function mergeLocaleMessage(locale, message) {
  1930. _messages.value[locale] = _messages.value[locale] || {};
  1931. deepCopy(message, _messages.value[locale]);
  1932. _context.messages = _messages.value;
  1933. }
  1934. // getDateTimeFormat
  1935. function getDateTimeFormat(locale) {
  1936. return _datetimeFormats.value[locale] || {};
  1937. }
  1938. // setDateTimeFormat
  1939. function setDateTimeFormat(locale, format) {
  1940. _datetimeFormats.value[locale] = format;
  1941. _context.datetimeFormats = _datetimeFormats.value;
  1942. clearDateTimeFormat(_context, locale, format);
  1943. }
  1944. // mergeDateTimeFormat
  1945. function mergeDateTimeFormat(locale, format) {
  1946. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  1947. _context.datetimeFormats = _datetimeFormats.value;
  1948. clearDateTimeFormat(_context, locale, format);
  1949. }
  1950. // getNumberFormat
  1951. function getNumberFormat(locale) {
  1952. return _numberFormats.value[locale] || {};
  1953. }
  1954. // setNumberFormat
  1955. function setNumberFormat(locale, format) {
  1956. _numberFormats.value[locale] = format;
  1957. _context.numberFormats = _numberFormats.value;
  1958. clearNumberFormat(_context, locale, format);
  1959. }
  1960. // mergeNumberFormat
  1961. function mergeNumberFormat(locale, format) {
  1962. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  1963. _context.numberFormats = _numberFormats.value;
  1964. clearNumberFormat(_context, locale, format);
  1965. }
  1966. // for debug
  1967. composerID++;
  1968. // watch root locale & fallbackLocale
  1969. if (__root) {
  1970. vue.watch(__root.locale, (val) => {
  1971. if (_inheritLocale) {
  1972. _locale.value = val;
  1973. _context.locale = val;
  1974. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1975. }
  1976. });
  1977. vue.watch(__root.fallbackLocale, (val) => {
  1978. if (_inheritLocale) {
  1979. _fallbackLocale.value = val;
  1980. _context.fallbackLocale = val;
  1981. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1982. }
  1983. });
  1984. }
  1985. // define composition API!
  1986. const composer = {
  1987. id: composerID,
  1988. locale,
  1989. fallbackLocale,
  1990. get inheritLocale() {
  1991. return _inheritLocale;
  1992. },
  1993. set inheritLocale(val) {
  1994. _inheritLocale = val;
  1995. if (val && __root) {
  1996. _locale.value = __root.locale.value;
  1997. _fallbackLocale.value = __root.fallbackLocale.value;
  1998. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1999. }
  2000. },
  2001. get availableLocales() {
  2002. return Object.keys(_messages.value).sort();
  2003. },
  2004. messages,
  2005. datetimeFormats,
  2006. numberFormats,
  2007. get modifiers() {
  2008. return _modifiers;
  2009. },
  2010. get pluralRules() {
  2011. return _pluralRules || {};
  2012. },
  2013. get isGlobal() {
  2014. return _isGlobal;
  2015. },
  2016. get missingWarn() {
  2017. return _missingWarn;
  2018. },
  2019. set missingWarn(val) {
  2020. _missingWarn = val;
  2021. _context.missingWarn = _missingWarn;
  2022. },
  2023. get fallbackWarn() {
  2024. return _fallbackWarn;
  2025. },
  2026. set fallbackWarn(val) {
  2027. _fallbackWarn = val;
  2028. _context.fallbackWarn = _fallbackWarn;
  2029. },
  2030. get fallbackRoot() {
  2031. return _fallbackRoot;
  2032. },
  2033. set fallbackRoot(val) {
  2034. _fallbackRoot = val;
  2035. },
  2036. get fallbackFormat() {
  2037. return _fallbackFormat;
  2038. },
  2039. set fallbackFormat(val) {
  2040. _fallbackFormat = val;
  2041. _context.fallbackFormat = _fallbackFormat;
  2042. },
  2043. get warnHtmlMessage() {
  2044. return _warnHtmlMessage;
  2045. },
  2046. set warnHtmlMessage(val) {
  2047. _warnHtmlMessage = val;
  2048. _context.warnHtmlMessage = val;
  2049. },
  2050. get escapeParameter() {
  2051. return _escapeParameter;
  2052. },
  2053. set escapeParameter(val) {
  2054. _escapeParameter = val;
  2055. _context.escapeParameter = val;
  2056. },
  2057. t,
  2058. rt,
  2059. d,
  2060. n,
  2061. te,
  2062. tm,
  2063. getLocaleMessage,
  2064. setLocaleMessage,
  2065. mergeLocaleMessage,
  2066. getDateTimeFormat,
  2067. setDateTimeFormat,
  2068. mergeDateTimeFormat,
  2069. getNumberFormat,
  2070. setNumberFormat,
  2071. mergeNumberFormat,
  2072. getPostTranslationHandler,
  2073. setPostTranslationHandler,
  2074. getMissingHandler,
  2075. setMissingHandler,
  2076. [TransrateVNodeSymbol]: transrateVNode,
  2077. [NumberPartsSymbol]: numberParts,
  2078. [DatetimePartsSymbol]: datetimeParts,
  2079. [SetPluralRulesSymbol]: setPluralRules,
  2080. [InejctWithOption]: options.__injectWithOption // eslint-disable-line @typescript-eslint/no-explicit-any
  2081. };
  2082. // for vue-devtools timeline event
  2083. {
  2084. composer[EnableEmitter] = (emitter) => {
  2085. _context.__v_emitter = emitter;
  2086. };
  2087. composer[DisableEmitter] = () => {
  2088. _context.__v_emitter = undefined;
  2089. };
  2090. }
  2091. return composer;
  2092. }
  2093. /**
  2094. * Convert to I18n Composer Options from VueI18n Options
  2095. *
  2096. * @internal
  2097. */
  2098. function convertComposerOptions(options) {
  2099. const locale = isString(options.locale) ? options.locale : 'en-US';
  2100. const fallbackLocale = isString(options.fallbackLocale) ||
  2101. isArray(options.fallbackLocale) ||
  2102. isPlainObject(options.fallbackLocale) ||
  2103. options.fallbackLocale === false
  2104. ? options.fallbackLocale
  2105. : locale;
  2106. const missing = isFunction(options.missing) ? options.missing : undefined;
  2107. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  2108. isRegExp(options.silentTranslationWarn)
  2109. ? !options.silentTranslationWarn
  2110. : true;
  2111. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  2112. isRegExp(options.silentFallbackWarn)
  2113. ? !options.silentFallbackWarn
  2114. : true;
  2115. const fallbackRoot = isBoolean(options.fallbackRoot)
  2116. ? options.fallbackRoot
  2117. : true;
  2118. const fallbackFormat = !!options.formatFallbackMessages;
  2119. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  2120. const pluralizationRules = options.pluralizationRules;
  2121. const postTranslation = isFunction(options.postTranslation)
  2122. ? options.postTranslation
  2123. : undefined;
  2124. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  2125. ? options.warnHtmlInMessage !== 'off'
  2126. : true;
  2127. const escapeParameter = !!options.escapeParameterHtml;
  2128. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  2129. if (options.formatter) {
  2130. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2131. }
  2132. if (options.preserveDirectiveContent) {
  2133. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2134. }
  2135. let messages = options.messages;
  2136. if (isPlainObject(options.sharedMessages)) {
  2137. const sharedMessages = options.sharedMessages;
  2138. const locales = Object.keys(sharedMessages);
  2139. messages = locales.reduce((messages, locale) => {
  2140. const message = messages[locale] || (messages[locale] = {});
  2141. assign(message, sharedMessages[locale]);
  2142. return messages;
  2143. }, (messages || {}));
  2144. }
  2145. const { __i18n, __root, __injectWithOption } = options;
  2146. const datetimeFormats = options.datetimeFormats;
  2147. const numberFormats = options.numberFormats;
  2148. const flatJson = options.flatJson;
  2149. return {
  2150. locale,
  2151. fallbackLocale,
  2152. messages,
  2153. flatJson,
  2154. datetimeFormats,
  2155. numberFormats,
  2156. missing,
  2157. missingWarn,
  2158. fallbackWarn,
  2159. fallbackRoot,
  2160. fallbackFormat,
  2161. modifiers,
  2162. pluralRules: pluralizationRules,
  2163. postTranslation,
  2164. warnHtmlMessage,
  2165. escapeParameter,
  2166. inheritLocale,
  2167. __i18n,
  2168. __root,
  2169. __injectWithOption
  2170. };
  2171. }
  2172. /**
  2173. * create VueI18n interface factory
  2174. *
  2175. * @internal
  2176. */
  2177. function createVueI18n(options = {}) {
  2178. const composer = createComposer(convertComposerOptions(options));
  2179. // defines VueI18n
  2180. const vueI18n = {
  2181. // id
  2182. id: composer.id,
  2183. // locale
  2184. get locale() {
  2185. return composer.locale.value;
  2186. },
  2187. set locale(val) {
  2188. composer.locale.value = val;
  2189. },
  2190. // fallbackLocale
  2191. get fallbackLocale() {
  2192. return composer.fallbackLocale.value;
  2193. },
  2194. set fallbackLocale(val) {
  2195. composer.fallbackLocale.value = val;
  2196. },
  2197. // messages
  2198. get messages() {
  2199. return composer.messages.value;
  2200. },
  2201. // datetimeFormats
  2202. get datetimeFormats() {
  2203. return composer.datetimeFormats.value;
  2204. },
  2205. // numberFormats
  2206. get numberFormats() {
  2207. return composer.numberFormats.value;
  2208. },
  2209. // availableLocales
  2210. get availableLocales() {
  2211. return composer.availableLocales;
  2212. },
  2213. // formatter
  2214. get formatter() {
  2215. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2216. // dummy
  2217. return {
  2218. interpolate() {
  2219. return [];
  2220. }
  2221. };
  2222. },
  2223. set formatter(val) {
  2224. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2225. },
  2226. // missing
  2227. get missing() {
  2228. return composer.getMissingHandler();
  2229. },
  2230. set missing(handler) {
  2231. composer.setMissingHandler(handler);
  2232. },
  2233. // silentTranslationWarn
  2234. get silentTranslationWarn() {
  2235. return isBoolean(composer.missingWarn)
  2236. ? !composer.missingWarn
  2237. : composer.missingWarn;
  2238. },
  2239. set silentTranslationWarn(val) {
  2240. composer.missingWarn = isBoolean(val) ? !val : val;
  2241. },
  2242. // silentFallbackWarn
  2243. get silentFallbackWarn() {
  2244. return isBoolean(composer.fallbackWarn)
  2245. ? !composer.fallbackWarn
  2246. : composer.fallbackWarn;
  2247. },
  2248. set silentFallbackWarn(val) {
  2249. composer.fallbackWarn = isBoolean(val) ? !val : val;
  2250. },
  2251. // modifiers
  2252. get modifiers() {
  2253. return composer.modifiers;
  2254. },
  2255. // formatFallbackMessages
  2256. get formatFallbackMessages() {
  2257. return composer.fallbackFormat;
  2258. },
  2259. set formatFallbackMessages(val) {
  2260. composer.fallbackFormat = val;
  2261. },
  2262. // postTranslation
  2263. get postTranslation() {
  2264. return composer.getPostTranslationHandler();
  2265. },
  2266. set postTranslation(handler) {
  2267. composer.setPostTranslationHandler(handler);
  2268. },
  2269. // sync
  2270. get sync() {
  2271. return composer.inheritLocale;
  2272. },
  2273. set sync(val) {
  2274. composer.inheritLocale = val;
  2275. },
  2276. // warnInHtmlMessage
  2277. get warnHtmlInMessage() {
  2278. return composer.warnHtmlMessage ? 'warn' : 'off';
  2279. },
  2280. set warnHtmlInMessage(val) {
  2281. composer.warnHtmlMessage = val !== 'off';
  2282. },
  2283. // escapeParameterHtml
  2284. get escapeParameterHtml() {
  2285. return composer.escapeParameter;
  2286. },
  2287. set escapeParameterHtml(val) {
  2288. composer.escapeParameter = val;
  2289. },
  2290. // preserveDirectiveContent
  2291. get preserveDirectiveContent() {
  2292. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2293. return true;
  2294. },
  2295. set preserveDirectiveContent(val) {
  2296. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2297. },
  2298. // pluralizationRules
  2299. get pluralizationRules() {
  2300. return composer.pluralRules || {};
  2301. },
  2302. // for internal
  2303. __composer: composer,
  2304. // t
  2305. t(...args) {
  2306. const [arg1, arg2, arg3] = args;
  2307. const options = {};
  2308. let list = null;
  2309. let named = null;
  2310. if (!isString(arg1)) {
  2311. throw createI18nError(15 /* INVALID_ARGUMENT */);
  2312. }
  2313. const key = arg1;
  2314. if (isString(arg2)) {
  2315. options.locale = arg2;
  2316. }
  2317. else if (isArray(arg2)) {
  2318. list = arg2;
  2319. }
  2320. else if (isPlainObject(arg2)) {
  2321. named = arg2;
  2322. }
  2323. if (isArray(arg3)) {
  2324. list = arg3;
  2325. }
  2326. else if (isPlainObject(arg3)) {
  2327. named = arg3;
  2328. }
  2329. return composer.t(key, list || named || {}, options);
  2330. },
  2331. rt(...args) {
  2332. return composer.rt(...args);
  2333. },
  2334. // tc
  2335. tc(...args) {
  2336. const [arg1, arg2, arg3] = args;
  2337. const options = { plural: 1 };
  2338. let list = null;
  2339. let named = null;
  2340. if (!isString(arg1)) {
  2341. throw createI18nError(15 /* INVALID_ARGUMENT */);
  2342. }
  2343. const key = arg1;
  2344. if (isString(arg2)) {
  2345. options.locale = arg2;
  2346. }
  2347. else if (isNumber(arg2)) {
  2348. options.plural = arg2;
  2349. }
  2350. else if (isArray(arg2)) {
  2351. list = arg2;
  2352. }
  2353. else if (isPlainObject(arg2)) {
  2354. named = arg2;
  2355. }
  2356. if (isString(arg3)) {
  2357. options.locale = arg3;
  2358. }
  2359. else if (isArray(arg3)) {
  2360. list = arg3;
  2361. }
  2362. else if (isPlainObject(arg3)) {
  2363. named = arg3;
  2364. }
  2365. return composer.t(key, list || named || {}, options);
  2366. },
  2367. // te
  2368. te(key, locale) {
  2369. return composer.te(key, locale);
  2370. },
  2371. // tm
  2372. tm(key) {
  2373. return composer.tm(key);
  2374. },
  2375. // getLocaleMessage
  2376. getLocaleMessage(locale) {
  2377. return composer.getLocaleMessage(locale);
  2378. },
  2379. // setLocaleMessage
  2380. setLocaleMessage(locale, message) {
  2381. composer.setLocaleMessage(locale, message);
  2382. },
  2383. // mergeLocaleMessage
  2384. mergeLocaleMessage(locale, message) {
  2385. composer.mergeLocaleMessage(locale, message);
  2386. },
  2387. // d
  2388. d(...args) {
  2389. return composer.d(...args);
  2390. },
  2391. // getDateTimeFormat
  2392. getDateTimeFormat(locale) {
  2393. return composer.getDateTimeFormat(locale);
  2394. },
  2395. // setDateTimeFormat
  2396. setDateTimeFormat(locale, format) {
  2397. composer.setDateTimeFormat(locale, format);
  2398. },
  2399. // mergeDateTimeFormat
  2400. mergeDateTimeFormat(locale, format) {
  2401. composer.mergeDateTimeFormat(locale, format);
  2402. },
  2403. // n
  2404. n(...args) {
  2405. return composer.n(...args);
  2406. },
  2407. // getNumberFormat
  2408. getNumberFormat(locale) {
  2409. return composer.getNumberFormat(locale);
  2410. },
  2411. // setNumberFormat
  2412. setNumberFormat(locale, format) {
  2413. composer.setNumberFormat(locale, format);
  2414. },
  2415. // mergeNumberFormat
  2416. mergeNumberFormat(locale, format) {
  2417. composer.mergeNumberFormat(locale, format);
  2418. },
  2419. // getChoiceIndex
  2420. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  2421. getChoiceIndex(choice, choicesLength) {
  2422. warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
  2423. return -1;
  2424. },
  2425. // for internal
  2426. __onComponentInstanceCreated(target) {
  2427. const { componentInstanceCreatedListener } = options;
  2428. if (componentInstanceCreatedListener) {
  2429. componentInstanceCreatedListener(target, vueI18n);
  2430. }
  2431. }
  2432. };
  2433. // for vue-devtools timeline event
  2434. {
  2435. vueI18n.__enableEmitter = (emitter) => {
  2436. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2437. const __composer = composer;
  2438. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  2439. };
  2440. vueI18n.__disableEmitter = () => {
  2441. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2442. const __composer = composer;
  2443. __composer[DisableEmitter] && __composer[DisableEmitter]();
  2444. };
  2445. }
  2446. return vueI18n;
  2447. }
  2448. const baseFormatProps = {
  2449. tag: {
  2450. type: [String, Object]
  2451. },
  2452. locale: {
  2453. type: String
  2454. },
  2455. scope: {
  2456. type: String,
  2457. validator: (val) => val === 'parent' || val === 'global',
  2458. default: 'parent'
  2459. },
  2460. i18n: {
  2461. type: Object
  2462. }
  2463. };
  2464. /**
  2465. * Translation Component
  2466. *
  2467. * @remarks
  2468. * See the following items for property about details
  2469. *
  2470. * @VueI18nSee [TranslationProps](component#translationprops)
  2471. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2472. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  2473. *
  2474. * @example
  2475. * ```html
  2476. * <div id="app">
  2477. * <!-- ... -->
  2478. * <i18n path="term" tag="label" for="tos">
  2479. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  2480. * </i18n>
  2481. * <!-- ... -->
  2482. * </div>
  2483. * ```
  2484. * ```js
  2485. * import { createApp } from 'vue'
  2486. * import { createI18n } from 'vue-i18n'
  2487. *
  2488. * const messages = {
  2489. * en: {
  2490. * tos: 'Term of Service',
  2491. * term: 'I accept xxx {0}.'
  2492. * },
  2493. * ja: {
  2494. * tos: '利用規約',
  2495. * term: '私は xxx の{0}に同意します。'
  2496. * }
  2497. * }
  2498. *
  2499. * const i18n = createI18n({
  2500. * locale: 'en',
  2501. * messages
  2502. * })
  2503. *
  2504. * const app = createApp({
  2505. * data: {
  2506. * url: '/term'
  2507. * }
  2508. * }).use(i18n).mount('#app')
  2509. * ```
  2510. *
  2511. * @VueI18nComponent
  2512. */
  2513. const Translation = {
  2514. /* eslint-disable */
  2515. name: 'i18n-t',
  2516. props: assign({
  2517. keypath: {
  2518. type: String,
  2519. required: true
  2520. },
  2521. plural: {
  2522. type: [Number, String],
  2523. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2524. validator: (val) => isNumber(val) || !isNaN(val)
  2525. }
  2526. }, baseFormatProps),
  2527. /* eslint-enable */
  2528. setup(props, context) {
  2529. const { slots, attrs } = context;
  2530. const i18n = props.i18n ||
  2531. useI18n({
  2532. useScope: props.scope,
  2533. __useComponent: true
  2534. });
  2535. const keys = Object.keys(slots).filter(key => key !== '_');
  2536. return () => {
  2537. const options = {};
  2538. if (props.locale) {
  2539. options.locale = props.locale;
  2540. }
  2541. if (props.plural !== undefined) {
  2542. options.plural = isString(props.plural) ? +props.plural : props.plural;
  2543. }
  2544. const arg = getInterpolateArg(context, keys);
  2545. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2546. const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
  2547. const assignedAttrs = assign({}, attrs);
  2548. // prettier-ignore
  2549. return isString(props.tag)
  2550. ? vue.h(props.tag, assignedAttrs, children)
  2551. : isObject(props.tag)
  2552. ? vue.h(props.tag, assignedAttrs, children)
  2553. : vue.h(vue.Fragment, assignedAttrs, children);
  2554. };
  2555. }
  2556. };
  2557. function getInterpolateArg({ slots }, keys) {
  2558. if (keys.length === 1 && keys[0] === 'default') {
  2559. // default slot only
  2560. return slots.default ? slots.default() : [];
  2561. }
  2562. else {
  2563. // named slots
  2564. return keys.reduce((arg, key) => {
  2565. const slot = slots[key];
  2566. if (slot) {
  2567. arg[key] = slot();
  2568. }
  2569. return arg;
  2570. }, {});
  2571. }
  2572. }
  2573. function renderFormatter(props, context, slotKeys, partFormatter) {
  2574. const { slots, attrs } = context;
  2575. return () => {
  2576. const options = { part: true };
  2577. let overrides = {};
  2578. if (props.locale) {
  2579. options.locale = props.locale;
  2580. }
  2581. if (isString(props.format)) {
  2582. options.key = props.format;
  2583. }
  2584. else if (isObject(props.format)) {
  2585. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2586. if (isString(props.format.key)) {
  2587. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2588. options.key = props.format.key;
  2589. }
  2590. // Filter out number format options only
  2591. overrides = Object.keys(props.format).reduce((options, prop) => {
  2592. return slotKeys.includes(prop)
  2593. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  2594. : options;
  2595. }, {});
  2596. }
  2597. const parts = partFormatter(...[props.value, options, overrides]);
  2598. let children = [options.key];
  2599. if (isArray(parts)) {
  2600. children = parts.map((part, index) => {
  2601. const slot = slots[part.type];
  2602. return slot
  2603. ? slot({ [part.type]: part.value, index, parts })
  2604. : [part.value];
  2605. });
  2606. }
  2607. else if (isString(parts)) {
  2608. children = [parts];
  2609. }
  2610. const assignedAttrs = assign({}, attrs);
  2611. // prettier-ignore
  2612. return isString(props.tag)
  2613. ? vue.h(props.tag, assignedAttrs, children)
  2614. : isObject(props.tag)
  2615. ? vue.h(props.tag, assignedAttrs, children)
  2616. : vue.h(vue.Fragment, assignedAttrs, children);
  2617. };
  2618. }
  2619. const NUMBER_FORMAT_KEYS = [
  2620. 'localeMatcher',
  2621. 'style',
  2622. 'unit',
  2623. 'unitDisplay',
  2624. 'currency',
  2625. 'currencyDisplay',
  2626. 'useGrouping',
  2627. 'numberingSystem',
  2628. 'minimumIntegerDigits',
  2629. 'minimumFractionDigits',
  2630. 'maximumFractionDigits',
  2631. 'minimumSignificantDigits',
  2632. 'maximumSignificantDigits',
  2633. 'notation',
  2634. 'formatMatcher'
  2635. ];
  2636. /**
  2637. * Number Format Component
  2638. *
  2639. * @remarks
  2640. * See the following items for property about details
  2641. *
  2642. * @VueI18nSee [FormattableProps](component#formattableprops)
  2643. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2644. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  2645. *
  2646. * @VueI18nDanger
  2647. * 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)
  2648. *
  2649. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  2650. *
  2651. * @VueI18nComponent
  2652. */
  2653. const NumberFormat = {
  2654. /* eslint-disable */
  2655. name: 'i18n-n',
  2656. props: assign({
  2657. value: {
  2658. type: Number,
  2659. required: true
  2660. },
  2661. format: {
  2662. type: [String, Object]
  2663. }
  2664. }, baseFormatProps),
  2665. /* eslint-enable */
  2666. setup(props, context) {
  2667. const i18n = props.i18n ||
  2668. useI18n({ useScope: 'parent', __useComponent: true });
  2669. return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
  2670. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2671. i18n[NumberPartsSymbol](...args));
  2672. }
  2673. };
  2674. const DATETIME_FORMAT_KEYS = [
  2675. 'dateStyle',
  2676. 'timeStyle',
  2677. 'fractionalSecondDigits',
  2678. 'calendar',
  2679. 'dayPeriod',
  2680. 'numberingSystem',
  2681. 'localeMatcher',
  2682. 'timeZone',
  2683. 'hour12',
  2684. 'hourCycle',
  2685. 'formatMatcher',
  2686. 'weekday',
  2687. 'era',
  2688. 'year',
  2689. 'month',
  2690. 'day',
  2691. 'hour',
  2692. 'minute',
  2693. 'second',
  2694. 'timeZoneName'
  2695. ];
  2696. /**
  2697. * Datetime Format Component
  2698. *
  2699. * @remarks
  2700. * See the following items for property about details
  2701. *
  2702. * @VueI18nSee [FormattableProps](component#formattableprops)
  2703. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2704. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  2705. *
  2706. * @VueI18nDanger
  2707. * 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)
  2708. *
  2709. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  2710. *
  2711. * @VueI18nComponent
  2712. */
  2713. const DatetimeFormat = {
  2714. /* eslint-disable */
  2715. name: 'i18n-d',
  2716. props: assign({
  2717. value: {
  2718. type: [Number, Date],
  2719. required: true
  2720. },
  2721. format: {
  2722. type: [String, Object]
  2723. }
  2724. }, baseFormatProps),
  2725. /* eslint-enable */
  2726. setup(props, context) {
  2727. const i18n = props.i18n ||
  2728. useI18n({ useScope: 'parent', __useComponent: true });
  2729. return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
  2730. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2731. i18n[DatetimePartsSymbol](...args));
  2732. }
  2733. };
  2734. function getComposer$2(i18n, instance) {
  2735. const i18nInternal = i18n;
  2736. if (i18n.mode === 'composition') {
  2737. return (i18nInternal.__getInstance(instance) || i18n.global);
  2738. }
  2739. else {
  2740. const vueI18n = i18nInternal.__getInstance(instance);
  2741. return vueI18n != null
  2742. ? vueI18n.__composer
  2743. : i18n.global.__composer;
  2744. }
  2745. }
  2746. function vTDirective(i18n) {
  2747. const bind = (el, { instance, value, modifiers }) => {
  2748. /* istanbul ignore if */
  2749. if (!instance || !instance.$) {
  2750. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  2751. }
  2752. const composer = getComposer$2(i18n, instance.$);
  2753. if (modifiers.preserve) {
  2754. warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
  2755. }
  2756. const parsedValue = parseValue(value);
  2757. el.textContent = composer.t(...makeParams(parsedValue));
  2758. };
  2759. return {
  2760. beforeMount: bind,
  2761. beforeUpdate: bind
  2762. };
  2763. }
  2764. function parseValue(value) {
  2765. if (isString(value)) {
  2766. return { path: value };
  2767. }
  2768. else if (isPlainObject(value)) {
  2769. if (!('path' in value)) {
  2770. throw createI18nError(19 /* REQUIRED_VALUE */, 'path');
  2771. }
  2772. return value;
  2773. }
  2774. else {
  2775. throw createI18nError(20 /* INVALID_VALUE */);
  2776. }
  2777. }
  2778. function makeParams(value) {
  2779. const { path, locale, args, choice, plural } = value;
  2780. const options = {};
  2781. const named = args || {};
  2782. if (isString(locale)) {
  2783. options.locale = locale;
  2784. }
  2785. if (isNumber(choice)) {
  2786. options.plural = choice;
  2787. }
  2788. if (isNumber(plural)) {
  2789. options.plural = plural;
  2790. }
  2791. return [path, named, options];
  2792. }
  2793. function apply(app, i18n, ...options) {
  2794. const pluginOptions = isPlainObject(options[0])
  2795. ? options[0]
  2796. : {};
  2797. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  2798. const globalInstall = isBoolean(pluginOptions.globalInstall)
  2799. ? pluginOptions.globalInstall
  2800. : true;
  2801. if (globalInstall && useI18nComponentName) {
  2802. warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
  2803. name: Translation.name
  2804. }));
  2805. }
  2806. if (globalInstall) {
  2807. // install components
  2808. app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
  2809. app.component(NumberFormat.name, NumberFormat);
  2810. app.component(DatetimeFormat.name, DatetimeFormat);
  2811. }
  2812. // install directive
  2813. app.directive('t', vTDirective(i18n));
  2814. }
  2815. var global$1 = (typeof global !== "undefined" ? global :
  2816. typeof self !== "undefined" ? self :
  2817. typeof window !== "undefined" ? window : {});
  2818. function getDevtoolsGlobalHook() {
  2819. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  2820. }
  2821. function getTarget() {
  2822. // @ts-ignore
  2823. return typeof navigator !== 'undefined'
  2824. ? window
  2825. : typeof global$1 !== 'undefined'
  2826. ? global$1
  2827. : {};
  2828. }
  2829. const HOOK_SETUP = 'devtools-plugin:setup';
  2830. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  2831. const hook = getDevtoolsGlobalHook();
  2832. if (hook) {
  2833. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  2834. }
  2835. else {
  2836. const target = getTarget();
  2837. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  2838. list.push({
  2839. pluginDescriptor,
  2840. setupFn
  2841. });
  2842. }
  2843. }
  2844. const VueDevToolsLabels = {
  2845. ["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
  2846. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
  2847. ["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
  2848. };
  2849. const VueDevToolsPlaceholders = {
  2850. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  2851. };
  2852. const VueDevToolsTimelineColors = {
  2853. ["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
  2854. };
  2855. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  2856. let devtoolsApi;
  2857. async function enableDevTools(app, i18n) {
  2858. return new Promise((resolve, reject) => {
  2859. try {
  2860. setupDevtoolsPlugin({
  2861. id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
  2862. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
  2863. packageName: 'vue-i18n',
  2864. homepage: 'https://vue-i18n.intlify.dev',
  2865. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  2866. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  2867. app
  2868. }, api => {
  2869. devtoolsApi = api;
  2870. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  2871. updateComponentTreeTags(componentInstance, treeNode, i18n);
  2872. });
  2873. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  2874. if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) {
  2875. if (i18n.mode === 'legacy') {
  2876. // ignore global scope on legacy mode
  2877. if (componentInstance.vnode.el.__VUE_I18N__ !==
  2878. i18n.global.__composer) {
  2879. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  2880. }
  2881. }
  2882. else {
  2883. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  2884. }
  2885. }
  2886. });
  2887. api.addInspector({
  2888. id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
  2889. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
  2890. icon: 'language',
  2891. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
  2892. });
  2893. api.on.getInspectorTree(payload => {
  2894. if (payload.app === app &&
  2895. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2896. registerScope(payload, i18n);
  2897. }
  2898. });
  2899. api.on.getInspectorState(payload => {
  2900. if (payload.app === app &&
  2901. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2902. inspectScope(payload, i18n);
  2903. }
  2904. });
  2905. api.on.editInspectorState(payload => {
  2906. if (payload.app === app &&
  2907. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2908. editScope(payload, i18n);
  2909. }
  2910. });
  2911. api.addTimelineLayer({
  2912. id: "vue-i18n-timeline" /* TIMELINE */,
  2913. label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
  2914. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
  2915. });
  2916. resolve(true);
  2917. });
  2918. }
  2919. catch (e) {
  2920. console.error(e);
  2921. reject(false);
  2922. }
  2923. });
  2924. }
  2925. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  2926. treeNode, i18n) {
  2927. // prettier-ignore
  2928. const global = i18n.mode === 'composition'
  2929. ? i18n.global
  2930. : i18n.global.__composer;
  2931. if (instance && instance.vnode.el.__VUE_I18N__) {
  2932. // add custom tags local scope only
  2933. if (instance.vnode.el.__VUE_I18N__ !== global) {
  2934. const label = instance.type.name || instance.type.displayName || instance.type.__file;
  2935. const tag = {
  2936. label: `i18n (${label} Scope)`,
  2937. textColor: 0x000000,
  2938. backgroundColor: 0xffcd19
  2939. };
  2940. treeNode.tags.push(tag);
  2941. }
  2942. }
  2943. }
  2944. function inspectComposer(instanceData, composer) {
  2945. const type = VUE_I18N_COMPONENT_TYPES;
  2946. instanceData.state.push({
  2947. type,
  2948. key: 'locale',
  2949. editable: true,
  2950. value: composer.locale.value
  2951. });
  2952. instanceData.state.push({
  2953. type,
  2954. key: 'availableLocales',
  2955. editable: false,
  2956. value: composer.availableLocales
  2957. });
  2958. instanceData.state.push({
  2959. type,
  2960. key: 'fallbackLocale',
  2961. editable: true,
  2962. value: composer.fallbackLocale.value
  2963. });
  2964. instanceData.state.push({
  2965. type,
  2966. key: 'inheritLocale',
  2967. editable: true,
  2968. value: composer.inheritLocale
  2969. });
  2970. instanceData.state.push({
  2971. type,
  2972. key: 'messages',
  2973. editable: false,
  2974. value: getLocaleMessageValue(composer.messages.value)
  2975. });
  2976. instanceData.state.push({
  2977. type,
  2978. key: 'datetimeFormats',
  2979. editable: false,
  2980. value: composer.datetimeFormats.value
  2981. });
  2982. instanceData.state.push({
  2983. type,
  2984. key: 'numberFormats',
  2985. editable: false,
  2986. value: composer.numberFormats.value
  2987. });
  2988. }
  2989. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2990. function getLocaleMessageValue(messages) {
  2991. const value = {};
  2992. Object.keys(messages).forEach((key) => {
  2993. const v = messages[key];
  2994. if (isFunction(v) && 'source' in v) {
  2995. value[key] = getMessageFunctionDetails(v);
  2996. }
  2997. else if (isObject(v)) {
  2998. value[key] = getLocaleMessageValue(v);
  2999. }
  3000. else {
  3001. value[key] = v;
  3002. }
  3003. });
  3004. return value;
  3005. }
  3006. const ESC = {
  3007. '<': '&lt;',
  3008. '>': '&gt;',
  3009. '"': '&quot;',
  3010. '&': '&amp;'
  3011. };
  3012. function escape(s) {
  3013. return s.replace(/[<>"&]/g, escapeChar);
  3014. }
  3015. function escapeChar(a) {
  3016. return ESC[a] || a;
  3017. }
  3018. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3019. function getMessageFunctionDetails(func) {
  3020. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  3021. return {
  3022. _custom: {
  3023. type: 'function',
  3024. display: `<span>ƒ</span> ${argString}`
  3025. }
  3026. };
  3027. }
  3028. function registerScope(payload, i18n) {
  3029. payload.rootNodes.push({
  3030. id: 'global',
  3031. label: 'Global Scope'
  3032. });
  3033. // prettier-ignore
  3034. const global = i18n.mode === 'composition'
  3035. ? i18n.global
  3036. : i18n.global.__composer;
  3037. for (const [keyInstance, instance] of i18n.__instances) {
  3038. // prettier-ignore
  3039. const composer = i18n.mode === 'composition'
  3040. ? instance
  3041. : instance.__composer;
  3042. if (global === composer) {
  3043. continue;
  3044. }
  3045. const label = keyInstance.type.name ||
  3046. keyInstance.type.displayName ||
  3047. keyInstance.type.__file;
  3048. payload.rootNodes.push({
  3049. id: composer.id.toString(),
  3050. label: `${label} Scope`
  3051. });
  3052. }
  3053. }
  3054. function getComposer$1(nodeId, i18n) {
  3055. if (nodeId === 'global') {
  3056. return i18n.mode === 'composition'
  3057. ? i18n.global
  3058. : i18n.global.__composer;
  3059. }
  3060. else {
  3061. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  3062. if (instance) {
  3063. return i18n.mode === 'composition'
  3064. ? instance
  3065. : instance.__composer;
  3066. }
  3067. else {
  3068. return null;
  3069. }
  3070. }
  3071. }
  3072. function inspectScope(payload, i18n) {
  3073. const composer = getComposer$1(payload.nodeId, i18n);
  3074. if (composer) {
  3075. payload.state = makeScopeInspectState(composer);
  3076. }
  3077. }
  3078. function makeScopeInspectState(composer) {
  3079. const state = {};
  3080. const localeType = 'Locale related info';
  3081. const localeStates = [
  3082. {
  3083. type: localeType,
  3084. key: 'locale',
  3085. editable: true,
  3086. value: composer.locale.value
  3087. },
  3088. {
  3089. type: localeType,
  3090. key: 'fallbackLocale',
  3091. editable: true,
  3092. value: composer.fallbackLocale.value
  3093. },
  3094. {
  3095. type: localeType,
  3096. key: 'availableLocales',
  3097. editable: false,
  3098. value: composer.availableLocales
  3099. },
  3100. {
  3101. type: localeType,
  3102. key: 'inheritLocale',
  3103. editable: true,
  3104. value: composer.inheritLocale
  3105. }
  3106. ];
  3107. state[localeType] = localeStates;
  3108. const localeMessagesType = 'Locale messages info';
  3109. const localeMessagesStates = [
  3110. {
  3111. type: localeMessagesType,
  3112. key: 'messages',
  3113. editable: false,
  3114. value: getLocaleMessageValue(composer.messages.value)
  3115. }
  3116. ];
  3117. state[localeMessagesType] = localeMessagesStates;
  3118. const datetimeFormatsType = 'Datetime formats info';
  3119. const datetimeFormatsStates = [
  3120. {
  3121. type: datetimeFormatsType,
  3122. key: 'datetimeFormats',
  3123. editable: false,
  3124. value: composer.datetimeFormats.value
  3125. }
  3126. ];
  3127. state[datetimeFormatsType] = datetimeFormatsStates;
  3128. const numberFormatsType = 'Datetime formats info';
  3129. const numberFormatsStates = [
  3130. {
  3131. type: numberFormatsType,
  3132. key: 'numberFormats',
  3133. editable: false,
  3134. value: composer.numberFormats.value
  3135. }
  3136. ];
  3137. state[numberFormatsType] = numberFormatsStates;
  3138. return state;
  3139. }
  3140. function addTimelineEvent(event, payload) {
  3141. if (devtoolsApi) {
  3142. let groupId;
  3143. if (payload && 'groupId' in payload) {
  3144. groupId = payload.groupId;
  3145. delete payload.groupId;
  3146. }
  3147. devtoolsApi.addTimelineEvent({
  3148. layerId: "vue-i18n-timeline" /* TIMELINE */,
  3149. event: {
  3150. title: event,
  3151. groupId,
  3152. time: Date.now(),
  3153. meta: {},
  3154. data: payload || {},
  3155. logType: event === "compile-error" /* COMPILE_ERROR */
  3156. ? 'error'
  3157. : event === "fallback" /* FALBACK */ ||
  3158. event === "missing" /* MISSING */
  3159. ? 'warning'
  3160. : 'default'
  3161. }
  3162. });
  3163. }
  3164. }
  3165. function editScope(payload, i18n) {
  3166. const composer = getComposer$1(payload.nodeId, i18n);
  3167. if (composer) {
  3168. const [field] = payload.path;
  3169. if (field === 'locale' && isString(payload.state.value)) {
  3170. composer.locale.value = payload.state.value;
  3171. }
  3172. else if (field === 'fallbackLocale' &&
  3173. (isString(payload.state.value) ||
  3174. isArray(payload.state.value) ||
  3175. isObject(payload.state.value))) {
  3176. composer.fallbackLocale.value = payload.state.value;
  3177. }
  3178. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  3179. composer.inheritLocale = payload.state.value;
  3180. }
  3181. }
  3182. }
  3183. // supports compatibility for legacy vue-i18n APIs
  3184. function defineMixin(vuei18n, composer, i18n) {
  3185. return {
  3186. beforeCreate() {
  3187. const instance = vue.getCurrentInstance();
  3188. /* istanbul ignore if */
  3189. if (!instance) {
  3190. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3191. }
  3192. const options = this.$options;
  3193. if (options.i18n) {
  3194. const optionsI18n = options.i18n;
  3195. if (options.__i18n) {
  3196. optionsI18n.__i18n = options.__i18n;
  3197. }
  3198. optionsI18n.__root = composer;
  3199. if (this === this.$root) {
  3200. this.$i18n = mergeToRoot(vuei18n, optionsI18n);
  3201. }
  3202. else {
  3203. optionsI18n.__injectWithOption = true;
  3204. this.$i18n = createVueI18n(optionsI18n);
  3205. }
  3206. }
  3207. else if (options.__i18n) {
  3208. if (this === this.$root) {
  3209. this.$i18n = mergeToRoot(vuei18n, options);
  3210. }
  3211. else {
  3212. this.$i18n = createVueI18n({
  3213. __i18n: options.__i18n,
  3214. __injectWithOption: true,
  3215. __root: composer
  3216. });
  3217. }
  3218. }
  3219. else {
  3220. // set global
  3221. this.$i18n = vuei18n;
  3222. }
  3223. vuei18n.__onComponentInstanceCreated(this.$i18n);
  3224. i18n.__setInstance(instance, this.$i18n);
  3225. // defines vue-i18n legacy APIs
  3226. this.$t = (...args) => this.$i18n.t(...args);
  3227. this.$rt = (...args) => this.$i18n.rt(...args);
  3228. this.$tc = (...args) => this.$i18n.tc(...args);
  3229. this.$te = (key, locale) => this.$i18n.te(key, locale);
  3230. this.$d = (...args) => this.$i18n.d(...args);
  3231. this.$n = (...args) => this.$i18n.n(...args);
  3232. this.$tm = (key) => this.$i18n.tm(key);
  3233. },
  3234. mounted() {
  3235. /* istanbul ignore if */
  3236. {
  3237. this.$el.__VUE_I18N__ = this.$i18n.__composer;
  3238. const emitter = (this.__v_emitter = createEmitter());
  3239. const _vueI18n = this.$i18n;
  3240. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  3241. emitter.on('*', addTimelineEvent);
  3242. }
  3243. },
  3244. beforeUnmount() {
  3245. const instance = vue.getCurrentInstance();
  3246. /* istanbul ignore if */
  3247. if (!instance) {
  3248. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3249. }
  3250. /* istanbul ignore if */
  3251. {
  3252. if (this.__v_emitter) {
  3253. this.__v_emitter.off('*', addTimelineEvent);
  3254. delete this.__v_emitter;
  3255. }
  3256. const _vueI18n = this.$i18n;
  3257. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  3258. delete this.$el.__VUE_I18N__;
  3259. }
  3260. delete this.$t;
  3261. delete this.$rt;
  3262. delete this.$tc;
  3263. delete this.$te;
  3264. delete this.$d;
  3265. delete this.$n;
  3266. delete this.$tm;
  3267. i18n.__deleteInstance(instance);
  3268. delete this.$i18n;
  3269. }
  3270. };
  3271. }
  3272. function mergeToRoot(root, options) {
  3273. root.locale = options.locale || root.locale;
  3274. root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
  3275. root.missing = options.missing || root.missing;
  3276. root.silentTranslationWarn =
  3277. options.silentTranslationWarn || root.silentFallbackWarn;
  3278. root.silentFallbackWarn =
  3279. options.silentFallbackWarn || root.silentFallbackWarn;
  3280. root.formatFallbackMessages =
  3281. options.formatFallbackMessages || root.formatFallbackMessages;
  3282. root.postTranslation = options.postTranslation || root.postTranslation;
  3283. root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
  3284. root.escapeParameterHtml =
  3285. options.escapeParameterHtml || root.escapeParameterHtml;
  3286. root.sync = options.sync || root.sync;
  3287. root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
  3288. const messages = getLocaleMessages(root.locale, {
  3289. messages: options.messages,
  3290. __i18n: options.__i18n
  3291. });
  3292. Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
  3293. if (options.datetimeFormats) {
  3294. Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  3295. }
  3296. if (options.numberFormats) {
  3297. Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
  3298. }
  3299. return root;
  3300. }
  3301. /**
  3302. * Vue I18n factory
  3303. *
  3304. * @param options - An options, see the {@link I18nOptions}
  3305. *
  3306. * @returns {@link I18n} instance
  3307. *
  3308. * @remarks
  3309. * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
  3310. *
  3311. * If you use composition API mode, you need to specify {@link ComposerOptions}.
  3312. *
  3313. * @VueI18nSee [Getting Started](../guide/)
  3314. * @VueI18nSee [Composition API](../guide/advanced/composition)
  3315. *
  3316. * @example
  3317. * case: for Legacy API
  3318. * ```js
  3319. * import { createApp } from 'vue'
  3320. * import { createI18n } from 'vue-i18n'
  3321. *
  3322. * // call with I18n option
  3323. * const i18n = createI18n({
  3324. * locale: 'ja',
  3325. * messages: {
  3326. * en: { ... },
  3327. * ja: { ... }
  3328. * }
  3329. * })
  3330. *
  3331. * const App = {
  3332. * // ...
  3333. * }
  3334. *
  3335. * const app = createApp(App)
  3336. *
  3337. * // install!
  3338. * app.use(i18n)
  3339. * app.mount('#app')
  3340. * ```
  3341. *
  3342. * @example
  3343. * case: for composition API
  3344. * ```js
  3345. * import { createApp } from 'vue'
  3346. * import { createI18n, useI18n } from 'vue-i18n'
  3347. *
  3348. * // call with I18n option
  3349. * const i18n = createI18n({
  3350. * legacy: false, // you must specify 'legacy: false' option
  3351. * locale: 'ja',
  3352. * messages: {
  3353. * en: { ... },
  3354. * ja: { ... }
  3355. * }
  3356. * })
  3357. *
  3358. * const App = {
  3359. * setup() {
  3360. * // ...
  3361. * const { t } = useI18n({ ... })
  3362. * return { ... , t }
  3363. * }
  3364. * }
  3365. *
  3366. * const app = createApp(App)
  3367. *
  3368. * // install!
  3369. * app.use(i18n)
  3370. * app.mount('#app')
  3371. * ```
  3372. *
  3373. * @VueI18nGeneral
  3374. */
  3375. function createI18n(options = {}) {
  3376. // prettier-ignore
  3377. const __legacyMode = isBoolean(options.legacy)
  3378. ? options.legacy
  3379. : true;
  3380. const __globalInjection = !!options.globalInjection;
  3381. const __instances = new Map();
  3382. // prettier-ignore
  3383. const __global = __legacyMode
  3384. ? createVueI18n(options)
  3385. : createComposer(options);
  3386. const symbol = makeSymbol('vue-i18n' );
  3387. const i18n = {
  3388. // mode
  3389. get mode() {
  3390. // prettier-ignore
  3391. return __legacyMode
  3392. ? 'legacy'
  3393. : 'composition'
  3394. ;
  3395. },
  3396. // install plugin
  3397. async install(app, ...options) {
  3398. {
  3399. app.__VUE_I18N__ = i18n;
  3400. }
  3401. // setup global provider
  3402. app.__VUE_I18N_SYMBOL__ = symbol;
  3403. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  3404. // global method and properties injection for Composition API
  3405. if (!__legacyMode && __globalInjection) {
  3406. injectGlobalFields(app, i18n.global);
  3407. }
  3408. // install built-in components and directive
  3409. {
  3410. apply(app, i18n, ...options);
  3411. }
  3412. // setup mixin for Legacy API
  3413. if (__legacyMode) {
  3414. app.mixin(defineMixin(__global, __global.__composer, i18n));
  3415. }
  3416. // setup vue-devtools plugin
  3417. {
  3418. const ret = await enableDevTools(app, i18n);
  3419. if (!ret) {
  3420. throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
  3421. }
  3422. const emitter = createEmitter();
  3423. if (__legacyMode) {
  3424. const _vueI18n = __global;
  3425. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  3426. }
  3427. else {
  3428. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3429. const _composer = __global;
  3430. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  3431. }
  3432. emitter.on('*', addTimelineEvent);
  3433. }
  3434. },
  3435. // global accessor
  3436. get global() {
  3437. return __global;
  3438. },
  3439. // @internal
  3440. __instances,
  3441. // @internal
  3442. __getInstance(component) {
  3443. return __instances.get(component) || null;
  3444. },
  3445. // @internal
  3446. __setInstance(component, instance) {
  3447. __instances.set(component, instance);
  3448. },
  3449. // @internal
  3450. __deleteInstance(component) {
  3451. __instances.delete(component);
  3452. }
  3453. };
  3454. return i18n;
  3455. }
  3456. /**
  3457. * Use Composition API for Vue I18n
  3458. *
  3459. * @param options - An options, see {@link UseI18nOptions}
  3460. *
  3461. * @returns {@link Composer} instance
  3462. *
  3463. * @remarks
  3464. * This function is mainly used by `setup`.
  3465. *
  3466. * If options are specified, Composer instance is created for each component and you can be localized on the component.
  3467. *
  3468. * If options are not specified, you can be localized using the global Composer.
  3469. *
  3470. * @example
  3471. * case: Component resource base localization
  3472. * ```html
  3473. * <template>
  3474. * <form>
  3475. * <label>{{ t('language') }}</label>
  3476. * <select v-model="locale">
  3477. * <option value="en">en</option>
  3478. * <option value="ja">ja</option>
  3479. * </select>
  3480. * </form>
  3481. * <p>message: {{ t('hello') }}</p>
  3482. * </template>
  3483. *
  3484. * <script>
  3485. * import { useI18n } from 'vue-i18n'
  3486. *
  3487. * export default {
  3488. * setup() {
  3489. * const { t, locale } = useI18n({
  3490. * locale: 'ja',
  3491. * messages: {
  3492. * en: { ... },
  3493. * ja: { ... }
  3494. * }
  3495. * })
  3496. * // Something to do ...
  3497. *
  3498. * return { ..., t, locale }
  3499. * }
  3500. * }
  3501. * </script>
  3502. * ```
  3503. *
  3504. * @VueI18nComposition
  3505. */
  3506. function useI18n(options = {}) {
  3507. const instance = vue.getCurrentInstance();
  3508. if (instance == null) {
  3509. throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */);
  3510. }
  3511. if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
  3512. throw createI18nError(17 /* NOT_INSLALLED */);
  3513. }
  3514. const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
  3515. /* istanbul ignore if */
  3516. if (!i18n) {
  3517. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3518. }
  3519. // prettier-ignore
  3520. const global = i18n.mode === 'composition'
  3521. ? i18n.global
  3522. : i18n.global.__composer;
  3523. // prettier-ignore
  3524. const scope = isEmptyObject(options)
  3525. ? ('__i18n' in instance.type)
  3526. ? 'local'
  3527. : 'global'
  3528. : !options.useScope
  3529. ? 'local'
  3530. : options.useScope;
  3531. if (scope === 'global') {
  3532. let messages = isObject(options.messages) ? options.messages : {};
  3533. if ('__i18nGlobal' in instance.type) {
  3534. messages = getLocaleMessages(global.locale.value, {
  3535. messages,
  3536. __i18n: instance.type.__i18nGlobal
  3537. });
  3538. }
  3539. // merge locale messages
  3540. const locales = Object.keys(messages);
  3541. if (locales.length) {
  3542. locales.forEach(locale => {
  3543. global.mergeLocaleMessage(locale, messages[locale]);
  3544. });
  3545. }
  3546. // merge datetime formats
  3547. if (isObject(options.datetimeFormats)) {
  3548. const locales = Object.keys(options.datetimeFormats);
  3549. if (locales.length) {
  3550. locales.forEach(locale => {
  3551. global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  3552. });
  3553. }
  3554. }
  3555. // merge number formats
  3556. if (isObject(options.numberFormats)) {
  3557. const locales = Object.keys(options.numberFormats);
  3558. if (locales.length) {
  3559. locales.forEach(locale => {
  3560. global.mergeNumberFormat(locale, options.numberFormats[locale]);
  3561. });
  3562. }
  3563. }
  3564. return global;
  3565. }
  3566. if (scope === 'parent') {
  3567. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3568. let composer = getComposer(i18n, instance, options.__useComponent);
  3569. if (composer == null) {
  3570. {
  3571. warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
  3572. }
  3573. composer = global;
  3574. }
  3575. return composer;
  3576. }
  3577. // scope 'local' case
  3578. if (i18n.mode === 'legacy') {
  3579. throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
  3580. }
  3581. const i18nInternal = i18n;
  3582. let composer = i18nInternal.__getInstance(instance);
  3583. if (composer == null) {
  3584. const type = instance.type;
  3585. const composerOptions = assign({}, options);
  3586. if (type.__i18n) {
  3587. composerOptions.__i18n = type.__i18n;
  3588. }
  3589. if (global) {
  3590. composerOptions.__root = global;
  3591. }
  3592. composer = createComposer(composerOptions);
  3593. setupLifeCycle(i18nInternal, instance, composer);
  3594. i18nInternal.__setInstance(instance, composer);
  3595. }
  3596. return composer;
  3597. }
  3598. function getComposer(i18n, target, useComponent = false) {
  3599. let composer = null;
  3600. const root = target.root;
  3601. let current = target.parent;
  3602. while (current != null) {
  3603. const i18nInternal = i18n;
  3604. if (i18n.mode === 'composition') {
  3605. composer = i18nInternal.__getInstance(current);
  3606. }
  3607. else {
  3608. const vueI18n = i18nInternal.__getInstance(current);
  3609. if (vueI18n != null) {
  3610. composer = vueI18n
  3611. .__composer;
  3612. }
  3613. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3614. if (useComponent && composer && !composer[InejctWithOption]) {
  3615. composer = null;
  3616. }
  3617. }
  3618. if (composer != null) {
  3619. break;
  3620. }
  3621. if (root === current) {
  3622. break;
  3623. }
  3624. current = current.parent;
  3625. }
  3626. return composer;
  3627. }
  3628. function setupLifeCycle(i18n, target, composer) {
  3629. let emitter = null;
  3630. vue.onMounted(() => {
  3631. // inject composer instance to DOM for intlify-devtools
  3632. if (target.vnode.el) {
  3633. target.vnode.el.__VUE_I18N__ = composer;
  3634. emitter = createEmitter();
  3635. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3636. const _composer = composer;
  3637. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  3638. emitter.on('*', addTimelineEvent);
  3639. }
  3640. }, target);
  3641. vue.onUnmounted(() => {
  3642. // remove composer instance from DOM for intlify-devtools
  3643. if (target.vnode.el &&
  3644. target.vnode.el.__VUE_I18N__) {
  3645. emitter && emitter.off('*', addTimelineEvent);
  3646. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3647. const _composer = composer;
  3648. _composer[DisableEmitter] && _composer[DisableEmitter]();
  3649. delete target.vnode.el.__VUE_I18N__;
  3650. }
  3651. i18n.__deleteInstance(target);
  3652. }, target);
  3653. }
  3654. const globalExportProps = [
  3655. 'locale',
  3656. 'fallbackLocale',
  3657. 'availableLocales'
  3658. ];
  3659. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm'];
  3660. function injectGlobalFields(app, composer) {
  3661. const i18n = Object.create(null);
  3662. globalExportProps.forEach(prop => {
  3663. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  3664. if (!desc) {
  3665. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3666. }
  3667. const wrap = vue.isRef(desc.value) // check computed props
  3668. ? {
  3669. get() {
  3670. return desc.value.value;
  3671. },
  3672. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3673. set(val) {
  3674. desc.value.value = val;
  3675. }
  3676. }
  3677. : {
  3678. get() {
  3679. return desc.get && desc.get();
  3680. }
  3681. };
  3682. Object.defineProperty(i18n, prop, wrap);
  3683. });
  3684. app.config.globalProperties.$i18n = i18n;
  3685. globalExportMethods.forEach(method => {
  3686. const desc = Object.getOwnPropertyDescriptor(composer, method);
  3687. if (!desc || !desc.value) {
  3688. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3689. }
  3690. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  3691. });
  3692. }
  3693. // NOTE: experimental !!
  3694. {
  3695. const target = getGlobalThis();
  3696. target.__INTLIFY__ = true;
  3697. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  3698. }
  3699. {
  3700. initDev();
  3701. }
  3702. exports.DatetimeFormat = DatetimeFormat;
  3703. exports.NumberFormat = NumberFormat;
  3704. exports.Translation = Translation;
  3705. exports.VERSION = VERSION;
  3706. exports.createI18n = createI18n;
  3707. exports.useI18n = useI18n;
  3708. exports.vTDirective = vTDirective;
  3709. Object.defineProperty(exports, '__esModule', { value: true });
  3710. return exports;
  3711. }({}, Vue));