vue-i18n.global.js 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073
  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. /** @internal */
  600. function defaultOnError(error) {
  601. throw error;
  602. }
  603. function createPosition(line, column, offset) {
  604. return { line, column, offset };
  605. }
  606. function createLocation(start, end, source) {
  607. const loc = { start, end };
  608. if (source != null) {
  609. loc.source = source;
  610. }
  611. return loc;
  612. }
  613. const CHAR_SP = ' ';
  614. const CHAR_CR = '\r';
  615. const CHAR_LF = '\n';
  616. const CHAR_LS = String.fromCharCode(0x2028);
  617. const CHAR_PS = String.fromCharCode(0x2029);
  618. function createScanner(str) {
  619. const _buf = str;
  620. let _index = 0;
  621. let _line = 1;
  622. let _column = 1;
  623. let _peekOffset = 0;
  624. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  625. const isLF = (index) => _buf[index] === CHAR_LF;
  626. const isPS = (index) => _buf[index] === CHAR_PS;
  627. const isLS = (index) => _buf[index] === CHAR_LS;
  628. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  629. const index = () => _index;
  630. const line = () => _line;
  631. const column = () => _column;
  632. const peekOffset = () => _peekOffset;
  633. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  634. const currentChar = () => charAt(_index);
  635. const currentPeek = () => charAt(_index + _peekOffset);
  636. function next() {
  637. _peekOffset = 0;
  638. if (isLineEnd(_index)) {
  639. _line++;
  640. _column = 0;
  641. }
  642. if (isCRLF(_index)) {
  643. _index++;
  644. }
  645. _index++;
  646. _column++;
  647. return _buf[_index];
  648. }
  649. function peek() {
  650. if (isCRLF(_index + _peekOffset)) {
  651. _peekOffset++;
  652. }
  653. _peekOffset++;
  654. return _buf[_index + _peekOffset];
  655. }
  656. function reset() {
  657. _index = 0;
  658. _line = 1;
  659. _column = 1;
  660. _peekOffset = 0;
  661. }
  662. function resetPeek(offset = 0) {
  663. _peekOffset = offset;
  664. }
  665. function skipToPeek() {
  666. const target = _index + _peekOffset;
  667. // eslint-disable-next-line no-unmodified-loop-condition
  668. while (target !== _index) {
  669. next();
  670. }
  671. _peekOffset = 0;
  672. }
  673. return {
  674. index,
  675. line,
  676. column,
  677. peekOffset,
  678. charAt,
  679. currentChar,
  680. currentPeek,
  681. next,
  682. peek,
  683. reset,
  684. resetPeek,
  685. skipToPeek
  686. };
  687. }
  688. const EOF = undefined;
  689. const LITERAL_DELIMITER = "'";
  690. const ERROR_DOMAIN$1 = 'tokenizer';
  691. function createTokenizer(source, options = {}) {
  692. const location = options.location !== false;
  693. const _scnr = createScanner(source);
  694. const currentOffset = () => _scnr.index();
  695. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  696. const _initLoc = currentPosition();
  697. const _initOffset = currentOffset();
  698. const _context = {
  699. currentType: 14 /* EOF */,
  700. offset: _initOffset,
  701. startLoc: _initLoc,
  702. endLoc: _initLoc,
  703. lastType: 14 /* EOF */,
  704. lastOffset: _initOffset,
  705. lastStartLoc: _initLoc,
  706. lastEndLoc: _initLoc,
  707. braceNest: 0,
  708. inLinked: false,
  709. text: ''
  710. };
  711. const context = () => _context;
  712. const { onError } = options;
  713. function emitError(code, pos, offset, ...args) {
  714. const ctx = context();
  715. pos.column += offset;
  716. pos.offset += offset;
  717. if (onError) {
  718. const loc = createLocation(ctx.startLoc, pos);
  719. const err = createCompileError(code, loc, {
  720. domain: ERROR_DOMAIN$1,
  721. args
  722. });
  723. onError(err);
  724. }
  725. }
  726. function getToken(context, type, value) {
  727. context.endLoc = currentPosition();
  728. context.currentType = type;
  729. const token = { type };
  730. if (location) {
  731. token.loc = createLocation(context.startLoc, context.endLoc);
  732. }
  733. if (value != null) {
  734. token.value = value;
  735. }
  736. return token;
  737. }
  738. const getEndToken = (context) => getToken(context, 14 /* EOF */);
  739. function eat(scnr, ch) {
  740. if (scnr.currentChar() === ch) {
  741. scnr.next();
  742. return ch;
  743. }
  744. else {
  745. emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
  746. return '';
  747. }
  748. }
  749. function peekSpaces(scnr) {
  750. let buf = '';
  751. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  752. buf += scnr.currentPeek();
  753. scnr.peek();
  754. }
  755. return buf;
  756. }
  757. function skipSpaces(scnr) {
  758. const buf = peekSpaces(scnr);
  759. scnr.skipToPeek();
  760. return buf;
  761. }
  762. function isIdentifierStart(ch) {
  763. if (ch === EOF) {
  764. return false;
  765. }
  766. const cc = ch.charCodeAt(0);
  767. return ((cc >= 97 && cc <= 122) || // a-z
  768. (cc >= 65 && cc <= 90) || // A-Z
  769. cc === 95 // _
  770. );
  771. }
  772. function isNumberStart(ch) {
  773. if (ch === EOF) {
  774. return false;
  775. }
  776. const cc = ch.charCodeAt(0);
  777. return cc >= 48 && cc <= 57; // 0-9
  778. }
  779. function isNamedIdentifierStart(scnr, context) {
  780. const { currentType } = context;
  781. if (currentType !== 2 /* BraceLeft */) {
  782. return false;
  783. }
  784. peekSpaces(scnr);
  785. const ret = isIdentifierStart(scnr.currentPeek());
  786. scnr.resetPeek();
  787. return ret;
  788. }
  789. function isListIdentifierStart(scnr, context) {
  790. const { currentType } = context;
  791. if (currentType !== 2 /* BraceLeft */) {
  792. return false;
  793. }
  794. peekSpaces(scnr);
  795. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  796. const ret = isNumberStart(ch);
  797. scnr.resetPeek();
  798. return ret;
  799. }
  800. function isLiteralStart(scnr, context) {
  801. const { currentType } = context;
  802. if (currentType !== 2 /* BraceLeft */) {
  803. return false;
  804. }
  805. peekSpaces(scnr);
  806. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  807. scnr.resetPeek();
  808. return ret;
  809. }
  810. function isLinkedDotStart(scnr, context) {
  811. const { currentType } = context;
  812. if (currentType !== 8 /* LinkedAlias */) {
  813. return false;
  814. }
  815. peekSpaces(scnr);
  816. const ret = scnr.currentPeek() === "." /* LinkedDot */;
  817. scnr.resetPeek();
  818. return ret;
  819. }
  820. function isLinkedModifierStart(scnr, context) {
  821. const { currentType } = context;
  822. if (currentType !== 9 /* LinkedDot */) {
  823. return false;
  824. }
  825. peekSpaces(scnr);
  826. const ret = isIdentifierStart(scnr.currentPeek());
  827. scnr.resetPeek();
  828. return ret;
  829. }
  830. function isLinkedDelimiterStart(scnr, context) {
  831. const { currentType } = context;
  832. if (!(currentType === 8 /* LinkedAlias */ ||
  833. currentType === 12 /* LinkedModifier */)) {
  834. return false;
  835. }
  836. peekSpaces(scnr);
  837. const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
  838. scnr.resetPeek();
  839. return ret;
  840. }
  841. function isLinkedReferStart(scnr, context) {
  842. const { currentType } = context;
  843. if (currentType !== 10 /* LinkedDelimiter */) {
  844. return false;
  845. }
  846. const fn = () => {
  847. const ch = scnr.currentPeek();
  848. if (ch === "{" /* BraceLeft */) {
  849. return isIdentifierStart(scnr.peek());
  850. }
  851. else if (ch === "@" /* LinkedAlias */ ||
  852. ch === "%" /* Modulo */ ||
  853. ch === "|" /* Pipe */ ||
  854. ch === ":" /* LinkedDelimiter */ ||
  855. ch === "." /* LinkedDot */ ||
  856. ch === CHAR_SP ||
  857. !ch) {
  858. return false;
  859. }
  860. else if (ch === CHAR_LF) {
  861. scnr.peek();
  862. return fn();
  863. }
  864. else {
  865. // other characters
  866. return isIdentifierStart(ch);
  867. }
  868. };
  869. const ret = fn();
  870. scnr.resetPeek();
  871. return ret;
  872. }
  873. function isPluralStart(scnr) {
  874. peekSpaces(scnr);
  875. const ret = scnr.currentPeek() === "|" /* Pipe */;
  876. scnr.resetPeek();
  877. return ret;
  878. }
  879. function isTextStart(scnr, reset = true) {
  880. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  881. const ch = scnr.currentPeek();
  882. if (ch === "{" /* BraceLeft */) {
  883. return prev === "%" /* Modulo */ ? false : hasSpace;
  884. }
  885. else if (ch === "@" /* LinkedAlias */ || !ch) {
  886. return prev === "%" /* Modulo */ ? true : hasSpace;
  887. }
  888. else if (ch === "%" /* Modulo */) {
  889. scnr.peek();
  890. return fn(hasSpace, "%" /* Modulo */, true);
  891. }
  892. else if (ch === "|" /* Pipe */) {
  893. return prev === "%" /* Modulo */ || detectModulo
  894. ? true
  895. : !(prev === CHAR_SP || prev === CHAR_LF);
  896. }
  897. else if (ch === CHAR_SP) {
  898. scnr.peek();
  899. return fn(true, CHAR_SP, detectModulo);
  900. }
  901. else if (ch === CHAR_LF) {
  902. scnr.peek();
  903. return fn(true, CHAR_LF, detectModulo);
  904. }
  905. else {
  906. return true;
  907. }
  908. };
  909. const ret = fn();
  910. reset && scnr.resetPeek();
  911. return ret;
  912. }
  913. function takeChar(scnr, fn) {
  914. const ch = scnr.currentChar();
  915. if (ch === EOF) {
  916. return EOF;
  917. }
  918. if (fn(ch)) {
  919. scnr.next();
  920. return ch;
  921. }
  922. return null;
  923. }
  924. function takeIdentifierChar(scnr) {
  925. const closure = (ch) => {
  926. const cc = ch.charCodeAt(0);
  927. return ((cc >= 97 && cc <= 122) || // a-z
  928. (cc >= 65 && cc <= 90) || // A-Z
  929. (cc >= 48 && cc <= 57) || // 0-9
  930. cc === 95 || // _
  931. cc === 36 // $
  932. );
  933. };
  934. return takeChar(scnr, closure);
  935. }
  936. function takeDigit(scnr) {
  937. const closure = (ch) => {
  938. const cc = ch.charCodeAt(0);
  939. return cc >= 48 && cc <= 57; // 0-9
  940. };
  941. return takeChar(scnr, closure);
  942. }
  943. function takeHexDigit(scnr) {
  944. const closure = (ch) => {
  945. const cc = ch.charCodeAt(0);
  946. return ((cc >= 48 && cc <= 57) || // 0-9
  947. (cc >= 65 && cc <= 70) || // A-F
  948. (cc >= 97 && cc <= 102)); // a-f
  949. };
  950. return takeChar(scnr, closure);
  951. }
  952. function getDigits(scnr) {
  953. let ch = '';
  954. let num = '';
  955. while ((ch = takeDigit(scnr))) {
  956. num += ch;
  957. }
  958. return num;
  959. }
  960. function readText(scnr) {
  961. let buf = '';
  962. while (true) {
  963. const ch = scnr.currentChar();
  964. if (ch === "{" /* BraceLeft */ ||
  965. ch === "}" /* BraceRight */ ||
  966. ch === "@" /* LinkedAlias */ ||
  967. ch === "|" /* Pipe */ ||
  968. !ch) {
  969. break;
  970. }
  971. else if (ch === "%" /* Modulo */) {
  972. if (isTextStart(scnr)) {
  973. buf += ch;
  974. scnr.next();
  975. }
  976. else {
  977. break;
  978. }
  979. }
  980. else if (ch === CHAR_SP || ch === CHAR_LF) {
  981. if (isTextStart(scnr)) {
  982. buf += ch;
  983. scnr.next();
  984. }
  985. else if (isPluralStart(scnr)) {
  986. break;
  987. }
  988. else {
  989. buf += ch;
  990. scnr.next();
  991. }
  992. }
  993. else {
  994. buf += ch;
  995. scnr.next();
  996. }
  997. }
  998. return buf;
  999. }
  1000. function readNamedIdentifier(scnr) {
  1001. skipSpaces(scnr);
  1002. let ch = '';
  1003. let name = '';
  1004. while ((ch = takeIdentifierChar(scnr))) {
  1005. name += ch;
  1006. }
  1007. if (scnr.currentChar() === EOF) {
  1008. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1009. }
  1010. return name;
  1011. }
  1012. function readListIdentifier(scnr) {
  1013. skipSpaces(scnr);
  1014. let value = '';
  1015. if (scnr.currentChar() === '-') {
  1016. scnr.next();
  1017. value += `-${getDigits(scnr)}`;
  1018. }
  1019. else {
  1020. value += getDigits(scnr);
  1021. }
  1022. if (scnr.currentChar() === EOF) {
  1023. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1024. }
  1025. return value;
  1026. }
  1027. function readLiteral(scnr) {
  1028. skipSpaces(scnr);
  1029. eat(scnr, `\'`);
  1030. let ch = '';
  1031. let literal = '';
  1032. const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
  1033. while ((ch = takeChar(scnr, fn))) {
  1034. if (ch === '\\') {
  1035. literal += readEscapeSequence(scnr);
  1036. }
  1037. else {
  1038. literal += ch;
  1039. }
  1040. }
  1041. const current = scnr.currentChar();
  1042. if (current === CHAR_LF || current === EOF) {
  1043. emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
  1044. // TODO: Is it correct really?
  1045. if (current === CHAR_LF) {
  1046. scnr.next();
  1047. eat(scnr, `\'`);
  1048. }
  1049. return literal;
  1050. }
  1051. eat(scnr, `\'`);
  1052. return literal;
  1053. }
  1054. function readEscapeSequence(scnr) {
  1055. const ch = scnr.currentChar();
  1056. switch (ch) {
  1057. case '\\':
  1058. case `\'`:
  1059. scnr.next();
  1060. return `\\${ch}`;
  1061. case 'u':
  1062. return readUnicodeEscapeSequence(scnr, ch, 4);
  1063. case 'U':
  1064. return readUnicodeEscapeSequence(scnr, ch, 6);
  1065. default:
  1066. emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
  1067. return '';
  1068. }
  1069. }
  1070. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  1071. eat(scnr, unicode);
  1072. let sequence = '';
  1073. for (let i = 0; i < digits; i++) {
  1074. const ch = takeHexDigit(scnr);
  1075. if (!ch) {
  1076. emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  1077. break;
  1078. }
  1079. sequence += ch;
  1080. }
  1081. return `\\${unicode}${sequence}`;
  1082. }
  1083. function readInvalidIdentifier(scnr) {
  1084. skipSpaces(scnr);
  1085. let ch = '';
  1086. let identifiers = '';
  1087. const closure = (ch) => ch !== "{" /* BraceLeft */ &&
  1088. ch !== "}" /* BraceRight */ &&
  1089. ch !== CHAR_SP &&
  1090. ch !== CHAR_LF;
  1091. while ((ch = takeChar(scnr, closure))) {
  1092. identifiers += ch;
  1093. }
  1094. return identifiers;
  1095. }
  1096. function readLinkedModifier(scnr) {
  1097. let ch = '';
  1098. let name = '';
  1099. while ((ch = takeIdentifierChar(scnr))) {
  1100. name += ch;
  1101. }
  1102. return name;
  1103. }
  1104. function readLinkedRefer(scnr) {
  1105. const fn = (detect = false, buf) => {
  1106. const ch = scnr.currentChar();
  1107. if (ch === "{" /* BraceLeft */ ||
  1108. ch === "%" /* Modulo */ ||
  1109. ch === "@" /* LinkedAlias */ ||
  1110. ch === "|" /* Pipe */ ||
  1111. !ch) {
  1112. return buf;
  1113. }
  1114. else if (ch === CHAR_SP) {
  1115. return buf;
  1116. }
  1117. else if (ch === CHAR_LF) {
  1118. buf += ch;
  1119. scnr.next();
  1120. return fn(detect, buf);
  1121. }
  1122. else {
  1123. buf += ch;
  1124. scnr.next();
  1125. return fn(true, buf);
  1126. }
  1127. };
  1128. return fn(false, '');
  1129. }
  1130. function readPlural(scnr) {
  1131. skipSpaces(scnr);
  1132. const plural = eat(scnr, "|" /* Pipe */);
  1133. skipSpaces(scnr);
  1134. return plural;
  1135. }
  1136. // TODO: We need refactoring of token parsing ...
  1137. function readTokenInPlaceholder(scnr, context) {
  1138. let token = null;
  1139. const ch = scnr.currentChar();
  1140. switch (ch) {
  1141. case "{" /* BraceLeft */:
  1142. if (context.braceNest >= 1) {
  1143. emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
  1144. }
  1145. scnr.next();
  1146. token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
  1147. skipSpaces(scnr);
  1148. context.braceNest++;
  1149. return token;
  1150. case "}" /* BraceRight */:
  1151. if (context.braceNest > 0 &&
  1152. context.currentType === 2 /* BraceLeft */) {
  1153. emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
  1154. }
  1155. scnr.next();
  1156. token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  1157. context.braceNest--;
  1158. context.braceNest > 0 && skipSpaces(scnr);
  1159. if (context.inLinked && context.braceNest === 0) {
  1160. context.inLinked = false;
  1161. }
  1162. return token;
  1163. case "@" /* LinkedAlias */:
  1164. if (context.braceNest > 0) {
  1165. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1166. }
  1167. token = readTokenInLinked(scnr, context) || getEndToken(context);
  1168. context.braceNest = 0;
  1169. return token;
  1170. default:
  1171. let validNamedIdentifier = true;
  1172. let validListIdentifier = true;
  1173. let validLiteral = true;
  1174. if (isPluralStart(scnr)) {
  1175. if (context.braceNest > 0) {
  1176. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1177. }
  1178. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1179. // reset
  1180. context.braceNest = 0;
  1181. context.inLinked = false;
  1182. return token;
  1183. }
  1184. if (context.braceNest > 0 &&
  1185. (context.currentType === 5 /* Named */ ||
  1186. context.currentType === 6 /* List */ ||
  1187. context.currentType === 7 /* Literal */)) {
  1188. emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
  1189. context.braceNest = 0;
  1190. return readToken(scnr, context);
  1191. }
  1192. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  1193. token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
  1194. skipSpaces(scnr);
  1195. return token;
  1196. }
  1197. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  1198. token = getToken(context, 6 /* List */, readListIdentifier(scnr));
  1199. skipSpaces(scnr);
  1200. return token;
  1201. }
  1202. if ((validLiteral = isLiteralStart(scnr, context))) {
  1203. token = getToken(context, 7 /* Literal */, readLiteral(scnr));
  1204. skipSpaces(scnr);
  1205. return token;
  1206. }
  1207. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  1208. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  1209. token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
  1210. emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
  1211. skipSpaces(scnr);
  1212. return token;
  1213. }
  1214. break;
  1215. }
  1216. return token;
  1217. }
  1218. // TODO: We need refactoring of token parsing ...
  1219. function readTokenInLinked(scnr, context) {
  1220. const { currentType } = context;
  1221. let token = null;
  1222. const ch = scnr.currentChar();
  1223. if ((currentType === 8 /* LinkedAlias */ ||
  1224. currentType === 9 /* LinkedDot */ ||
  1225. currentType === 12 /* LinkedModifier */ ||
  1226. currentType === 10 /* LinkedDelimiter */) &&
  1227. (ch === CHAR_LF || ch === CHAR_SP)) {
  1228. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  1229. }
  1230. switch (ch) {
  1231. case "@" /* LinkedAlias */:
  1232. scnr.next();
  1233. token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
  1234. context.inLinked = true;
  1235. return token;
  1236. case "." /* LinkedDot */:
  1237. skipSpaces(scnr);
  1238. scnr.next();
  1239. return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
  1240. case ":" /* LinkedDelimiter */:
  1241. skipSpaces(scnr);
  1242. scnr.next();
  1243. return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
  1244. default:
  1245. if (isPluralStart(scnr)) {
  1246. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1247. // reset
  1248. context.braceNest = 0;
  1249. context.inLinked = false;
  1250. return token;
  1251. }
  1252. if (isLinkedDotStart(scnr, context) ||
  1253. isLinkedDelimiterStart(scnr, context)) {
  1254. skipSpaces(scnr);
  1255. return readTokenInLinked(scnr, context);
  1256. }
  1257. if (isLinkedModifierStart(scnr, context)) {
  1258. skipSpaces(scnr);
  1259. return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
  1260. }
  1261. if (isLinkedReferStart(scnr, context)) {
  1262. skipSpaces(scnr);
  1263. if (ch === "{" /* BraceLeft */) {
  1264. // scan the placeholder
  1265. return readTokenInPlaceholder(scnr, context) || token;
  1266. }
  1267. else {
  1268. return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
  1269. }
  1270. }
  1271. if (currentType === 8 /* LinkedAlias */) {
  1272. emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
  1273. }
  1274. context.braceNest = 0;
  1275. context.inLinked = false;
  1276. return readToken(scnr, context);
  1277. }
  1278. }
  1279. // TODO: We need refactoring of token parsing ...
  1280. function readToken(scnr, context) {
  1281. let token = { type: 14 /* EOF */ };
  1282. if (context.braceNest > 0) {
  1283. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1284. }
  1285. if (context.inLinked) {
  1286. return readTokenInLinked(scnr, context) || getEndToken(context);
  1287. }
  1288. const ch = scnr.currentChar();
  1289. switch (ch) {
  1290. case "{" /* BraceLeft */:
  1291. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1292. case "}" /* BraceRight */:
  1293. emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
  1294. scnr.next();
  1295. return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
  1296. case "@" /* LinkedAlias */:
  1297. return readTokenInLinked(scnr, context) || getEndToken(context);
  1298. default:
  1299. if (isPluralStart(scnr)) {
  1300. token = getToken(context, 1 /* Pipe */, readPlural(scnr));
  1301. // reset
  1302. context.braceNest = 0;
  1303. context.inLinked = false;
  1304. return token;
  1305. }
  1306. if (isTextStart(scnr)) {
  1307. return getToken(context, 0 /* Text */, readText(scnr));
  1308. }
  1309. if (ch === "%" /* Modulo */) {
  1310. scnr.next();
  1311. return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
  1312. }
  1313. break;
  1314. }
  1315. return token;
  1316. }
  1317. function nextToken() {
  1318. const { currentType, offset, startLoc, endLoc } = _context;
  1319. _context.lastType = currentType;
  1320. _context.lastOffset = offset;
  1321. _context.lastStartLoc = startLoc;
  1322. _context.lastEndLoc = endLoc;
  1323. _context.offset = currentOffset();
  1324. _context.startLoc = currentPosition();
  1325. if (_scnr.currentChar() === EOF) {
  1326. return getToken(_context, 14 /* EOF */);
  1327. }
  1328. return readToken(_scnr, _context);
  1329. }
  1330. return {
  1331. nextToken,
  1332. currentOffset,
  1333. currentPosition,
  1334. context
  1335. };
  1336. }
  1337. const ERROR_DOMAIN = 'parser';
  1338. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1339. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1340. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1341. switch (match) {
  1342. case `\\\\`:
  1343. return `\\`;
  1344. case `\\\'`:
  1345. return `\'`;
  1346. default: {
  1347. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1348. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1349. return String.fromCodePoint(codePoint);
  1350. }
  1351. // invalid ...
  1352. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1353. return '�';
  1354. }
  1355. }
  1356. }
  1357. function createParser(options = {}) {
  1358. const location = options.location !== false;
  1359. const { onError } = options;
  1360. function emitError(tokenzer, code, start, offset, ...args) {
  1361. const end = tokenzer.currentPosition();
  1362. end.offset += offset;
  1363. end.column += offset;
  1364. if (onError) {
  1365. const loc = createLocation(start, end);
  1366. const err = createCompileError(code, loc, {
  1367. domain: ERROR_DOMAIN,
  1368. args
  1369. });
  1370. onError(err);
  1371. }
  1372. }
  1373. function startNode(type, offset, loc) {
  1374. const node = {
  1375. type,
  1376. start: offset,
  1377. end: offset
  1378. };
  1379. if (location) {
  1380. node.loc = { start: loc, end: loc };
  1381. }
  1382. return node;
  1383. }
  1384. function endNode(node, offset, pos, type) {
  1385. node.end = offset;
  1386. if (type) {
  1387. node.type = type;
  1388. }
  1389. if (location && node.loc) {
  1390. node.loc.end = pos;
  1391. }
  1392. }
  1393. function parseText(tokenizer, value) {
  1394. const context = tokenizer.context();
  1395. const node = startNode(3 /* Text */, context.offset, context.startLoc);
  1396. node.value = value;
  1397. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1398. return node;
  1399. }
  1400. function parseList(tokenizer, index) {
  1401. const context = tokenizer.context();
  1402. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1403. const node = startNode(5 /* List */, offset, loc);
  1404. node.index = parseInt(index, 10);
  1405. tokenizer.nextToken(); // skip brach right
  1406. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1407. return node;
  1408. }
  1409. function parseNamed(tokenizer, key) {
  1410. const context = tokenizer.context();
  1411. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1412. const node = startNode(4 /* Named */, offset, loc);
  1413. node.key = key;
  1414. tokenizer.nextToken(); // skip brach right
  1415. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1416. return node;
  1417. }
  1418. function parseLiteral(tokenizer, value) {
  1419. const context = tokenizer.context();
  1420. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1421. const node = startNode(9 /* Literal */, offset, loc);
  1422. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1423. tokenizer.nextToken(); // skip brach right
  1424. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1425. return node;
  1426. }
  1427. function parseLinkedModifier(tokenizer) {
  1428. const token = tokenizer.nextToken();
  1429. const context = tokenizer.context();
  1430. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1431. const node = startNode(8 /* LinkedModifier */, offset, loc);
  1432. if (token.type !== 12 /* LinkedModifier */) {
  1433. // empty modifier
  1434. emitError(tokenizer, 11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */, context.lastStartLoc, 0);
  1435. node.value = '';
  1436. endNode(node, offset, loc);
  1437. return {
  1438. nextConsumeToken: token,
  1439. node
  1440. };
  1441. }
  1442. // check token
  1443. if (token.value == null) {
  1444. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1445. }
  1446. node.value = token.value || '';
  1447. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1448. return {
  1449. node
  1450. };
  1451. }
  1452. function parseLinkedKey(tokenizer, value) {
  1453. const context = tokenizer.context();
  1454. const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
  1455. node.value = value;
  1456. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1457. return node;
  1458. }
  1459. function parseLinked(tokenizer) {
  1460. const context = tokenizer.context();
  1461. const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
  1462. let token = tokenizer.nextToken();
  1463. if (token.type === 9 /* LinkedDot */) {
  1464. const parsed = parseLinkedModifier(tokenizer);
  1465. linkedNode.modifier = parsed.node;
  1466. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1467. }
  1468. // asset check token
  1469. if (token.type !== 10 /* LinkedDelimiter */) {
  1470. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1471. }
  1472. token = tokenizer.nextToken();
  1473. // skip brace left
  1474. if (token.type === 2 /* BraceLeft */) {
  1475. token = tokenizer.nextToken();
  1476. }
  1477. switch (token.type) {
  1478. case 11 /* LinkedKey */:
  1479. if (token.value == null) {
  1480. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1481. }
  1482. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1483. break;
  1484. case 5 /* Named */:
  1485. if (token.value == null) {
  1486. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1487. }
  1488. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1489. break;
  1490. case 6 /* List */:
  1491. if (token.value == null) {
  1492. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1493. }
  1494. linkedNode.key = parseList(tokenizer, token.value || '');
  1495. break;
  1496. case 7 /* Literal */:
  1497. if (token.value == null) {
  1498. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1499. }
  1500. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1501. break;
  1502. default:
  1503. // empty key
  1504. emitError(tokenizer, 12 /* UNEXPECTED_EMPTY_LINKED_KEY */, context.lastStartLoc, 0);
  1505. const nextContext = tokenizer.context();
  1506. const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc);
  1507. emptyLinkedKeyNode.value = '';
  1508. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1509. linkedNode.key = emptyLinkedKeyNode;
  1510. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1511. return {
  1512. nextConsumeToken: token,
  1513. node: linkedNode
  1514. };
  1515. }
  1516. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1517. return {
  1518. node: linkedNode
  1519. };
  1520. }
  1521. function parseMessage(tokenizer) {
  1522. const context = tokenizer.context();
  1523. const startOffset = context.currentType === 1 /* Pipe */
  1524. ? tokenizer.currentOffset()
  1525. : context.offset;
  1526. const startLoc = context.currentType === 1 /* Pipe */
  1527. ? context.endLoc
  1528. : context.startLoc;
  1529. const node = startNode(2 /* Message */, startOffset, startLoc);
  1530. node.items = [];
  1531. let nextToken = null;
  1532. do {
  1533. const token = nextToken || tokenizer.nextToken();
  1534. nextToken = null;
  1535. switch (token.type) {
  1536. case 0 /* Text */:
  1537. if (token.value == null) {
  1538. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1539. }
  1540. node.items.push(parseText(tokenizer, token.value || ''));
  1541. break;
  1542. case 6 /* List */:
  1543. if (token.value == null) {
  1544. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1545. }
  1546. node.items.push(parseList(tokenizer, token.value || ''));
  1547. break;
  1548. case 5 /* Named */:
  1549. if (token.value == null) {
  1550. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1551. }
  1552. node.items.push(parseNamed(tokenizer, token.value || ''));
  1553. break;
  1554. case 7 /* Literal */:
  1555. if (token.value == null) {
  1556. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, getTokenCaption(token));
  1557. }
  1558. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1559. break;
  1560. case 8 /* LinkedAlias */:
  1561. const parsed = parseLinked(tokenizer);
  1562. node.items.push(parsed.node);
  1563. nextToken = parsed.nextConsumeToken || null;
  1564. break;
  1565. }
  1566. } while (context.currentType !== 14 /* EOF */ &&
  1567. context.currentType !== 1 /* Pipe */);
  1568. // adjust message node loc
  1569. const endOffset = context.currentType === 1 /* Pipe */
  1570. ? context.lastOffset
  1571. : tokenizer.currentOffset();
  1572. const endLoc = context.currentType === 1 /* Pipe */
  1573. ? context.lastEndLoc
  1574. : tokenizer.currentPosition();
  1575. endNode(node, endOffset, endLoc);
  1576. return node;
  1577. }
  1578. function parsePlural(tokenizer, offset, loc, msgNode) {
  1579. const context = tokenizer.context();
  1580. let hasEmptyMessage = msgNode.items.length === 0;
  1581. const node = startNode(1 /* Plural */, offset, loc);
  1582. node.cases = [];
  1583. node.cases.push(msgNode);
  1584. do {
  1585. const msg = parseMessage(tokenizer);
  1586. if (!hasEmptyMessage) {
  1587. hasEmptyMessage = msg.items.length === 0;
  1588. }
  1589. node.cases.push(msg);
  1590. } while (context.currentType !== 14 /* EOF */);
  1591. if (hasEmptyMessage) {
  1592. emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
  1593. }
  1594. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1595. return node;
  1596. }
  1597. function parseResource(tokenizer) {
  1598. const context = tokenizer.context();
  1599. const { offset, startLoc } = context;
  1600. const msgNode = parseMessage(tokenizer);
  1601. if (context.currentType === 14 /* EOF */) {
  1602. return msgNode;
  1603. }
  1604. else {
  1605. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1606. }
  1607. }
  1608. function parse(source) {
  1609. const tokenizer = createTokenizer(source, assign({}, options));
  1610. const context = tokenizer.context();
  1611. const node = startNode(0 /* Resource */, context.offset, context.startLoc);
  1612. if (location && node.loc) {
  1613. node.loc.source = source;
  1614. }
  1615. node.body = parseResource(tokenizer);
  1616. // assert whether achieved to EOF
  1617. if (context.currentType !== 14 /* EOF */) {
  1618. emitError(tokenizer, 13 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, source[context.offset] || '');
  1619. }
  1620. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1621. return node;
  1622. }
  1623. return { parse };
  1624. }
  1625. function getTokenCaption(token) {
  1626. if (token.type === 14 /* EOF */) {
  1627. return 'EOF';
  1628. }
  1629. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1630. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1631. }
  1632. function createTransformer(ast, options = {} // eslint-disable-line
  1633. ) {
  1634. const _context = {
  1635. ast,
  1636. helpers: new Set()
  1637. };
  1638. const context = () => _context;
  1639. const helper = (name) => {
  1640. _context.helpers.add(name);
  1641. return name;
  1642. };
  1643. return { context, helper };
  1644. }
  1645. function traverseNodes(nodes, transformer) {
  1646. for (let i = 0; i < nodes.length; i++) {
  1647. traverseNode(nodes[i], transformer);
  1648. }
  1649. }
  1650. function traverseNode(node, transformer) {
  1651. // TODO: if we need pre-hook of transform, should be implemented to here
  1652. switch (node.type) {
  1653. case 1 /* Plural */:
  1654. traverseNodes(node.cases, transformer);
  1655. transformer.helper("plural" /* PLURAL */);
  1656. break;
  1657. case 2 /* Message */:
  1658. traverseNodes(node.items, transformer);
  1659. break;
  1660. case 6 /* Linked */:
  1661. const linked = node;
  1662. traverseNode(linked.key, transformer);
  1663. transformer.helper("linked" /* LINKED */);
  1664. break;
  1665. case 5 /* List */:
  1666. transformer.helper("interpolate" /* INTERPOLATE */);
  1667. transformer.helper("list" /* LIST */);
  1668. break;
  1669. case 4 /* Named */:
  1670. transformer.helper("interpolate" /* INTERPOLATE */);
  1671. transformer.helper("named" /* NAMED */);
  1672. break;
  1673. }
  1674. // TODO: if we need post-hook of transform, should be implemented to here
  1675. }
  1676. // transform AST
  1677. function transform(ast, options = {} // eslint-disable-line
  1678. ) {
  1679. const transformer = createTransformer(ast);
  1680. transformer.helper("normalize" /* NORMALIZE */);
  1681. // traverse
  1682. ast.body && traverseNode(ast.body, transformer);
  1683. // set meta information
  1684. const context = transformer.context();
  1685. ast.helpers = Array.from(context.helpers);
  1686. }
  1687. function createCodeGenerator(ast, options) {
  1688. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1689. const _context = {
  1690. source: ast.loc.source,
  1691. filename,
  1692. code: '',
  1693. column: 1,
  1694. line: 1,
  1695. offset: 0,
  1696. map: undefined,
  1697. breakLineCode,
  1698. needIndent: _needIndent,
  1699. indentLevel: 0
  1700. };
  1701. const context = () => _context;
  1702. function push(code, node) {
  1703. _context.code += code;
  1704. }
  1705. function _newline(n, withBreakLine = true) {
  1706. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1707. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1708. }
  1709. function indent(withNewLine = true) {
  1710. const level = ++_context.indentLevel;
  1711. withNewLine && _newline(level);
  1712. }
  1713. function deindent(withNewLine = true) {
  1714. const level = --_context.indentLevel;
  1715. withNewLine && _newline(level);
  1716. }
  1717. function newline() {
  1718. _newline(_context.indentLevel);
  1719. }
  1720. const helper = (key) => `_${key}`;
  1721. const needIndent = () => _context.needIndent;
  1722. return {
  1723. context,
  1724. push,
  1725. indent,
  1726. deindent,
  1727. newline,
  1728. helper,
  1729. needIndent
  1730. };
  1731. }
  1732. function generateLinkedNode(generator, node) {
  1733. const { helper } = generator;
  1734. generator.push(`${helper("linked" /* LINKED */)}(`);
  1735. generateNode(generator, node.key);
  1736. if (node.modifier) {
  1737. generator.push(`, `);
  1738. generateNode(generator, node.modifier);
  1739. }
  1740. generator.push(`)`);
  1741. }
  1742. function generateMessageNode(generator, node) {
  1743. const { helper, needIndent } = generator;
  1744. generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
  1745. generator.indent(needIndent());
  1746. const length = node.items.length;
  1747. for (let i = 0; i < length; i++) {
  1748. generateNode(generator, node.items[i]);
  1749. if (i === length - 1) {
  1750. break;
  1751. }
  1752. generator.push(', ');
  1753. }
  1754. generator.deindent(needIndent());
  1755. generator.push('])');
  1756. }
  1757. function generatePluralNode(generator, node) {
  1758. const { helper, needIndent } = generator;
  1759. if (node.cases.length > 1) {
  1760. generator.push(`${helper("plural" /* PLURAL */)}([`);
  1761. generator.indent(needIndent());
  1762. const length = node.cases.length;
  1763. for (let i = 0; i < length; i++) {
  1764. generateNode(generator, node.cases[i]);
  1765. if (i === length - 1) {
  1766. break;
  1767. }
  1768. generator.push(', ');
  1769. }
  1770. generator.deindent(needIndent());
  1771. generator.push(`])`);
  1772. }
  1773. }
  1774. function generateResource(generator, node) {
  1775. if (node.body) {
  1776. generateNode(generator, node.body);
  1777. }
  1778. else {
  1779. generator.push('null');
  1780. }
  1781. }
  1782. function generateNode(generator, node) {
  1783. const { helper } = generator;
  1784. switch (node.type) {
  1785. case 0 /* Resource */:
  1786. generateResource(generator, node);
  1787. break;
  1788. case 1 /* Plural */:
  1789. generatePluralNode(generator, node);
  1790. break;
  1791. case 2 /* Message */:
  1792. generateMessageNode(generator, node);
  1793. break;
  1794. case 6 /* Linked */:
  1795. generateLinkedNode(generator, node);
  1796. break;
  1797. case 8 /* LinkedModifier */:
  1798. generator.push(JSON.stringify(node.value), node);
  1799. break;
  1800. case 7 /* LinkedKey */:
  1801. generator.push(JSON.stringify(node.value), node);
  1802. break;
  1803. case 5 /* List */:
  1804. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
  1805. break;
  1806. case 4 /* Named */:
  1807. generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1808. break;
  1809. case 9 /* Literal */:
  1810. generator.push(JSON.stringify(node.value), node);
  1811. break;
  1812. case 3 /* Text */:
  1813. generator.push(JSON.stringify(node.value), node);
  1814. break;
  1815. default:
  1816. {
  1817. throw new Error(`unhandled codegen node type: ${node.type}`);
  1818. }
  1819. }
  1820. }
  1821. // generate code from AST
  1822. const generate = (ast, options = {} // eslint-disable-line
  1823. ) => {
  1824. const mode = isString(options.mode) ? options.mode : 'normal';
  1825. const filename = isString(options.filename)
  1826. ? options.filename
  1827. : 'message.intl';
  1828. const sourceMap = !!options.sourceMap;
  1829. // prettier-ignore
  1830. const breakLineCode = options.breakLineCode != null
  1831. ? options.breakLineCode
  1832. : mode === 'arrow'
  1833. ? ';'
  1834. : '\n';
  1835. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1836. const helpers = ast.helpers || [];
  1837. const generator = createCodeGenerator(ast, {
  1838. mode,
  1839. filename,
  1840. sourceMap,
  1841. breakLineCode,
  1842. needIndent
  1843. });
  1844. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1845. generator.indent(needIndent);
  1846. if (helpers.length > 0) {
  1847. generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
  1848. generator.newline();
  1849. }
  1850. generator.push(`return `);
  1851. generateNode(generator, ast);
  1852. generator.deindent(needIndent);
  1853. generator.push(`}`);
  1854. const { code, map } = generator.context();
  1855. return {
  1856. ast,
  1857. code,
  1858. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1859. };
  1860. };
  1861. function baseCompile(source, options = {}) {
  1862. const assignedOptions = assign({}, options);
  1863. // parse source codes
  1864. const parser = createParser(assignedOptions);
  1865. const ast = parser.parse(source);
  1866. // transform ASTs
  1867. transform(ast, assignedOptions);
  1868. // generate javascript codes
  1869. return generate(ast, assignedOptions);
  1870. }
  1871. const IntlifyDevToolsHooks = {
  1872. I18nInit: 'i18n:init',
  1873. FunctionTranslate: 'function:translate'
  1874. };
  1875. let devtools = null;
  1876. function setDevToolsHook(hook) {
  1877. devtools = hook;
  1878. }
  1879. function initI18nDevTools(i18n, version, meta) {
  1880. // TODO: queue if devtools is undefined
  1881. devtools &&
  1882. devtools.emit(IntlifyDevToolsHooks.I18nInit, {
  1883. timestamp: Date.now(),
  1884. i18n,
  1885. version,
  1886. meta
  1887. });
  1888. }
  1889. const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
  1890. function createDevToolsHook(hook) {
  1891. return (payloads) => devtools && devtools.emit(hook, payloads);
  1892. }
  1893. /** @internal */
  1894. const warnMessages$1 = {
  1895. [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
  1896. [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
  1897. [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  1898. [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
  1899. [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  1900. [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
  1901. };
  1902. function getWarnMessage$1(code, ...args) {
  1903. return format(warnMessages$1[code], ...args);
  1904. }
  1905. /**
  1906. * Intlify core-base version
  1907. * @internal
  1908. */
  1909. const VERSION$1 = '9.1.9';
  1910. const NOT_REOSLVED = -1;
  1911. const MISSING_RESOLVE_VALUE = '';
  1912. function getDefaultLinkedModifiers() {
  1913. return {
  1914. upper: (val) => (isString(val) ? val.toUpperCase() : val),
  1915. lower: (val) => (isString(val) ? val.toLowerCase() : val),
  1916. // prettier-ignore
  1917. capitalize: (val) => (isString(val)
  1918. ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
  1919. : val)
  1920. };
  1921. }
  1922. let _compiler;
  1923. function registerMessageCompiler(compiler) {
  1924. _compiler = compiler;
  1925. }
  1926. // Additional Meta for Intlify DevTools
  1927. let _additionalMeta = null;
  1928. const setAdditionalMeta = /* #__PURE__*/ (meta) => {
  1929. _additionalMeta = meta;
  1930. };
  1931. const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
  1932. // ID for CoreContext
  1933. let _cid = 0;
  1934. function createCoreContext(options = {}) {
  1935. // setup options
  1936. const version = isString(options.version) ? options.version : VERSION$1;
  1937. const locale = isString(options.locale) ? options.locale : 'en-US';
  1938. const fallbackLocale = isArray(options.fallbackLocale) ||
  1939. isPlainObject(options.fallbackLocale) ||
  1940. isString(options.fallbackLocale) ||
  1941. options.fallbackLocale === false
  1942. ? options.fallbackLocale
  1943. : locale;
  1944. const messages = isPlainObject(options.messages)
  1945. ? options.messages
  1946. : { [locale]: {} };
  1947. const datetimeFormats = isPlainObject(options.datetimeFormats)
  1948. ? options.datetimeFormats
  1949. : { [locale]: {} };
  1950. const numberFormats = isPlainObject(options.numberFormats)
  1951. ? options.numberFormats
  1952. : { [locale]: {} };
  1953. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  1954. const pluralRules = options.pluralRules || {};
  1955. const missing = isFunction(options.missing) ? options.missing : null;
  1956. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1957. ? options.missingWarn
  1958. : true;
  1959. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1960. ? options.fallbackWarn
  1961. : true;
  1962. const fallbackFormat = !!options.fallbackFormat;
  1963. const unresolving = !!options.unresolving;
  1964. const postTranslation = isFunction(options.postTranslation)
  1965. ? options.postTranslation
  1966. : null;
  1967. const processor = isPlainObject(options.processor) ? options.processor : null;
  1968. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1969. ? options.warnHtmlMessage
  1970. : true;
  1971. const escapeParameter = !!options.escapeParameter;
  1972. const messageCompiler = isFunction(options.messageCompiler)
  1973. ? options.messageCompiler
  1974. : _compiler;
  1975. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  1976. // setup internal options
  1977. const internalOptions = options;
  1978. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  1979. ? internalOptions.__datetimeFormatters
  1980. : new Map();
  1981. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  1982. ? internalOptions.__numberFormatters
  1983. : new Map();
  1984. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  1985. _cid++;
  1986. const context = {
  1987. version,
  1988. cid: _cid,
  1989. locale,
  1990. fallbackLocale,
  1991. messages,
  1992. datetimeFormats,
  1993. numberFormats,
  1994. modifiers,
  1995. pluralRules,
  1996. missing,
  1997. missingWarn,
  1998. fallbackWarn,
  1999. fallbackFormat,
  2000. unresolving,
  2001. postTranslation,
  2002. processor,
  2003. warnHtmlMessage,
  2004. escapeParameter,
  2005. messageCompiler,
  2006. onWarn,
  2007. __datetimeFormatters,
  2008. __numberFormatters,
  2009. __meta
  2010. };
  2011. // for vue-devtools timeline event
  2012. {
  2013. context.__v_emitter =
  2014. internalOptions.__v_emitter != null
  2015. ? internalOptions.__v_emitter
  2016. : undefined;
  2017. }
  2018. // NOTE: experimental !!
  2019. {
  2020. initI18nDevTools(context, version, __meta);
  2021. }
  2022. return context;
  2023. }
  2024. /** @internal */
  2025. function isTranslateFallbackWarn(fallback, key) {
  2026. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2027. }
  2028. /** @internal */
  2029. function isTranslateMissingWarn(missing, key) {
  2030. return missing instanceof RegExp ? missing.test(key) : missing;
  2031. }
  2032. /** @internal */
  2033. function handleMissing(context, key, locale, missingWarn, type) {
  2034. const { missing, onWarn } = context;
  2035. // for vue-devtools timeline event
  2036. {
  2037. const emitter = context.__v_emitter;
  2038. if (emitter) {
  2039. emitter.emit("missing" /* MISSING */, {
  2040. locale,
  2041. key,
  2042. type,
  2043. groupId: `${type}:${key}`
  2044. });
  2045. }
  2046. }
  2047. if (missing !== null) {
  2048. const ret = missing(context, locale, key, type);
  2049. return isString(ret) ? ret : key;
  2050. }
  2051. else {
  2052. if (isTranslateMissingWarn(missingWarn, key)) {
  2053. onWarn(getWarnMessage$1(0 /* NOT_FOUND_KEY */, { key, locale }));
  2054. }
  2055. return key;
  2056. }
  2057. }
  2058. /** @internal */
  2059. function getLocaleChain(ctx, fallback, start) {
  2060. const context = ctx;
  2061. if (!context.__localeChainCache) {
  2062. context.__localeChainCache = new Map();
  2063. }
  2064. let chain = context.__localeChainCache.get(start);
  2065. if (!chain) {
  2066. chain = [];
  2067. // first block defined by start
  2068. let block = [start];
  2069. // while any intervening block found
  2070. while (isArray(block)) {
  2071. block = appendBlockToChain(chain, block, fallback);
  2072. }
  2073. // prettier-ignore
  2074. // last block defined by default
  2075. const defaults = isArray(fallback)
  2076. ? fallback
  2077. : isPlainObject(fallback)
  2078. ? fallback['default']
  2079. ? fallback['default']
  2080. : null
  2081. : fallback;
  2082. // convert defaults to array
  2083. block = isString(defaults) ? [defaults] : defaults;
  2084. if (isArray(block)) {
  2085. appendBlockToChain(chain, block, false);
  2086. }
  2087. context.__localeChainCache.set(start, chain);
  2088. }
  2089. return chain;
  2090. }
  2091. function appendBlockToChain(chain, block, blocks) {
  2092. let follow = true;
  2093. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2094. const locale = block[i];
  2095. if (isString(locale)) {
  2096. follow = appendLocaleToChain(chain, block[i], blocks);
  2097. }
  2098. }
  2099. return follow;
  2100. }
  2101. function appendLocaleToChain(chain, locale, blocks) {
  2102. let follow;
  2103. const tokens = locale.split('-');
  2104. do {
  2105. const target = tokens.join('-');
  2106. follow = appendItemToChain(chain, target, blocks);
  2107. tokens.splice(-1, 1);
  2108. } while (tokens.length && follow === true);
  2109. return follow;
  2110. }
  2111. function appendItemToChain(chain, target, blocks) {
  2112. let follow = false;
  2113. if (!chain.includes(target)) {
  2114. follow = true;
  2115. if (target) {
  2116. follow = target[target.length - 1] !== '!';
  2117. const locale = target.replace(/!/g, '');
  2118. chain.push(locale);
  2119. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2120. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2121. ) {
  2122. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2123. follow = blocks[locale];
  2124. }
  2125. }
  2126. }
  2127. return follow;
  2128. }
  2129. /** @internal */
  2130. function updateFallbackLocale(ctx, locale, fallback) {
  2131. const context = ctx;
  2132. context.__localeChainCache = new Map();
  2133. getLocaleChain(ctx, fallback, locale);
  2134. }
  2135. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  2136. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  2137. function checkHtmlMessage(source, options) {
  2138. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2139. ? options.warnHtmlMessage
  2140. : true;
  2141. if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
  2142. warn(format(WARN_MESSAGE, { source }));
  2143. }
  2144. }
  2145. const defaultOnCacheKey = (source) => source;
  2146. let compileCache = Object.create(null);
  2147. function compileToFunction(source, options = {}) {
  2148. {
  2149. // check HTML message
  2150. checkHtmlMessage(source, options);
  2151. // check caches
  2152. const onCacheKey = options.onCacheKey || defaultOnCacheKey;
  2153. const key = onCacheKey(source);
  2154. const cached = compileCache[key];
  2155. if (cached) {
  2156. return cached;
  2157. }
  2158. // compile error detecting
  2159. let occurred = false;
  2160. const onError = options.onError || defaultOnError;
  2161. options.onError = (err) => {
  2162. occurred = true;
  2163. onError(err);
  2164. };
  2165. // compile
  2166. const { code } = baseCompile(source, options);
  2167. // evaluate function
  2168. const msg = new Function(`return ${code}`)();
  2169. // if occurred compile error, don't cache
  2170. return !occurred ? (compileCache[key] = msg) : msg;
  2171. }
  2172. }
  2173. function createCoreError(code) {
  2174. return createCompileError(code, null, { messages: errorMessages$1 } );
  2175. }
  2176. /** @internal */
  2177. const errorMessages$1 = {
  2178. [14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
  2179. [15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
  2180. 'Make sure your Date represents a valid date.',
  2181. [16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
  2182. };
  2183. const NOOP_MESSAGE_FUNCTION = () => '';
  2184. const isMessageFunction = (val) => isFunction(val);
  2185. // implementation of `translate` function
  2186. function translate(context, ...args) {
  2187. const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
  2188. const [key, options] = parseTranslateArgs(...args);
  2189. const missingWarn = isBoolean(options.missingWarn)
  2190. ? options.missingWarn
  2191. : context.missingWarn;
  2192. const fallbackWarn = isBoolean(options.fallbackWarn)
  2193. ? options.fallbackWarn
  2194. : context.fallbackWarn;
  2195. const escapeParameter = isBoolean(options.escapeParameter)
  2196. ? options.escapeParameter
  2197. : context.escapeParameter;
  2198. const resolvedMessage = !!options.resolvedMessage;
  2199. // prettier-ignore
  2200. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  2201. ? !isBoolean(options.default)
  2202. ? options.default
  2203. : key
  2204. : fallbackFormat // default by `fallbackFormat` option
  2205. ? key
  2206. : '';
  2207. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  2208. const locale = isString(options.locale) ? options.locale : context.locale;
  2209. // escape params
  2210. escapeParameter && escapeParams(options);
  2211. // resolve message format
  2212. // eslint-disable-next-line prefer-const
  2213. let [format, targetLocale, message] = !resolvedMessage
  2214. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  2215. : [
  2216. key,
  2217. locale,
  2218. messages[locale] || {}
  2219. ];
  2220. // if you use default message, set it as message format!
  2221. let cacheBaseKey = key;
  2222. if (!resolvedMessage &&
  2223. !(isString(format) || isMessageFunction(format))) {
  2224. if (enableDefaultMsg) {
  2225. format = defaultMsgOrKey;
  2226. cacheBaseKey = format;
  2227. }
  2228. }
  2229. // checking message format and target locale
  2230. if (!resolvedMessage &&
  2231. (!(isString(format) || isMessageFunction(format)) ||
  2232. !isString(targetLocale))) {
  2233. return unresolving ? NOT_REOSLVED : key;
  2234. }
  2235. if (isString(format) && context.messageCompiler == null) {
  2236. warn(`The message format compilation is not supported in this build. ` +
  2237. `Because message compiler isn't included. ` +
  2238. `You need to pre-compilation all message format. ` +
  2239. `So translate function return '${key}'.`);
  2240. return key;
  2241. }
  2242. // setup compile error detecting
  2243. let occurred = false;
  2244. const errorDetector = () => {
  2245. occurred = true;
  2246. };
  2247. // compile message format
  2248. const msg = !isMessageFunction(format)
  2249. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
  2250. : format;
  2251. // if occurred compile error, return the message format
  2252. if (occurred) {
  2253. return format;
  2254. }
  2255. // evaluate message with context
  2256. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  2257. const msgContext = createMessageContext(ctxOptions);
  2258. const messaged = evaluateMessage(context, msg, msgContext);
  2259. // if use post translation option, proceed it with handler
  2260. const ret = postTranslation ? postTranslation(messaged) : messaged;
  2261. // NOTE: experimental !!
  2262. {
  2263. // prettier-ignore
  2264. const payloads = {
  2265. timestamp: Date.now(),
  2266. key: isString(key)
  2267. ? key
  2268. : isMessageFunction(format)
  2269. ? format.key
  2270. : '',
  2271. locale: targetLocale || (isMessageFunction(format)
  2272. ? format.locale
  2273. : ''),
  2274. format: isString(format)
  2275. ? format
  2276. : isMessageFunction(format)
  2277. ? format.source
  2278. : '',
  2279. message: ret
  2280. };
  2281. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  2282. translateDevTools(payloads);
  2283. }
  2284. return ret;
  2285. }
  2286. function escapeParams(options) {
  2287. if (isArray(options.list)) {
  2288. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  2289. }
  2290. else if (isObject(options.named)) {
  2291. Object.keys(options.named).forEach(key => {
  2292. if (isString(options.named[key])) {
  2293. options.named[key] = escapeHtml(options.named[key]);
  2294. }
  2295. });
  2296. }
  2297. }
  2298. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  2299. const { messages, onWarn } = context;
  2300. const locales = getLocaleChain(context, fallbackLocale, locale);
  2301. let message = {};
  2302. let targetLocale;
  2303. let format = null;
  2304. let from = locale;
  2305. let to = null;
  2306. const type = 'translate';
  2307. for (let i = 0; i < locales.length; i++) {
  2308. targetLocale = to = locales[i];
  2309. if (locale !== targetLocale &&
  2310. isTranslateFallbackWarn(fallbackWarn, key)) {
  2311. onWarn(getWarnMessage$1(1 /* FALLBACK_TO_TRANSLATE */, {
  2312. key,
  2313. target: targetLocale
  2314. }));
  2315. }
  2316. // for vue-devtools timeline event
  2317. if (locale !== targetLocale) {
  2318. const emitter = context.__v_emitter;
  2319. if (emitter) {
  2320. emitter.emit("fallback" /* FALBACK */, {
  2321. type,
  2322. key,
  2323. from,
  2324. to,
  2325. groupId: `${type}:${key}`
  2326. });
  2327. }
  2328. }
  2329. message =
  2330. messages[targetLocale] || {};
  2331. // for vue-devtools timeline event
  2332. let start = null;
  2333. let startTag;
  2334. let endTag;
  2335. if (inBrowser) {
  2336. start = window.performance.now();
  2337. startTag = 'intlify-message-resolve-start';
  2338. endTag = 'intlify-message-resolve-end';
  2339. mark && mark(startTag);
  2340. }
  2341. if ((format = resolveValue(message, key)) === null) {
  2342. // if null, resolve with object key path
  2343. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  2344. }
  2345. // for vue-devtools timeline event
  2346. if (inBrowser) {
  2347. const end = window.performance.now();
  2348. const emitter = context.__v_emitter;
  2349. if (emitter && start && format) {
  2350. emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
  2351. type: "message-resolve" /* MESSAGE_RESOLVE */,
  2352. key,
  2353. message: format,
  2354. time: end - start,
  2355. groupId: `${type}:${key}`
  2356. });
  2357. }
  2358. if (startTag && endTag && mark && measure) {
  2359. mark(endTag);
  2360. measure('intlify message resolve', startTag, endTag);
  2361. }
  2362. }
  2363. if (isString(format) || isFunction(format))
  2364. break;
  2365. const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
  2366. if (missingRet !== key) {
  2367. format = missingRet;
  2368. }
  2369. from = to;
  2370. }
  2371. return [format, targetLocale, message];
  2372. }
  2373. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
  2374. const { messageCompiler, warnHtmlMessage } = context;
  2375. if (isMessageFunction(format)) {
  2376. const msg = format;
  2377. msg.locale = msg.locale || targetLocale;
  2378. msg.key = msg.key || key;
  2379. return msg;
  2380. }
  2381. // for vue-devtools timeline event
  2382. let start = null;
  2383. let startTag;
  2384. let endTag;
  2385. if (inBrowser) {
  2386. start = window.performance.now();
  2387. startTag = 'intlify-message-compilation-start';
  2388. endTag = 'intlify-message-compilation-end';
  2389. mark && mark(startTag);
  2390. }
  2391. const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
  2392. // for vue-devtools timeline event
  2393. if (inBrowser) {
  2394. const end = window.performance.now();
  2395. const emitter = context.__v_emitter;
  2396. if (emitter && start) {
  2397. emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
  2398. type: "message-compilation" /* MESSAGE_COMPILATION */,
  2399. message: format,
  2400. time: end - start,
  2401. groupId: `${'translate'}:${key}`
  2402. });
  2403. }
  2404. if (startTag && endTag && mark && measure) {
  2405. mark(endTag);
  2406. measure('intlify message compilation', startTag, endTag);
  2407. }
  2408. }
  2409. msg.locale = targetLocale;
  2410. msg.key = key;
  2411. msg.source = format;
  2412. return msg;
  2413. }
  2414. function evaluateMessage(context, msg, msgCtx) {
  2415. // for vue-devtools timeline event
  2416. let start = null;
  2417. let startTag;
  2418. let endTag;
  2419. if (inBrowser) {
  2420. start = window.performance.now();
  2421. startTag = 'intlify-message-evaluation-start';
  2422. endTag = 'intlify-message-evaluation-end';
  2423. mark && mark(startTag);
  2424. }
  2425. const messaged = msg(msgCtx);
  2426. // for vue-devtools timeline event
  2427. if (inBrowser) {
  2428. const end = window.performance.now();
  2429. const emitter = context.__v_emitter;
  2430. if (emitter && start) {
  2431. emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
  2432. type: "message-evaluation" /* MESSAGE_EVALUATION */,
  2433. value: messaged,
  2434. time: end - start,
  2435. groupId: `${'translate'}:${msg.key}`
  2436. });
  2437. }
  2438. if (startTag && endTag && mark && measure) {
  2439. mark(endTag);
  2440. measure('intlify message evaluation', startTag, endTag);
  2441. }
  2442. }
  2443. return messaged;
  2444. }
  2445. /** @internal */
  2446. function parseTranslateArgs(...args) {
  2447. const [arg1, arg2, arg3] = args;
  2448. const options = {};
  2449. if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
  2450. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2451. }
  2452. // prettier-ignore
  2453. const key = isNumber(arg1)
  2454. ? String(arg1)
  2455. : isMessageFunction(arg1)
  2456. ? arg1
  2457. : arg1;
  2458. if (isNumber(arg2)) {
  2459. options.plural = arg2;
  2460. }
  2461. else if (isString(arg2)) {
  2462. options.default = arg2;
  2463. }
  2464. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  2465. options.named = arg2;
  2466. }
  2467. else if (isArray(arg2)) {
  2468. options.list = arg2;
  2469. }
  2470. if (isNumber(arg3)) {
  2471. options.plural = arg3;
  2472. }
  2473. else if (isString(arg3)) {
  2474. options.default = arg3;
  2475. }
  2476. else if (isPlainObject(arg3)) {
  2477. assign(options, arg3);
  2478. }
  2479. return [key, options];
  2480. }
  2481. function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
  2482. return {
  2483. warnHtmlMessage,
  2484. onError: (err) => {
  2485. errorDetector && errorDetector(err);
  2486. {
  2487. const message = `Message compilation error: ${err.message}`;
  2488. const codeFrame = err.location &&
  2489. generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
  2490. const emitter = context
  2491. .__v_emitter;
  2492. if (emitter) {
  2493. emitter.emit("compile-error" /* COMPILE_ERROR */, {
  2494. message: source,
  2495. error: err.message,
  2496. start: err.location && err.location.start.offset,
  2497. end: err.location && err.location.end.offset,
  2498. groupId: `${'translate'}:${key}`
  2499. });
  2500. }
  2501. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  2502. }
  2503. },
  2504. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  2505. };
  2506. }
  2507. function getMessageContextOptions(context, locale, message, options) {
  2508. const { modifiers, pluralRules } = context;
  2509. const resolveMessage = (key) => {
  2510. const val = resolveValue(message, key);
  2511. if (isString(val)) {
  2512. let occurred = false;
  2513. const errorDetector = () => {
  2514. occurred = true;
  2515. };
  2516. const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
  2517. return !occurred
  2518. ? msg
  2519. : NOOP_MESSAGE_FUNCTION;
  2520. }
  2521. else if (isMessageFunction(val)) {
  2522. return val;
  2523. }
  2524. else {
  2525. // TODO: should be implemented warning message
  2526. return NOOP_MESSAGE_FUNCTION;
  2527. }
  2528. };
  2529. const ctxOptions = {
  2530. locale,
  2531. modifiers,
  2532. pluralRules,
  2533. messages: resolveMessage
  2534. };
  2535. if (context.processor) {
  2536. ctxOptions.processor = context.processor;
  2537. }
  2538. if (options.list) {
  2539. ctxOptions.list = options.list;
  2540. }
  2541. if (options.named) {
  2542. ctxOptions.named = options.named;
  2543. }
  2544. if (isNumber(options.plural)) {
  2545. ctxOptions.pluralIndex = options.plural;
  2546. }
  2547. return ctxOptions;
  2548. }
  2549. const intlDefined = typeof Intl !== 'undefined';
  2550. const Availabilities = {
  2551. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  2552. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  2553. };
  2554. // implementation of `datetime` function
  2555. function datetime(context, ...args) {
  2556. const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
  2557. const { __datetimeFormatters } = context;
  2558. if (!Availabilities.dateTimeFormat) {
  2559. onWarn(getWarnMessage$1(4 /* CANNOT_FORMAT_DATE */));
  2560. return MISSING_RESOLVE_VALUE;
  2561. }
  2562. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  2563. const missingWarn = isBoolean(options.missingWarn)
  2564. ? options.missingWarn
  2565. : context.missingWarn;
  2566. const fallbackWarn = isBoolean(options.fallbackWarn)
  2567. ? options.fallbackWarn
  2568. : context.fallbackWarn;
  2569. const part = !!options.part;
  2570. const locale = isString(options.locale) ? options.locale : context.locale;
  2571. const locales = getLocaleChain(context, fallbackLocale, locale);
  2572. if (!isString(key) || key === '') {
  2573. return new Intl.DateTimeFormat(locale).format(value);
  2574. }
  2575. // resolve format
  2576. let datetimeFormat = {};
  2577. let targetLocale;
  2578. let format = null;
  2579. let from = locale;
  2580. let to = null;
  2581. const type = 'datetime format';
  2582. for (let i = 0; i < locales.length; i++) {
  2583. targetLocale = to = locales[i];
  2584. if (locale !== targetLocale &&
  2585. isTranslateFallbackWarn(fallbackWarn, key)) {
  2586. onWarn(getWarnMessage$1(5 /* FALLBACK_TO_DATE_FORMAT */, {
  2587. key,
  2588. target: targetLocale
  2589. }));
  2590. }
  2591. // for vue-devtools timeline event
  2592. if (locale !== targetLocale) {
  2593. const emitter = context.__v_emitter;
  2594. if (emitter) {
  2595. emitter.emit("fallback" /* FALBACK */, {
  2596. type,
  2597. key,
  2598. from,
  2599. to,
  2600. groupId: `${type}:${key}`
  2601. });
  2602. }
  2603. }
  2604. datetimeFormat =
  2605. datetimeFormats[targetLocale] || {};
  2606. format = datetimeFormat[key];
  2607. if (isPlainObject(format))
  2608. break;
  2609. handleMissing(context, key, targetLocale, missingWarn, type);
  2610. from = to;
  2611. }
  2612. // checking format and target locale
  2613. if (!isPlainObject(format) || !isString(targetLocale)) {
  2614. return unresolving ? NOT_REOSLVED : key;
  2615. }
  2616. let id = `${targetLocale}__${key}`;
  2617. if (!isEmptyObject(overrides)) {
  2618. id = `${id}__${JSON.stringify(overrides)}`;
  2619. }
  2620. let formatter = __datetimeFormatters.get(id);
  2621. if (!formatter) {
  2622. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  2623. __datetimeFormatters.set(id, formatter);
  2624. }
  2625. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2626. }
  2627. /** @internal */
  2628. function parseDateTimeArgs(...args) {
  2629. const [arg1, arg2, arg3, arg4] = args;
  2630. let options = {};
  2631. let overrides = {};
  2632. let value;
  2633. if (isString(arg1)) {
  2634. // Only allow ISO strings - other date formats are often supported,
  2635. // but may cause different results in different browsers.
  2636. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
  2637. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  2638. }
  2639. value = new Date(arg1);
  2640. try {
  2641. // This will fail if the date is not valid
  2642. value.toISOString();
  2643. }
  2644. catch (e) {
  2645. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  2646. }
  2647. }
  2648. else if (isDate(arg1)) {
  2649. if (isNaN(arg1.getTime())) {
  2650. throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
  2651. }
  2652. value = arg1;
  2653. }
  2654. else if (isNumber(arg1)) {
  2655. value = arg1;
  2656. }
  2657. else {
  2658. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2659. }
  2660. if (isString(arg2)) {
  2661. options.key = arg2;
  2662. }
  2663. else if (isPlainObject(arg2)) {
  2664. options = arg2;
  2665. }
  2666. if (isString(arg3)) {
  2667. options.locale = arg3;
  2668. }
  2669. else if (isPlainObject(arg3)) {
  2670. overrides = arg3;
  2671. }
  2672. if (isPlainObject(arg4)) {
  2673. overrides = arg4;
  2674. }
  2675. return [options.key || '', value, options, overrides];
  2676. }
  2677. /** @internal */
  2678. function clearDateTimeFormat(ctx, locale, format) {
  2679. const context = ctx;
  2680. for (const key in format) {
  2681. const id = `${locale}__${key}`;
  2682. if (!context.__datetimeFormatters.has(id)) {
  2683. continue;
  2684. }
  2685. context.__datetimeFormatters.delete(id);
  2686. }
  2687. }
  2688. // implementation of `number` function
  2689. function number(context, ...args) {
  2690. const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
  2691. const { __numberFormatters } = context;
  2692. if (!Availabilities.numberFormat) {
  2693. onWarn(getWarnMessage$1(2 /* CANNOT_FORMAT_NUMBER */));
  2694. return MISSING_RESOLVE_VALUE;
  2695. }
  2696. const [key, value, options, overrides] = parseNumberArgs(...args);
  2697. const missingWarn = isBoolean(options.missingWarn)
  2698. ? options.missingWarn
  2699. : context.missingWarn;
  2700. const fallbackWarn = isBoolean(options.fallbackWarn)
  2701. ? options.fallbackWarn
  2702. : context.fallbackWarn;
  2703. const part = !!options.part;
  2704. const locale = isString(options.locale) ? options.locale : context.locale;
  2705. const locales = getLocaleChain(context, fallbackLocale, locale);
  2706. if (!isString(key) || key === '') {
  2707. return new Intl.NumberFormat(locale).format(value);
  2708. }
  2709. // resolve format
  2710. let numberFormat = {};
  2711. let targetLocale;
  2712. let format = null;
  2713. let from = locale;
  2714. let to = null;
  2715. const type = 'number format';
  2716. for (let i = 0; i < locales.length; i++) {
  2717. targetLocale = to = locales[i];
  2718. if (locale !== targetLocale &&
  2719. isTranslateFallbackWarn(fallbackWarn, key)) {
  2720. onWarn(getWarnMessage$1(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
  2721. key,
  2722. target: targetLocale
  2723. }));
  2724. }
  2725. // for vue-devtools timeline event
  2726. if (locale !== targetLocale) {
  2727. const emitter = context.__v_emitter;
  2728. if (emitter) {
  2729. emitter.emit("fallback" /* FALBACK */, {
  2730. type,
  2731. key,
  2732. from,
  2733. to,
  2734. groupId: `${type}:${key}`
  2735. });
  2736. }
  2737. }
  2738. numberFormat =
  2739. numberFormats[targetLocale] || {};
  2740. format = numberFormat[key];
  2741. if (isPlainObject(format))
  2742. break;
  2743. handleMissing(context, key, targetLocale, missingWarn, type);
  2744. from = to;
  2745. }
  2746. // checking format and target locale
  2747. if (!isPlainObject(format) || !isString(targetLocale)) {
  2748. return unresolving ? NOT_REOSLVED : key;
  2749. }
  2750. let id = `${targetLocale}__${key}`;
  2751. if (!isEmptyObject(overrides)) {
  2752. id = `${id}__${JSON.stringify(overrides)}`;
  2753. }
  2754. let formatter = __numberFormatters.get(id);
  2755. if (!formatter) {
  2756. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  2757. __numberFormatters.set(id, formatter);
  2758. }
  2759. return !part ? formatter.format(value) : formatter.formatToParts(value);
  2760. }
  2761. /** @internal */
  2762. function parseNumberArgs(...args) {
  2763. const [arg1, arg2, arg3, arg4] = args;
  2764. let options = {};
  2765. let overrides = {};
  2766. if (!isNumber(arg1)) {
  2767. throw createCoreError(14 /* INVALID_ARGUMENT */);
  2768. }
  2769. const value = arg1;
  2770. if (isString(arg2)) {
  2771. options.key = arg2;
  2772. }
  2773. else if (isPlainObject(arg2)) {
  2774. options = arg2;
  2775. }
  2776. if (isString(arg3)) {
  2777. options.locale = arg3;
  2778. }
  2779. else if (isPlainObject(arg3)) {
  2780. overrides = arg3;
  2781. }
  2782. if (isPlainObject(arg4)) {
  2783. overrides = arg4;
  2784. }
  2785. return [options.key || '', value, options, overrides];
  2786. }
  2787. /** @internal */
  2788. function clearNumberFormat(ctx, locale, format) {
  2789. const context = ctx;
  2790. for (const key in format) {
  2791. const id = `${locale}__${key}`;
  2792. if (!context.__numberFormatters.has(id)) {
  2793. continue;
  2794. }
  2795. context.__numberFormatters.delete(id);
  2796. }
  2797. }
  2798. /**
  2799. * Vue I18n Version
  2800. *
  2801. * @remarks
  2802. * Semver format. Same format as the package.json `version` field.
  2803. *
  2804. * @VueI18nGeneral
  2805. */
  2806. const VERSION = '9.1.9';
  2807. /**
  2808. * This is only called development env
  2809. * istanbul-ignore-next
  2810. */
  2811. function initDev() {
  2812. {
  2813. {
  2814. console.info(`You are running a development build of vue-i18n.\n` +
  2815. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  2816. }
  2817. }
  2818. }
  2819. const warnMessages = {
  2820. [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
  2821. [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`,
  2822. [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`,
  2823. [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`,
  2824. [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`,
  2825. [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  2826. [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
  2827. };
  2828. function getWarnMessage(code, ...args) {
  2829. return format(warnMessages[code], ...args);
  2830. }
  2831. function createI18nError(code, ...args) {
  2832. return createCompileError(code, null, { messages: errorMessages, args } );
  2833. }
  2834. const errorMessages = {
  2835. [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
  2836. [15 /* INVALID_ARGUMENT */]: 'Invalid argument',
  2837. [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
  2838. [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
  2839. [22 /* UNEXPECTED_ERROR */]: 'Unexpected error',
  2840. [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
  2841. [19 /* REQUIRED_VALUE */]: `Required in value: {0}`,
  2842. [20 /* INVALID_VALUE */]: `Invalid value`,
  2843. [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
  2844. };
  2845. const DEVTOOLS_META = '__INTLIFY_META__';
  2846. const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
  2847. const DatetimePartsSymbol = makeSymbol('__datetimeParts');
  2848. const NumberPartsSymbol = makeSymbol('__numberParts');
  2849. const EnableEmitter = makeSymbol('__enableEmitter');
  2850. const DisableEmitter = makeSymbol('__disableEmitter');
  2851. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  2852. const InejctWithOption = makeSymbol('__injectWithOption');
  2853. let composerID = 0;
  2854. function defineCoreMissingHandler(missing) {
  2855. return ((ctx, locale, key, type) => {
  2856. return missing(locale, key, vue.getCurrentInstance() || undefined, type);
  2857. });
  2858. }
  2859. function getLocaleMessages(locale, options) {
  2860. const { messages, __i18n } = options;
  2861. // prettier-ignore
  2862. const ret = isPlainObject(messages)
  2863. ? messages
  2864. : isArray(__i18n)
  2865. ? {}
  2866. : { [locale]: {} };
  2867. // merge locale messages of i18n custom block
  2868. if (isArray(__i18n)) {
  2869. __i18n.forEach(({ locale, resource }) => {
  2870. if (locale) {
  2871. ret[locale] = ret[locale] || {};
  2872. deepCopy(resource, ret[locale]);
  2873. }
  2874. else {
  2875. deepCopy(resource, ret);
  2876. }
  2877. });
  2878. }
  2879. // handle messages for flat json
  2880. if (options.flatJson) {
  2881. for (const key in ret) {
  2882. if (hasOwn(ret, key)) {
  2883. handleFlatJson(ret[key]);
  2884. }
  2885. }
  2886. }
  2887. return ret;
  2888. }
  2889. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  2890. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2891. function deepCopy(src, des) {
  2892. // src and des should both be objects, and non of then can be a array
  2893. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  2894. throw createI18nError(20 /* INVALID_VALUE */);
  2895. }
  2896. for (const key in src) {
  2897. if (hasOwn(src, key)) {
  2898. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  2899. // replace with src[key] when:
  2900. // src[key] or des[key] is not a object, or
  2901. // src[key] or des[key] is a array
  2902. des[key] = src[key];
  2903. }
  2904. else {
  2905. // src[key] and des[key] are both object, merge them
  2906. deepCopy(src[key], des[key]);
  2907. }
  2908. }
  2909. }
  2910. }
  2911. // for Intlify DevTools
  2912. const getMetaInfo = /* #__PURE__*/ () => {
  2913. const instance = vue.getCurrentInstance();
  2914. return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any
  2915. ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any
  2916. : null;
  2917. };
  2918. /**
  2919. * Create composer interface factory
  2920. *
  2921. * @internal
  2922. */
  2923. function createComposer(options = {}) {
  2924. const { __root } = options;
  2925. const _isGlobal = __root === undefined;
  2926. let _inheritLocale = isBoolean(options.inheritLocale)
  2927. ? options.inheritLocale
  2928. : true;
  2929. const _locale = vue.ref(
  2930. // prettier-ignore
  2931. __root && _inheritLocale
  2932. ? __root.locale.value
  2933. : isString(options.locale)
  2934. ? options.locale
  2935. : 'en-US');
  2936. const _fallbackLocale = vue.ref(
  2937. // prettier-ignore
  2938. __root && _inheritLocale
  2939. ? __root.fallbackLocale.value
  2940. : isString(options.fallbackLocale) ||
  2941. isArray(options.fallbackLocale) ||
  2942. isPlainObject(options.fallbackLocale) ||
  2943. options.fallbackLocale === false
  2944. ? options.fallbackLocale
  2945. : _locale.value);
  2946. const _messages = vue.ref(getLocaleMessages(_locale.value, options));
  2947. const _datetimeFormats = vue.ref(isPlainObject(options.datetimeFormats)
  2948. ? options.datetimeFormats
  2949. : { [_locale.value]: {} });
  2950. const _numberFormats = vue.ref(isPlainObject(options.numberFormats)
  2951. ? options.numberFormats
  2952. : { [_locale.value]: {} });
  2953. // warning suppress options
  2954. // prettier-ignore
  2955. let _missingWarn = __root
  2956. ? __root.missingWarn
  2957. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2958. ? options.missingWarn
  2959. : true;
  2960. // prettier-ignore
  2961. let _fallbackWarn = __root
  2962. ? __root.fallbackWarn
  2963. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2964. ? options.fallbackWarn
  2965. : true;
  2966. // prettier-ignore
  2967. let _fallbackRoot = __root
  2968. ? __root.fallbackRoot
  2969. : isBoolean(options.fallbackRoot)
  2970. ? options.fallbackRoot
  2971. : true;
  2972. // configure fall back to root
  2973. let _fallbackFormat = !!options.fallbackFormat;
  2974. // runtime missing
  2975. let _missing = isFunction(options.missing) ? options.missing : null;
  2976. let _runtimeMissing = isFunction(options.missing)
  2977. ? defineCoreMissingHandler(options.missing)
  2978. : null;
  2979. // postTranslation handler
  2980. let _postTranslation = isFunction(options.postTranslation)
  2981. ? options.postTranslation
  2982. : null;
  2983. let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2984. ? options.warnHtmlMessage
  2985. : true;
  2986. let _escapeParameter = !!options.escapeParameter;
  2987. // custom linked modifiers
  2988. // prettier-ignore
  2989. const _modifiers = __root
  2990. ? __root.modifiers
  2991. : isPlainObject(options.modifiers)
  2992. ? options.modifiers
  2993. : {};
  2994. // pluralRules
  2995. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  2996. // runtime context
  2997. // eslint-disable-next-line prefer-const
  2998. let _context;
  2999. function getCoreContext() {
  3000. return createCoreContext({
  3001. version: VERSION,
  3002. locale: _locale.value,
  3003. fallbackLocale: _fallbackLocale.value,
  3004. messages: _messages.value,
  3005. datetimeFormats: _datetimeFormats.value,
  3006. numberFormats: _numberFormats.value,
  3007. modifiers: _modifiers,
  3008. pluralRules: _pluralRules,
  3009. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  3010. missingWarn: _missingWarn,
  3011. fallbackWarn: _fallbackWarn,
  3012. fallbackFormat: _fallbackFormat,
  3013. unresolving: true,
  3014. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  3015. warnHtmlMessage: _warnHtmlMessage,
  3016. escapeParameter: _escapeParameter,
  3017. __datetimeFormatters: isPlainObject(_context)
  3018. ? _context.__datetimeFormatters
  3019. : undefined,
  3020. __numberFormatters: isPlainObject(_context)
  3021. ? _context.__numberFormatters
  3022. : undefined,
  3023. __v_emitter: isPlainObject(_context)
  3024. ? _context.__v_emitter
  3025. : undefined,
  3026. __meta: { framework: 'vue' }
  3027. });
  3028. }
  3029. _context = getCoreContext();
  3030. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3031. // track reactivity
  3032. function trackReactivityValues() {
  3033. return [
  3034. _locale.value,
  3035. _fallbackLocale.value,
  3036. _messages.value,
  3037. _datetimeFormats.value,
  3038. _numberFormats.value
  3039. ];
  3040. }
  3041. // locale
  3042. const locale = vue.computed({
  3043. get: () => _locale.value,
  3044. set: val => {
  3045. _locale.value = val;
  3046. _context.locale = _locale.value;
  3047. }
  3048. });
  3049. // fallbackLocale
  3050. const fallbackLocale = vue.computed({
  3051. get: () => _fallbackLocale.value,
  3052. set: val => {
  3053. _fallbackLocale.value = val;
  3054. _context.fallbackLocale = _fallbackLocale.value;
  3055. updateFallbackLocale(_context, _locale.value, val);
  3056. }
  3057. });
  3058. // messages
  3059. const messages = vue.computed(() => _messages.value);
  3060. // datetimeFormats
  3061. const datetimeFormats = vue.computed(() => _datetimeFormats.value);
  3062. // numberFormats
  3063. const numberFormats = vue.computed(() => _numberFormats.value);
  3064. // getPostTranslationHandler
  3065. function getPostTranslationHandler() {
  3066. return isFunction(_postTranslation) ? _postTranslation : null;
  3067. }
  3068. // setPostTranslationHandler
  3069. function setPostTranslationHandler(handler) {
  3070. _postTranslation = handler;
  3071. _context.postTranslation = handler;
  3072. }
  3073. // getMissingHandler
  3074. function getMissingHandler() {
  3075. return _missing;
  3076. }
  3077. // setMissingHandler
  3078. function setMissingHandler(handler) {
  3079. if (handler !== null) {
  3080. _runtimeMissing = defineCoreMissingHandler(handler);
  3081. }
  3082. _missing = handler;
  3083. _context.missing = _runtimeMissing;
  3084. }
  3085. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  3086. ) {
  3087. return type !== 'translate' || !!arg.resolvedMessage === false;
  3088. }
  3089. function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
  3090. trackReactivityValues(); // track reactive dependency
  3091. // NOTE: experimental !!
  3092. let ret;
  3093. {
  3094. try {
  3095. setAdditionalMeta(getMetaInfo());
  3096. ret = fn(_context);
  3097. }
  3098. finally {
  3099. setAdditionalMeta(null);
  3100. }
  3101. }
  3102. if (isNumber(ret) && ret === NOT_REOSLVED) {
  3103. const [key, arg2] = argumentParser();
  3104. if (__root &&
  3105. isString(key) &&
  3106. isResolvedTranslateMessage(warnType, arg2)) {
  3107. if (_fallbackRoot &&
  3108. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  3109. isTranslateMissingWarn(_missingWarn, key))) {
  3110. warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
  3111. key,
  3112. type: warnType
  3113. }));
  3114. }
  3115. // for vue-devtools timeline event
  3116. {
  3117. const { __v_emitter: emitter } = _context;
  3118. if (emitter && _fallbackRoot) {
  3119. emitter.emit("fallback" /* FALBACK */, {
  3120. type: warnType,
  3121. key,
  3122. to: 'global',
  3123. groupId: `${warnType}:${key}`
  3124. });
  3125. }
  3126. }
  3127. }
  3128. return __root && _fallbackRoot
  3129. ? fallbackSuccess(__root)
  3130. : fallbackFail(key);
  3131. }
  3132. else if (successCondition(ret)) {
  3133. return ret;
  3134. }
  3135. else {
  3136. /* istanbul ignore next */
  3137. throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */);
  3138. }
  3139. }
  3140. // t
  3141. function t(...args) {
  3142. return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val));
  3143. }
  3144. // rt
  3145. function rt(...args) {
  3146. const [arg1, arg2, arg3] = args;
  3147. if (arg3 && !isObject(arg3)) {
  3148. throw createI18nError(15 /* INVALID_ARGUMENT */);
  3149. }
  3150. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  3151. }
  3152. // d
  3153. function d(...args) {
  3154. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  3155. }
  3156. // n
  3157. function n(...args) {
  3158. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  3159. }
  3160. // for custom processor
  3161. function normalize(values) {
  3162. return values.map(val => isString(val) ? vue.createVNode(vue.Text, null, val, 0) : val);
  3163. }
  3164. const interpolate = (val) => val;
  3165. const processor = {
  3166. normalize,
  3167. interpolate,
  3168. type: 'vnode'
  3169. };
  3170. // transrateVNode, using for `i18n-t` component
  3171. function transrateVNode(...args) {
  3172. return wrapWithDeps(context => {
  3173. let ret;
  3174. const _context = context;
  3175. try {
  3176. _context.processor = processor;
  3177. ret = translate(_context, ...args);
  3178. }
  3179. finally {
  3180. _context.processor = null;
  3181. }
  3182. return ret;
  3183. }, () => parseTranslateArgs(...args), 'translate',
  3184. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3185. root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => isArray(val));
  3186. }
  3187. // numberParts, using for `i18n-n` component
  3188. function numberParts(...args) {
  3189. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format',
  3190. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3191. root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  3192. }
  3193. // datetimeParts, using for `i18n-d` component
  3194. function datetimeParts(...args) {
  3195. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format',
  3196. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3197. root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  3198. }
  3199. function setPluralRules(rules) {
  3200. _pluralRules = rules;
  3201. _context.pluralRules = _pluralRules;
  3202. }
  3203. // te
  3204. function te(key, locale) {
  3205. const targetLocale = isString(locale) ? locale : _locale.value;
  3206. const message = getLocaleMessage(targetLocale);
  3207. return resolveValue(message, key) !== null;
  3208. }
  3209. function resolveMessages(key) {
  3210. let messages = null;
  3211. const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value);
  3212. for (let i = 0; i < locales.length; i++) {
  3213. const targetLocaleMessages = _messages.value[locales[i]] || {};
  3214. const messageValue = resolveValue(targetLocaleMessages, key);
  3215. if (messageValue != null) {
  3216. messages = messageValue;
  3217. break;
  3218. }
  3219. }
  3220. return messages;
  3221. }
  3222. // tm
  3223. function tm(key) {
  3224. const messages = resolveMessages(key);
  3225. // prettier-ignore
  3226. return messages != null
  3227. ? messages
  3228. : __root
  3229. ? __root.tm(key) || {}
  3230. : {};
  3231. }
  3232. // getLocaleMessage
  3233. function getLocaleMessage(locale) {
  3234. return (_messages.value[locale] || {});
  3235. }
  3236. // setLocaleMessage
  3237. function setLocaleMessage(locale, message) {
  3238. _messages.value[locale] = message;
  3239. _context.messages = _messages.value;
  3240. }
  3241. // mergeLocaleMessage
  3242. function mergeLocaleMessage(locale, message) {
  3243. _messages.value[locale] = _messages.value[locale] || {};
  3244. deepCopy(message, _messages.value[locale]);
  3245. _context.messages = _messages.value;
  3246. }
  3247. // getDateTimeFormat
  3248. function getDateTimeFormat(locale) {
  3249. return _datetimeFormats.value[locale] || {};
  3250. }
  3251. // setDateTimeFormat
  3252. function setDateTimeFormat(locale, format) {
  3253. _datetimeFormats.value[locale] = format;
  3254. _context.datetimeFormats = _datetimeFormats.value;
  3255. clearDateTimeFormat(_context, locale, format);
  3256. }
  3257. // mergeDateTimeFormat
  3258. function mergeDateTimeFormat(locale, format) {
  3259. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  3260. _context.datetimeFormats = _datetimeFormats.value;
  3261. clearDateTimeFormat(_context, locale, format);
  3262. }
  3263. // getNumberFormat
  3264. function getNumberFormat(locale) {
  3265. return _numberFormats.value[locale] || {};
  3266. }
  3267. // setNumberFormat
  3268. function setNumberFormat(locale, format) {
  3269. _numberFormats.value[locale] = format;
  3270. _context.numberFormats = _numberFormats.value;
  3271. clearNumberFormat(_context, locale, format);
  3272. }
  3273. // mergeNumberFormat
  3274. function mergeNumberFormat(locale, format) {
  3275. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  3276. _context.numberFormats = _numberFormats.value;
  3277. clearNumberFormat(_context, locale, format);
  3278. }
  3279. // for debug
  3280. composerID++;
  3281. // watch root locale & fallbackLocale
  3282. if (__root) {
  3283. vue.watch(__root.locale, (val) => {
  3284. if (_inheritLocale) {
  3285. _locale.value = val;
  3286. _context.locale = val;
  3287. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3288. }
  3289. });
  3290. vue.watch(__root.fallbackLocale, (val) => {
  3291. if (_inheritLocale) {
  3292. _fallbackLocale.value = val;
  3293. _context.fallbackLocale = val;
  3294. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3295. }
  3296. });
  3297. }
  3298. // define composition API!
  3299. const composer = {
  3300. id: composerID,
  3301. locale,
  3302. fallbackLocale,
  3303. get inheritLocale() {
  3304. return _inheritLocale;
  3305. },
  3306. set inheritLocale(val) {
  3307. _inheritLocale = val;
  3308. if (val && __root) {
  3309. _locale.value = __root.locale.value;
  3310. _fallbackLocale.value = __root.fallbackLocale.value;
  3311. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3312. }
  3313. },
  3314. get availableLocales() {
  3315. return Object.keys(_messages.value).sort();
  3316. },
  3317. messages,
  3318. datetimeFormats,
  3319. numberFormats,
  3320. get modifiers() {
  3321. return _modifiers;
  3322. },
  3323. get pluralRules() {
  3324. return _pluralRules || {};
  3325. },
  3326. get isGlobal() {
  3327. return _isGlobal;
  3328. },
  3329. get missingWarn() {
  3330. return _missingWarn;
  3331. },
  3332. set missingWarn(val) {
  3333. _missingWarn = val;
  3334. _context.missingWarn = _missingWarn;
  3335. },
  3336. get fallbackWarn() {
  3337. return _fallbackWarn;
  3338. },
  3339. set fallbackWarn(val) {
  3340. _fallbackWarn = val;
  3341. _context.fallbackWarn = _fallbackWarn;
  3342. },
  3343. get fallbackRoot() {
  3344. return _fallbackRoot;
  3345. },
  3346. set fallbackRoot(val) {
  3347. _fallbackRoot = val;
  3348. },
  3349. get fallbackFormat() {
  3350. return _fallbackFormat;
  3351. },
  3352. set fallbackFormat(val) {
  3353. _fallbackFormat = val;
  3354. _context.fallbackFormat = _fallbackFormat;
  3355. },
  3356. get warnHtmlMessage() {
  3357. return _warnHtmlMessage;
  3358. },
  3359. set warnHtmlMessage(val) {
  3360. _warnHtmlMessage = val;
  3361. _context.warnHtmlMessage = val;
  3362. },
  3363. get escapeParameter() {
  3364. return _escapeParameter;
  3365. },
  3366. set escapeParameter(val) {
  3367. _escapeParameter = val;
  3368. _context.escapeParameter = val;
  3369. },
  3370. t,
  3371. rt,
  3372. d,
  3373. n,
  3374. te,
  3375. tm,
  3376. getLocaleMessage,
  3377. setLocaleMessage,
  3378. mergeLocaleMessage,
  3379. getDateTimeFormat,
  3380. setDateTimeFormat,
  3381. mergeDateTimeFormat,
  3382. getNumberFormat,
  3383. setNumberFormat,
  3384. mergeNumberFormat,
  3385. getPostTranslationHandler,
  3386. setPostTranslationHandler,
  3387. getMissingHandler,
  3388. setMissingHandler,
  3389. [TransrateVNodeSymbol]: transrateVNode,
  3390. [NumberPartsSymbol]: numberParts,
  3391. [DatetimePartsSymbol]: datetimeParts,
  3392. [SetPluralRulesSymbol]: setPluralRules,
  3393. [InejctWithOption]: options.__injectWithOption // eslint-disable-line @typescript-eslint/no-explicit-any
  3394. };
  3395. // for vue-devtools timeline event
  3396. {
  3397. composer[EnableEmitter] = (emitter) => {
  3398. _context.__v_emitter = emitter;
  3399. };
  3400. composer[DisableEmitter] = () => {
  3401. _context.__v_emitter = undefined;
  3402. };
  3403. }
  3404. return composer;
  3405. }
  3406. /**
  3407. * Convert to I18n Composer Options from VueI18n Options
  3408. *
  3409. * @internal
  3410. */
  3411. function convertComposerOptions(options) {
  3412. const locale = isString(options.locale) ? options.locale : 'en-US';
  3413. const fallbackLocale = isString(options.fallbackLocale) ||
  3414. isArray(options.fallbackLocale) ||
  3415. isPlainObject(options.fallbackLocale) ||
  3416. options.fallbackLocale === false
  3417. ? options.fallbackLocale
  3418. : locale;
  3419. const missing = isFunction(options.missing) ? options.missing : undefined;
  3420. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  3421. isRegExp(options.silentTranslationWarn)
  3422. ? !options.silentTranslationWarn
  3423. : true;
  3424. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  3425. isRegExp(options.silentFallbackWarn)
  3426. ? !options.silentFallbackWarn
  3427. : true;
  3428. const fallbackRoot = isBoolean(options.fallbackRoot)
  3429. ? options.fallbackRoot
  3430. : true;
  3431. const fallbackFormat = !!options.formatFallbackMessages;
  3432. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  3433. const pluralizationRules = options.pluralizationRules;
  3434. const postTranslation = isFunction(options.postTranslation)
  3435. ? options.postTranslation
  3436. : undefined;
  3437. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  3438. ? options.warnHtmlInMessage !== 'off'
  3439. : true;
  3440. const escapeParameter = !!options.escapeParameterHtml;
  3441. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  3442. if (options.formatter) {
  3443. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  3444. }
  3445. if (options.preserveDirectiveContent) {
  3446. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  3447. }
  3448. let messages = options.messages;
  3449. if (isPlainObject(options.sharedMessages)) {
  3450. const sharedMessages = options.sharedMessages;
  3451. const locales = Object.keys(sharedMessages);
  3452. messages = locales.reduce((messages, locale) => {
  3453. const message = messages[locale] || (messages[locale] = {});
  3454. assign(message, sharedMessages[locale]);
  3455. return messages;
  3456. }, (messages || {}));
  3457. }
  3458. const { __i18n, __root, __injectWithOption } = options;
  3459. const datetimeFormats = options.datetimeFormats;
  3460. const numberFormats = options.numberFormats;
  3461. const flatJson = options.flatJson;
  3462. return {
  3463. locale,
  3464. fallbackLocale,
  3465. messages,
  3466. flatJson,
  3467. datetimeFormats,
  3468. numberFormats,
  3469. missing,
  3470. missingWarn,
  3471. fallbackWarn,
  3472. fallbackRoot,
  3473. fallbackFormat,
  3474. modifiers,
  3475. pluralRules: pluralizationRules,
  3476. postTranslation,
  3477. warnHtmlMessage,
  3478. escapeParameter,
  3479. inheritLocale,
  3480. __i18n,
  3481. __root,
  3482. __injectWithOption
  3483. };
  3484. }
  3485. /**
  3486. * create VueI18n interface factory
  3487. *
  3488. * @internal
  3489. */
  3490. function createVueI18n(options = {}) {
  3491. const composer = createComposer(convertComposerOptions(options));
  3492. // defines VueI18n
  3493. const vueI18n = {
  3494. // id
  3495. id: composer.id,
  3496. // locale
  3497. get locale() {
  3498. return composer.locale.value;
  3499. },
  3500. set locale(val) {
  3501. composer.locale.value = val;
  3502. },
  3503. // fallbackLocale
  3504. get fallbackLocale() {
  3505. return composer.fallbackLocale.value;
  3506. },
  3507. set fallbackLocale(val) {
  3508. composer.fallbackLocale.value = val;
  3509. },
  3510. // messages
  3511. get messages() {
  3512. return composer.messages.value;
  3513. },
  3514. // datetimeFormats
  3515. get datetimeFormats() {
  3516. return composer.datetimeFormats.value;
  3517. },
  3518. // numberFormats
  3519. get numberFormats() {
  3520. return composer.numberFormats.value;
  3521. },
  3522. // availableLocales
  3523. get availableLocales() {
  3524. return composer.availableLocales;
  3525. },
  3526. // formatter
  3527. get formatter() {
  3528. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  3529. // dummy
  3530. return {
  3531. interpolate() {
  3532. return [];
  3533. }
  3534. };
  3535. },
  3536. set formatter(val) {
  3537. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  3538. },
  3539. // missing
  3540. get missing() {
  3541. return composer.getMissingHandler();
  3542. },
  3543. set missing(handler) {
  3544. composer.setMissingHandler(handler);
  3545. },
  3546. // silentTranslationWarn
  3547. get silentTranslationWarn() {
  3548. return isBoolean(composer.missingWarn)
  3549. ? !composer.missingWarn
  3550. : composer.missingWarn;
  3551. },
  3552. set silentTranslationWarn(val) {
  3553. composer.missingWarn = isBoolean(val) ? !val : val;
  3554. },
  3555. // silentFallbackWarn
  3556. get silentFallbackWarn() {
  3557. return isBoolean(composer.fallbackWarn)
  3558. ? !composer.fallbackWarn
  3559. : composer.fallbackWarn;
  3560. },
  3561. set silentFallbackWarn(val) {
  3562. composer.fallbackWarn = isBoolean(val) ? !val : val;
  3563. },
  3564. // modifiers
  3565. get modifiers() {
  3566. return composer.modifiers;
  3567. },
  3568. // formatFallbackMessages
  3569. get formatFallbackMessages() {
  3570. return composer.fallbackFormat;
  3571. },
  3572. set formatFallbackMessages(val) {
  3573. composer.fallbackFormat = val;
  3574. },
  3575. // postTranslation
  3576. get postTranslation() {
  3577. return composer.getPostTranslationHandler();
  3578. },
  3579. set postTranslation(handler) {
  3580. composer.setPostTranslationHandler(handler);
  3581. },
  3582. // sync
  3583. get sync() {
  3584. return composer.inheritLocale;
  3585. },
  3586. set sync(val) {
  3587. composer.inheritLocale = val;
  3588. },
  3589. // warnInHtmlMessage
  3590. get warnHtmlInMessage() {
  3591. return composer.warnHtmlMessage ? 'warn' : 'off';
  3592. },
  3593. set warnHtmlInMessage(val) {
  3594. composer.warnHtmlMessage = val !== 'off';
  3595. },
  3596. // escapeParameterHtml
  3597. get escapeParameterHtml() {
  3598. return composer.escapeParameter;
  3599. },
  3600. set escapeParameterHtml(val) {
  3601. composer.escapeParameter = val;
  3602. },
  3603. // preserveDirectiveContent
  3604. get preserveDirectiveContent() {
  3605. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  3606. return true;
  3607. },
  3608. set preserveDirectiveContent(val) {
  3609. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  3610. },
  3611. // pluralizationRules
  3612. get pluralizationRules() {
  3613. return composer.pluralRules || {};
  3614. },
  3615. // for internal
  3616. __composer: composer,
  3617. // t
  3618. t(...args) {
  3619. const [arg1, arg2, arg3] = args;
  3620. const options = {};
  3621. let list = null;
  3622. let named = null;
  3623. if (!isString(arg1)) {
  3624. throw createI18nError(15 /* INVALID_ARGUMENT */);
  3625. }
  3626. const key = arg1;
  3627. if (isString(arg2)) {
  3628. options.locale = arg2;
  3629. }
  3630. else if (isArray(arg2)) {
  3631. list = arg2;
  3632. }
  3633. else if (isPlainObject(arg2)) {
  3634. named = arg2;
  3635. }
  3636. if (isArray(arg3)) {
  3637. list = arg3;
  3638. }
  3639. else if (isPlainObject(arg3)) {
  3640. named = arg3;
  3641. }
  3642. return composer.t(key, list || named || {}, options);
  3643. },
  3644. rt(...args) {
  3645. return composer.rt(...args);
  3646. },
  3647. // tc
  3648. tc(...args) {
  3649. const [arg1, arg2, arg3] = args;
  3650. const options = { plural: 1 };
  3651. let list = null;
  3652. let named = null;
  3653. if (!isString(arg1)) {
  3654. throw createI18nError(15 /* INVALID_ARGUMENT */);
  3655. }
  3656. const key = arg1;
  3657. if (isString(arg2)) {
  3658. options.locale = arg2;
  3659. }
  3660. else if (isNumber(arg2)) {
  3661. options.plural = arg2;
  3662. }
  3663. else if (isArray(arg2)) {
  3664. list = arg2;
  3665. }
  3666. else if (isPlainObject(arg2)) {
  3667. named = arg2;
  3668. }
  3669. if (isString(arg3)) {
  3670. options.locale = arg3;
  3671. }
  3672. else if (isArray(arg3)) {
  3673. list = arg3;
  3674. }
  3675. else if (isPlainObject(arg3)) {
  3676. named = arg3;
  3677. }
  3678. return composer.t(key, list || named || {}, options);
  3679. },
  3680. // te
  3681. te(key, locale) {
  3682. return composer.te(key, locale);
  3683. },
  3684. // tm
  3685. tm(key) {
  3686. return composer.tm(key);
  3687. },
  3688. // getLocaleMessage
  3689. getLocaleMessage(locale) {
  3690. return composer.getLocaleMessage(locale);
  3691. },
  3692. // setLocaleMessage
  3693. setLocaleMessage(locale, message) {
  3694. composer.setLocaleMessage(locale, message);
  3695. },
  3696. // mergeLocaleMessage
  3697. mergeLocaleMessage(locale, message) {
  3698. composer.mergeLocaleMessage(locale, message);
  3699. },
  3700. // d
  3701. d(...args) {
  3702. return composer.d(...args);
  3703. },
  3704. // getDateTimeFormat
  3705. getDateTimeFormat(locale) {
  3706. return composer.getDateTimeFormat(locale);
  3707. },
  3708. // setDateTimeFormat
  3709. setDateTimeFormat(locale, format) {
  3710. composer.setDateTimeFormat(locale, format);
  3711. },
  3712. // mergeDateTimeFormat
  3713. mergeDateTimeFormat(locale, format) {
  3714. composer.mergeDateTimeFormat(locale, format);
  3715. },
  3716. // n
  3717. n(...args) {
  3718. return composer.n(...args);
  3719. },
  3720. // getNumberFormat
  3721. getNumberFormat(locale) {
  3722. return composer.getNumberFormat(locale);
  3723. },
  3724. // setNumberFormat
  3725. setNumberFormat(locale, format) {
  3726. composer.setNumberFormat(locale, format);
  3727. },
  3728. // mergeNumberFormat
  3729. mergeNumberFormat(locale, format) {
  3730. composer.mergeNumberFormat(locale, format);
  3731. },
  3732. // getChoiceIndex
  3733. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  3734. getChoiceIndex(choice, choicesLength) {
  3735. warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
  3736. return -1;
  3737. },
  3738. // for internal
  3739. __onComponentInstanceCreated(target) {
  3740. const { componentInstanceCreatedListener } = options;
  3741. if (componentInstanceCreatedListener) {
  3742. componentInstanceCreatedListener(target, vueI18n);
  3743. }
  3744. }
  3745. };
  3746. // for vue-devtools timeline event
  3747. {
  3748. vueI18n.__enableEmitter = (emitter) => {
  3749. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3750. const __composer = composer;
  3751. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  3752. };
  3753. vueI18n.__disableEmitter = () => {
  3754. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3755. const __composer = composer;
  3756. __composer[DisableEmitter] && __composer[DisableEmitter]();
  3757. };
  3758. }
  3759. return vueI18n;
  3760. }
  3761. const baseFormatProps = {
  3762. tag: {
  3763. type: [String, Object]
  3764. },
  3765. locale: {
  3766. type: String
  3767. },
  3768. scope: {
  3769. type: String,
  3770. validator: (val) => val === 'parent' || val === 'global',
  3771. default: 'parent'
  3772. },
  3773. i18n: {
  3774. type: Object
  3775. }
  3776. };
  3777. /**
  3778. * Translation Component
  3779. *
  3780. * @remarks
  3781. * See the following items for property about details
  3782. *
  3783. * @VueI18nSee [TranslationProps](component#translationprops)
  3784. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3785. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  3786. *
  3787. * @example
  3788. * ```html
  3789. * <div id="app">
  3790. * <!-- ... -->
  3791. * <i18n path="term" tag="label" for="tos">
  3792. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  3793. * </i18n>
  3794. * <!-- ... -->
  3795. * </div>
  3796. * ```
  3797. * ```js
  3798. * import { createApp } from 'vue'
  3799. * import { createI18n } from 'vue-i18n'
  3800. *
  3801. * const messages = {
  3802. * en: {
  3803. * tos: 'Term of Service',
  3804. * term: 'I accept xxx {0}.'
  3805. * },
  3806. * ja: {
  3807. * tos: '利用規約',
  3808. * term: '私は xxx の{0}に同意します。'
  3809. * }
  3810. * }
  3811. *
  3812. * const i18n = createI18n({
  3813. * locale: 'en',
  3814. * messages
  3815. * })
  3816. *
  3817. * const app = createApp({
  3818. * data: {
  3819. * url: '/term'
  3820. * }
  3821. * }).use(i18n).mount('#app')
  3822. * ```
  3823. *
  3824. * @VueI18nComponent
  3825. */
  3826. const Translation = {
  3827. /* eslint-disable */
  3828. name: 'i18n-t',
  3829. props: assign({
  3830. keypath: {
  3831. type: String,
  3832. required: true
  3833. },
  3834. plural: {
  3835. type: [Number, String],
  3836. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3837. validator: (val) => isNumber(val) || !isNaN(val)
  3838. }
  3839. }, baseFormatProps),
  3840. /* eslint-enable */
  3841. setup(props, context) {
  3842. const { slots, attrs } = context;
  3843. const i18n = props.i18n ||
  3844. useI18n({
  3845. useScope: props.scope,
  3846. __useComponent: true
  3847. });
  3848. const keys = Object.keys(slots).filter(key => key !== '_');
  3849. return () => {
  3850. const options = {};
  3851. if (props.locale) {
  3852. options.locale = props.locale;
  3853. }
  3854. if (props.plural !== undefined) {
  3855. options.plural = isString(props.plural) ? +props.plural : props.plural;
  3856. }
  3857. const arg = getInterpolateArg(context, keys);
  3858. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3859. const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
  3860. const assignedAttrs = assign({}, attrs);
  3861. // prettier-ignore
  3862. return isString(props.tag)
  3863. ? vue.h(props.tag, assignedAttrs, children)
  3864. : isObject(props.tag)
  3865. ? vue.h(props.tag, assignedAttrs, children)
  3866. : vue.h(vue.Fragment, assignedAttrs, children);
  3867. };
  3868. }
  3869. };
  3870. function getInterpolateArg({ slots }, keys) {
  3871. if (keys.length === 1 && keys[0] === 'default') {
  3872. // default slot only
  3873. return slots.default ? slots.default() : [];
  3874. }
  3875. else {
  3876. // named slots
  3877. return keys.reduce((arg, key) => {
  3878. const slot = slots[key];
  3879. if (slot) {
  3880. arg[key] = slot();
  3881. }
  3882. return arg;
  3883. }, {});
  3884. }
  3885. }
  3886. function renderFormatter(props, context, slotKeys, partFormatter) {
  3887. const { slots, attrs } = context;
  3888. return () => {
  3889. const options = { part: true };
  3890. let overrides = {};
  3891. if (props.locale) {
  3892. options.locale = props.locale;
  3893. }
  3894. if (isString(props.format)) {
  3895. options.key = props.format;
  3896. }
  3897. else if (isObject(props.format)) {
  3898. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3899. if (isString(props.format.key)) {
  3900. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3901. options.key = props.format.key;
  3902. }
  3903. // Filter out number format options only
  3904. overrides = Object.keys(props.format).reduce((options, prop) => {
  3905. return slotKeys.includes(prop)
  3906. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  3907. : options;
  3908. }, {});
  3909. }
  3910. const parts = partFormatter(...[props.value, options, overrides]);
  3911. let children = [options.key];
  3912. if (isArray(parts)) {
  3913. children = parts.map((part, index) => {
  3914. const slot = slots[part.type];
  3915. return slot
  3916. ? slot({ [part.type]: part.value, index, parts })
  3917. : [part.value];
  3918. });
  3919. }
  3920. else if (isString(parts)) {
  3921. children = [parts];
  3922. }
  3923. const assignedAttrs = assign({}, attrs);
  3924. // prettier-ignore
  3925. return isString(props.tag)
  3926. ? vue.h(props.tag, assignedAttrs, children)
  3927. : isObject(props.tag)
  3928. ? vue.h(props.tag, assignedAttrs, children)
  3929. : vue.h(vue.Fragment, assignedAttrs, children);
  3930. };
  3931. }
  3932. const NUMBER_FORMAT_KEYS = [
  3933. 'localeMatcher',
  3934. 'style',
  3935. 'unit',
  3936. 'unitDisplay',
  3937. 'currency',
  3938. 'currencyDisplay',
  3939. 'useGrouping',
  3940. 'numberingSystem',
  3941. 'minimumIntegerDigits',
  3942. 'minimumFractionDigits',
  3943. 'maximumFractionDigits',
  3944. 'minimumSignificantDigits',
  3945. 'maximumSignificantDigits',
  3946. 'notation',
  3947. 'formatMatcher'
  3948. ];
  3949. /**
  3950. * Number Format Component
  3951. *
  3952. * @remarks
  3953. * See the following items for property about details
  3954. *
  3955. * @VueI18nSee [FormattableProps](component#formattableprops)
  3956. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3957. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  3958. *
  3959. * @VueI18nDanger
  3960. * 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)
  3961. *
  3962. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  3963. *
  3964. * @VueI18nComponent
  3965. */
  3966. const NumberFormat = {
  3967. /* eslint-disable */
  3968. name: 'i18n-n',
  3969. props: assign({
  3970. value: {
  3971. type: Number,
  3972. required: true
  3973. },
  3974. format: {
  3975. type: [String, Object]
  3976. }
  3977. }, baseFormatProps),
  3978. /* eslint-enable */
  3979. setup(props, context) {
  3980. const i18n = props.i18n ||
  3981. useI18n({ useScope: 'parent', __useComponent: true });
  3982. return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
  3983. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3984. i18n[NumberPartsSymbol](...args));
  3985. }
  3986. };
  3987. const DATETIME_FORMAT_KEYS = [
  3988. 'dateStyle',
  3989. 'timeStyle',
  3990. 'fractionalSecondDigits',
  3991. 'calendar',
  3992. 'dayPeriod',
  3993. 'numberingSystem',
  3994. 'localeMatcher',
  3995. 'timeZone',
  3996. 'hour12',
  3997. 'hourCycle',
  3998. 'formatMatcher',
  3999. 'weekday',
  4000. 'era',
  4001. 'year',
  4002. 'month',
  4003. 'day',
  4004. 'hour',
  4005. 'minute',
  4006. 'second',
  4007. 'timeZoneName'
  4008. ];
  4009. /**
  4010. * Datetime Format Component
  4011. *
  4012. * @remarks
  4013. * See the following items for property about details
  4014. *
  4015. * @VueI18nSee [FormattableProps](component#formattableprops)
  4016. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4017. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  4018. *
  4019. * @VueI18nDanger
  4020. * 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)
  4021. *
  4022. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  4023. *
  4024. * @VueI18nComponent
  4025. */
  4026. const DatetimeFormat = {
  4027. /* eslint-disable */
  4028. name: 'i18n-d',
  4029. props: assign({
  4030. value: {
  4031. type: [Number, Date],
  4032. required: true
  4033. },
  4034. format: {
  4035. type: [String, Object]
  4036. }
  4037. }, baseFormatProps),
  4038. /* eslint-enable */
  4039. setup(props, context) {
  4040. const i18n = props.i18n ||
  4041. useI18n({ useScope: 'parent', __useComponent: true });
  4042. return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
  4043. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4044. i18n[DatetimePartsSymbol](...args));
  4045. }
  4046. };
  4047. function getComposer$2(i18n, instance) {
  4048. const i18nInternal = i18n;
  4049. if (i18n.mode === 'composition') {
  4050. return (i18nInternal.__getInstance(instance) || i18n.global);
  4051. }
  4052. else {
  4053. const vueI18n = i18nInternal.__getInstance(instance);
  4054. return vueI18n != null
  4055. ? vueI18n.__composer
  4056. : i18n.global.__composer;
  4057. }
  4058. }
  4059. function vTDirective(i18n) {
  4060. const bind = (el, { instance, value, modifiers }) => {
  4061. /* istanbul ignore if */
  4062. if (!instance || !instance.$) {
  4063. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  4064. }
  4065. const composer = getComposer$2(i18n, instance.$);
  4066. if (modifiers.preserve) {
  4067. warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
  4068. }
  4069. const parsedValue = parseValue(value);
  4070. el.textContent = composer.t(...makeParams(parsedValue));
  4071. };
  4072. return {
  4073. beforeMount: bind,
  4074. beforeUpdate: bind
  4075. };
  4076. }
  4077. function parseValue(value) {
  4078. if (isString(value)) {
  4079. return { path: value };
  4080. }
  4081. else if (isPlainObject(value)) {
  4082. if (!('path' in value)) {
  4083. throw createI18nError(19 /* REQUIRED_VALUE */, 'path');
  4084. }
  4085. return value;
  4086. }
  4087. else {
  4088. throw createI18nError(20 /* INVALID_VALUE */);
  4089. }
  4090. }
  4091. function makeParams(value) {
  4092. const { path, locale, args, choice, plural } = value;
  4093. const options = {};
  4094. const named = args || {};
  4095. if (isString(locale)) {
  4096. options.locale = locale;
  4097. }
  4098. if (isNumber(choice)) {
  4099. options.plural = choice;
  4100. }
  4101. if (isNumber(plural)) {
  4102. options.plural = plural;
  4103. }
  4104. return [path, named, options];
  4105. }
  4106. function apply(app, i18n, ...options) {
  4107. const pluginOptions = isPlainObject(options[0])
  4108. ? options[0]
  4109. : {};
  4110. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  4111. const globalInstall = isBoolean(pluginOptions.globalInstall)
  4112. ? pluginOptions.globalInstall
  4113. : true;
  4114. if (globalInstall && useI18nComponentName) {
  4115. warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
  4116. name: Translation.name
  4117. }));
  4118. }
  4119. if (globalInstall) {
  4120. // install components
  4121. app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
  4122. app.component(NumberFormat.name, NumberFormat);
  4123. app.component(DatetimeFormat.name, DatetimeFormat);
  4124. }
  4125. // install directive
  4126. app.directive('t', vTDirective(i18n));
  4127. }
  4128. var global$1 = (typeof global !== "undefined" ? global :
  4129. typeof self !== "undefined" ? self :
  4130. typeof window !== "undefined" ? window : {});
  4131. function getDevtoolsGlobalHook() {
  4132. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  4133. }
  4134. function getTarget() {
  4135. // @ts-ignore
  4136. return typeof navigator !== 'undefined'
  4137. ? window
  4138. : typeof global$1 !== 'undefined'
  4139. ? global$1
  4140. : {};
  4141. }
  4142. const HOOK_SETUP = 'devtools-plugin:setup';
  4143. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  4144. const hook = getDevtoolsGlobalHook();
  4145. if (hook) {
  4146. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  4147. }
  4148. else {
  4149. const target = getTarget();
  4150. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  4151. list.push({
  4152. pluginDescriptor,
  4153. setupFn
  4154. });
  4155. }
  4156. }
  4157. const VueDevToolsLabels = {
  4158. ["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
  4159. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
  4160. ["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
  4161. };
  4162. const VueDevToolsPlaceholders = {
  4163. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  4164. };
  4165. const VueDevToolsTimelineColors = {
  4166. ["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
  4167. };
  4168. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  4169. let devtoolsApi;
  4170. async function enableDevTools(app, i18n) {
  4171. return new Promise((resolve, reject) => {
  4172. try {
  4173. setupDevtoolsPlugin({
  4174. id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
  4175. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
  4176. packageName: 'vue-i18n',
  4177. homepage: 'https://vue-i18n.intlify.dev',
  4178. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  4179. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  4180. app
  4181. }, api => {
  4182. devtoolsApi = api;
  4183. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  4184. updateComponentTreeTags(componentInstance, treeNode, i18n);
  4185. });
  4186. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  4187. if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) {
  4188. if (i18n.mode === 'legacy') {
  4189. // ignore global scope on legacy mode
  4190. if (componentInstance.vnode.el.__VUE_I18N__ !==
  4191. i18n.global.__composer) {
  4192. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  4193. }
  4194. }
  4195. else {
  4196. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  4197. }
  4198. }
  4199. });
  4200. api.addInspector({
  4201. id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
  4202. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
  4203. icon: 'language',
  4204. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
  4205. });
  4206. api.on.getInspectorTree(payload => {
  4207. if (payload.app === app &&
  4208. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  4209. registerScope(payload, i18n);
  4210. }
  4211. });
  4212. api.on.getInspectorState(payload => {
  4213. if (payload.app === app &&
  4214. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  4215. inspectScope(payload, i18n);
  4216. }
  4217. });
  4218. api.on.editInspectorState(payload => {
  4219. if (payload.app === app &&
  4220. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  4221. editScope(payload, i18n);
  4222. }
  4223. });
  4224. api.addTimelineLayer({
  4225. id: "vue-i18n-timeline" /* TIMELINE */,
  4226. label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
  4227. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
  4228. });
  4229. resolve(true);
  4230. });
  4231. }
  4232. catch (e) {
  4233. console.error(e);
  4234. reject(false);
  4235. }
  4236. });
  4237. }
  4238. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  4239. treeNode, i18n) {
  4240. // prettier-ignore
  4241. const global = i18n.mode === 'composition'
  4242. ? i18n.global
  4243. : i18n.global.__composer;
  4244. if (instance && instance.vnode.el.__VUE_I18N__) {
  4245. // add custom tags local scope only
  4246. if (instance.vnode.el.__VUE_I18N__ !== global) {
  4247. const label = instance.type.name || instance.type.displayName || instance.type.__file;
  4248. const tag = {
  4249. label: `i18n (${label} Scope)`,
  4250. textColor: 0x000000,
  4251. backgroundColor: 0xffcd19
  4252. };
  4253. treeNode.tags.push(tag);
  4254. }
  4255. }
  4256. }
  4257. function inspectComposer(instanceData, composer) {
  4258. const type = VUE_I18N_COMPONENT_TYPES;
  4259. instanceData.state.push({
  4260. type,
  4261. key: 'locale',
  4262. editable: true,
  4263. value: composer.locale.value
  4264. });
  4265. instanceData.state.push({
  4266. type,
  4267. key: 'availableLocales',
  4268. editable: false,
  4269. value: composer.availableLocales
  4270. });
  4271. instanceData.state.push({
  4272. type,
  4273. key: 'fallbackLocale',
  4274. editable: true,
  4275. value: composer.fallbackLocale.value
  4276. });
  4277. instanceData.state.push({
  4278. type,
  4279. key: 'inheritLocale',
  4280. editable: true,
  4281. value: composer.inheritLocale
  4282. });
  4283. instanceData.state.push({
  4284. type,
  4285. key: 'messages',
  4286. editable: false,
  4287. value: getLocaleMessageValue(composer.messages.value)
  4288. });
  4289. instanceData.state.push({
  4290. type,
  4291. key: 'datetimeFormats',
  4292. editable: false,
  4293. value: composer.datetimeFormats.value
  4294. });
  4295. instanceData.state.push({
  4296. type,
  4297. key: 'numberFormats',
  4298. editable: false,
  4299. value: composer.numberFormats.value
  4300. });
  4301. }
  4302. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4303. function getLocaleMessageValue(messages) {
  4304. const value = {};
  4305. Object.keys(messages).forEach((key) => {
  4306. const v = messages[key];
  4307. if (isFunction(v) && 'source' in v) {
  4308. value[key] = getMessageFunctionDetails(v);
  4309. }
  4310. else if (isObject(v)) {
  4311. value[key] = getLocaleMessageValue(v);
  4312. }
  4313. else {
  4314. value[key] = v;
  4315. }
  4316. });
  4317. return value;
  4318. }
  4319. const ESC = {
  4320. '<': '&lt;',
  4321. '>': '&gt;',
  4322. '"': '&quot;',
  4323. '&': '&amp;'
  4324. };
  4325. function escape(s) {
  4326. return s.replace(/[<>"&]/g, escapeChar);
  4327. }
  4328. function escapeChar(a) {
  4329. return ESC[a] || a;
  4330. }
  4331. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4332. function getMessageFunctionDetails(func) {
  4333. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  4334. return {
  4335. _custom: {
  4336. type: 'function',
  4337. display: `<span>ƒ</span> ${argString}`
  4338. }
  4339. };
  4340. }
  4341. function registerScope(payload, i18n) {
  4342. payload.rootNodes.push({
  4343. id: 'global',
  4344. label: 'Global Scope'
  4345. });
  4346. // prettier-ignore
  4347. const global = i18n.mode === 'composition'
  4348. ? i18n.global
  4349. : i18n.global.__composer;
  4350. for (const [keyInstance, instance] of i18n.__instances) {
  4351. // prettier-ignore
  4352. const composer = i18n.mode === 'composition'
  4353. ? instance
  4354. : instance.__composer;
  4355. if (global === composer) {
  4356. continue;
  4357. }
  4358. const label = keyInstance.type.name ||
  4359. keyInstance.type.displayName ||
  4360. keyInstance.type.__file;
  4361. payload.rootNodes.push({
  4362. id: composer.id.toString(),
  4363. label: `${label} Scope`
  4364. });
  4365. }
  4366. }
  4367. function getComposer$1(nodeId, i18n) {
  4368. if (nodeId === 'global') {
  4369. return i18n.mode === 'composition'
  4370. ? i18n.global
  4371. : i18n.global.__composer;
  4372. }
  4373. else {
  4374. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  4375. if (instance) {
  4376. return i18n.mode === 'composition'
  4377. ? instance
  4378. : instance.__composer;
  4379. }
  4380. else {
  4381. return null;
  4382. }
  4383. }
  4384. }
  4385. function inspectScope(payload, i18n) {
  4386. const composer = getComposer$1(payload.nodeId, i18n);
  4387. if (composer) {
  4388. payload.state = makeScopeInspectState(composer);
  4389. }
  4390. }
  4391. function makeScopeInspectState(composer) {
  4392. const state = {};
  4393. const localeType = 'Locale related info';
  4394. const localeStates = [
  4395. {
  4396. type: localeType,
  4397. key: 'locale',
  4398. editable: true,
  4399. value: composer.locale.value
  4400. },
  4401. {
  4402. type: localeType,
  4403. key: 'fallbackLocale',
  4404. editable: true,
  4405. value: composer.fallbackLocale.value
  4406. },
  4407. {
  4408. type: localeType,
  4409. key: 'availableLocales',
  4410. editable: false,
  4411. value: composer.availableLocales
  4412. },
  4413. {
  4414. type: localeType,
  4415. key: 'inheritLocale',
  4416. editable: true,
  4417. value: composer.inheritLocale
  4418. }
  4419. ];
  4420. state[localeType] = localeStates;
  4421. const localeMessagesType = 'Locale messages info';
  4422. const localeMessagesStates = [
  4423. {
  4424. type: localeMessagesType,
  4425. key: 'messages',
  4426. editable: false,
  4427. value: getLocaleMessageValue(composer.messages.value)
  4428. }
  4429. ];
  4430. state[localeMessagesType] = localeMessagesStates;
  4431. const datetimeFormatsType = 'Datetime formats info';
  4432. const datetimeFormatsStates = [
  4433. {
  4434. type: datetimeFormatsType,
  4435. key: 'datetimeFormats',
  4436. editable: false,
  4437. value: composer.datetimeFormats.value
  4438. }
  4439. ];
  4440. state[datetimeFormatsType] = datetimeFormatsStates;
  4441. const numberFormatsType = 'Datetime formats info';
  4442. const numberFormatsStates = [
  4443. {
  4444. type: numberFormatsType,
  4445. key: 'numberFormats',
  4446. editable: false,
  4447. value: composer.numberFormats.value
  4448. }
  4449. ];
  4450. state[numberFormatsType] = numberFormatsStates;
  4451. return state;
  4452. }
  4453. function addTimelineEvent(event, payload) {
  4454. if (devtoolsApi) {
  4455. let groupId;
  4456. if (payload && 'groupId' in payload) {
  4457. groupId = payload.groupId;
  4458. delete payload.groupId;
  4459. }
  4460. devtoolsApi.addTimelineEvent({
  4461. layerId: "vue-i18n-timeline" /* TIMELINE */,
  4462. event: {
  4463. title: event,
  4464. groupId,
  4465. time: Date.now(),
  4466. meta: {},
  4467. data: payload || {},
  4468. logType: event === "compile-error" /* COMPILE_ERROR */
  4469. ? 'error'
  4470. : event === "fallback" /* FALBACK */ ||
  4471. event === "missing" /* MISSING */
  4472. ? 'warning'
  4473. : 'default'
  4474. }
  4475. });
  4476. }
  4477. }
  4478. function editScope(payload, i18n) {
  4479. const composer = getComposer$1(payload.nodeId, i18n);
  4480. if (composer) {
  4481. const [field] = payload.path;
  4482. if (field === 'locale' && isString(payload.state.value)) {
  4483. composer.locale.value = payload.state.value;
  4484. }
  4485. else if (field === 'fallbackLocale' &&
  4486. (isString(payload.state.value) ||
  4487. isArray(payload.state.value) ||
  4488. isObject(payload.state.value))) {
  4489. composer.fallbackLocale.value = payload.state.value;
  4490. }
  4491. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  4492. composer.inheritLocale = payload.state.value;
  4493. }
  4494. }
  4495. }
  4496. // supports compatibility for legacy vue-i18n APIs
  4497. function defineMixin(vuei18n, composer, i18n) {
  4498. return {
  4499. beforeCreate() {
  4500. const instance = vue.getCurrentInstance();
  4501. /* istanbul ignore if */
  4502. if (!instance) {
  4503. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  4504. }
  4505. const options = this.$options;
  4506. if (options.i18n) {
  4507. const optionsI18n = options.i18n;
  4508. if (options.__i18n) {
  4509. optionsI18n.__i18n = options.__i18n;
  4510. }
  4511. optionsI18n.__root = composer;
  4512. if (this === this.$root) {
  4513. this.$i18n = mergeToRoot(vuei18n, optionsI18n);
  4514. }
  4515. else {
  4516. optionsI18n.__injectWithOption = true;
  4517. this.$i18n = createVueI18n(optionsI18n);
  4518. }
  4519. }
  4520. else if (options.__i18n) {
  4521. if (this === this.$root) {
  4522. this.$i18n = mergeToRoot(vuei18n, options);
  4523. }
  4524. else {
  4525. this.$i18n = createVueI18n({
  4526. __i18n: options.__i18n,
  4527. __injectWithOption: true,
  4528. __root: composer
  4529. });
  4530. }
  4531. }
  4532. else {
  4533. // set global
  4534. this.$i18n = vuei18n;
  4535. }
  4536. vuei18n.__onComponentInstanceCreated(this.$i18n);
  4537. i18n.__setInstance(instance, this.$i18n);
  4538. // defines vue-i18n legacy APIs
  4539. this.$t = (...args) => this.$i18n.t(...args);
  4540. this.$rt = (...args) => this.$i18n.rt(...args);
  4541. this.$tc = (...args) => this.$i18n.tc(...args);
  4542. this.$te = (key, locale) => this.$i18n.te(key, locale);
  4543. this.$d = (...args) => this.$i18n.d(...args);
  4544. this.$n = (...args) => this.$i18n.n(...args);
  4545. this.$tm = (key) => this.$i18n.tm(key);
  4546. },
  4547. mounted() {
  4548. /* istanbul ignore if */
  4549. {
  4550. this.$el.__VUE_I18N__ = this.$i18n.__composer;
  4551. const emitter = (this.__v_emitter = createEmitter());
  4552. const _vueI18n = this.$i18n;
  4553. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4554. emitter.on('*', addTimelineEvent);
  4555. }
  4556. },
  4557. beforeUnmount() {
  4558. const instance = vue.getCurrentInstance();
  4559. /* istanbul ignore if */
  4560. if (!instance) {
  4561. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  4562. }
  4563. /* istanbul ignore if */
  4564. {
  4565. if (this.__v_emitter) {
  4566. this.__v_emitter.off('*', addTimelineEvent);
  4567. delete this.__v_emitter;
  4568. }
  4569. const _vueI18n = this.$i18n;
  4570. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  4571. delete this.$el.__VUE_I18N__;
  4572. }
  4573. delete this.$t;
  4574. delete this.$rt;
  4575. delete this.$tc;
  4576. delete this.$te;
  4577. delete this.$d;
  4578. delete this.$n;
  4579. delete this.$tm;
  4580. i18n.__deleteInstance(instance);
  4581. delete this.$i18n;
  4582. }
  4583. };
  4584. }
  4585. function mergeToRoot(root, options) {
  4586. root.locale = options.locale || root.locale;
  4587. root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
  4588. root.missing = options.missing || root.missing;
  4589. root.silentTranslationWarn =
  4590. options.silentTranslationWarn || root.silentFallbackWarn;
  4591. root.silentFallbackWarn =
  4592. options.silentFallbackWarn || root.silentFallbackWarn;
  4593. root.formatFallbackMessages =
  4594. options.formatFallbackMessages || root.formatFallbackMessages;
  4595. root.postTranslation = options.postTranslation || root.postTranslation;
  4596. root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
  4597. root.escapeParameterHtml =
  4598. options.escapeParameterHtml || root.escapeParameterHtml;
  4599. root.sync = options.sync || root.sync;
  4600. root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
  4601. const messages = getLocaleMessages(root.locale, {
  4602. messages: options.messages,
  4603. __i18n: options.__i18n
  4604. });
  4605. Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
  4606. if (options.datetimeFormats) {
  4607. Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  4608. }
  4609. if (options.numberFormats) {
  4610. Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
  4611. }
  4612. return root;
  4613. }
  4614. /**
  4615. * Vue I18n factory
  4616. *
  4617. * @param options - An options, see the {@link I18nOptions}
  4618. *
  4619. * @returns {@link I18n} instance
  4620. *
  4621. * @remarks
  4622. * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
  4623. *
  4624. * If you use composition API mode, you need to specify {@link ComposerOptions}.
  4625. *
  4626. * @VueI18nSee [Getting Started](../guide/)
  4627. * @VueI18nSee [Composition API](../guide/advanced/composition)
  4628. *
  4629. * @example
  4630. * case: for Legacy API
  4631. * ```js
  4632. * import { createApp } from 'vue'
  4633. * import { createI18n } from 'vue-i18n'
  4634. *
  4635. * // call with I18n option
  4636. * const i18n = createI18n({
  4637. * locale: 'ja',
  4638. * messages: {
  4639. * en: { ... },
  4640. * ja: { ... }
  4641. * }
  4642. * })
  4643. *
  4644. * const App = {
  4645. * // ...
  4646. * }
  4647. *
  4648. * const app = createApp(App)
  4649. *
  4650. * // install!
  4651. * app.use(i18n)
  4652. * app.mount('#app')
  4653. * ```
  4654. *
  4655. * @example
  4656. * case: for composition API
  4657. * ```js
  4658. * import { createApp } from 'vue'
  4659. * import { createI18n, useI18n } from 'vue-i18n'
  4660. *
  4661. * // call with I18n option
  4662. * const i18n = createI18n({
  4663. * legacy: false, // you must specify 'legacy: false' option
  4664. * locale: 'ja',
  4665. * messages: {
  4666. * en: { ... },
  4667. * ja: { ... }
  4668. * }
  4669. * })
  4670. *
  4671. * const App = {
  4672. * setup() {
  4673. * // ...
  4674. * const { t } = useI18n({ ... })
  4675. * return { ... , t }
  4676. * }
  4677. * }
  4678. *
  4679. * const app = createApp(App)
  4680. *
  4681. * // install!
  4682. * app.use(i18n)
  4683. * app.mount('#app')
  4684. * ```
  4685. *
  4686. * @VueI18nGeneral
  4687. */
  4688. function createI18n(options = {}) {
  4689. // prettier-ignore
  4690. const __legacyMode = isBoolean(options.legacy)
  4691. ? options.legacy
  4692. : true;
  4693. const __globalInjection = !!options.globalInjection;
  4694. const __instances = new Map();
  4695. // prettier-ignore
  4696. const __global = __legacyMode
  4697. ? createVueI18n(options)
  4698. : createComposer(options);
  4699. const symbol = makeSymbol('vue-i18n' );
  4700. const i18n = {
  4701. // mode
  4702. get mode() {
  4703. // prettier-ignore
  4704. return __legacyMode
  4705. ? 'legacy'
  4706. : 'composition'
  4707. ;
  4708. },
  4709. // install plugin
  4710. async install(app, ...options) {
  4711. {
  4712. app.__VUE_I18N__ = i18n;
  4713. }
  4714. // setup global provider
  4715. app.__VUE_I18N_SYMBOL__ = symbol;
  4716. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  4717. // global method and properties injection for Composition API
  4718. if (!__legacyMode && __globalInjection) {
  4719. injectGlobalFields(app, i18n.global);
  4720. }
  4721. // install built-in components and directive
  4722. {
  4723. apply(app, i18n, ...options);
  4724. }
  4725. // setup mixin for Legacy API
  4726. if (__legacyMode) {
  4727. app.mixin(defineMixin(__global, __global.__composer, i18n));
  4728. }
  4729. // setup vue-devtools plugin
  4730. {
  4731. const ret = await enableDevTools(app, i18n);
  4732. if (!ret) {
  4733. throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
  4734. }
  4735. const emitter = createEmitter();
  4736. if (__legacyMode) {
  4737. const _vueI18n = __global;
  4738. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4739. }
  4740. else {
  4741. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4742. const _composer = __global;
  4743. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4744. }
  4745. emitter.on('*', addTimelineEvent);
  4746. }
  4747. },
  4748. // global accessor
  4749. get global() {
  4750. return __global;
  4751. },
  4752. // @internal
  4753. __instances,
  4754. // @internal
  4755. __getInstance(component) {
  4756. return __instances.get(component) || null;
  4757. },
  4758. // @internal
  4759. __setInstance(component, instance) {
  4760. __instances.set(component, instance);
  4761. },
  4762. // @internal
  4763. __deleteInstance(component) {
  4764. __instances.delete(component);
  4765. }
  4766. };
  4767. return i18n;
  4768. }
  4769. /**
  4770. * Use Composition API for Vue I18n
  4771. *
  4772. * @param options - An options, see {@link UseI18nOptions}
  4773. *
  4774. * @returns {@link Composer} instance
  4775. *
  4776. * @remarks
  4777. * This function is mainly used by `setup`.
  4778. *
  4779. * If options are specified, Composer instance is created for each component and you can be localized on the component.
  4780. *
  4781. * If options are not specified, you can be localized using the global Composer.
  4782. *
  4783. * @example
  4784. * case: Component resource base localization
  4785. * ```html
  4786. * <template>
  4787. * <form>
  4788. * <label>{{ t('language') }}</label>
  4789. * <select v-model="locale">
  4790. * <option value="en">en</option>
  4791. * <option value="ja">ja</option>
  4792. * </select>
  4793. * </form>
  4794. * <p>message: {{ t('hello') }}</p>
  4795. * </template>
  4796. *
  4797. * <script>
  4798. * import { useI18n } from 'vue-i18n'
  4799. *
  4800. * export default {
  4801. * setup() {
  4802. * const { t, locale } = useI18n({
  4803. * locale: 'ja',
  4804. * messages: {
  4805. * en: { ... },
  4806. * ja: { ... }
  4807. * }
  4808. * })
  4809. * // Something to do ...
  4810. *
  4811. * return { ..., t, locale }
  4812. * }
  4813. * }
  4814. * </script>
  4815. * ```
  4816. *
  4817. * @VueI18nComposition
  4818. */
  4819. function useI18n(options = {}) {
  4820. const instance = vue.getCurrentInstance();
  4821. if (instance == null) {
  4822. throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */);
  4823. }
  4824. if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
  4825. throw createI18nError(17 /* NOT_INSLALLED */);
  4826. }
  4827. const i18n = vue.inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
  4828. /* istanbul ignore if */
  4829. if (!i18n) {
  4830. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  4831. }
  4832. // prettier-ignore
  4833. const global = i18n.mode === 'composition'
  4834. ? i18n.global
  4835. : i18n.global.__composer;
  4836. // prettier-ignore
  4837. const scope = isEmptyObject(options)
  4838. ? ('__i18n' in instance.type)
  4839. ? 'local'
  4840. : 'global'
  4841. : !options.useScope
  4842. ? 'local'
  4843. : options.useScope;
  4844. if (scope === 'global') {
  4845. let messages = isObject(options.messages) ? options.messages : {};
  4846. if ('__i18nGlobal' in instance.type) {
  4847. messages = getLocaleMessages(global.locale.value, {
  4848. messages,
  4849. __i18n: instance.type.__i18nGlobal
  4850. });
  4851. }
  4852. // merge locale messages
  4853. const locales = Object.keys(messages);
  4854. if (locales.length) {
  4855. locales.forEach(locale => {
  4856. global.mergeLocaleMessage(locale, messages[locale]);
  4857. });
  4858. }
  4859. // merge datetime formats
  4860. if (isObject(options.datetimeFormats)) {
  4861. const locales = Object.keys(options.datetimeFormats);
  4862. if (locales.length) {
  4863. locales.forEach(locale => {
  4864. global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  4865. });
  4866. }
  4867. }
  4868. // merge number formats
  4869. if (isObject(options.numberFormats)) {
  4870. const locales = Object.keys(options.numberFormats);
  4871. if (locales.length) {
  4872. locales.forEach(locale => {
  4873. global.mergeNumberFormat(locale, options.numberFormats[locale]);
  4874. });
  4875. }
  4876. }
  4877. return global;
  4878. }
  4879. if (scope === 'parent') {
  4880. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4881. let composer = getComposer(i18n, instance, options.__useComponent);
  4882. if (composer == null) {
  4883. {
  4884. warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
  4885. }
  4886. composer = global;
  4887. }
  4888. return composer;
  4889. }
  4890. // scope 'local' case
  4891. if (i18n.mode === 'legacy') {
  4892. throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
  4893. }
  4894. const i18nInternal = i18n;
  4895. let composer = i18nInternal.__getInstance(instance);
  4896. if (composer == null) {
  4897. const type = instance.type;
  4898. const composerOptions = assign({}, options);
  4899. if (type.__i18n) {
  4900. composerOptions.__i18n = type.__i18n;
  4901. }
  4902. if (global) {
  4903. composerOptions.__root = global;
  4904. }
  4905. composer = createComposer(composerOptions);
  4906. setupLifeCycle(i18nInternal, instance, composer);
  4907. i18nInternal.__setInstance(instance, composer);
  4908. }
  4909. return composer;
  4910. }
  4911. function getComposer(i18n, target, useComponent = false) {
  4912. let composer = null;
  4913. const root = target.root;
  4914. let current = target.parent;
  4915. while (current != null) {
  4916. const i18nInternal = i18n;
  4917. if (i18n.mode === 'composition') {
  4918. composer = i18nInternal.__getInstance(current);
  4919. }
  4920. else {
  4921. const vueI18n = i18nInternal.__getInstance(current);
  4922. if (vueI18n != null) {
  4923. composer = vueI18n
  4924. .__composer;
  4925. }
  4926. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4927. if (useComponent && composer && !composer[InejctWithOption]) {
  4928. composer = null;
  4929. }
  4930. }
  4931. if (composer != null) {
  4932. break;
  4933. }
  4934. if (root === current) {
  4935. break;
  4936. }
  4937. current = current.parent;
  4938. }
  4939. return composer;
  4940. }
  4941. function setupLifeCycle(i18n, target, composer) {
  4942. let emitter = null;
  4943. vue.onMounted(() => {
  4944. // inject composer instance to DOM for intlify-devtools
  4945. if (target.vnode.el) {
  4946. target.vnode.el.__VUE_I18N__ = composer;
  4947. emitter = createEmitter();
  4948. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4949. const _composer = composer;
  4950. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4951. emitter.on('*', addTimelineEvent);
  4952. }
  4953. }, target);
  4954. vue.onUnmounted(() => {
  4955. // remove composer instance from DOM for intlify-devtools
  4956. if (target.vnode.el &&
  4957. target.vnode.el.__VUE_I18N__) {
  4958. emitter && emitter.off('*', addTimelineEvent);
  4959. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4960. const _composer = composer;
  4961. _composer[DisableEmitter] && _composer[DisableEmitter]();
  4962. delete target.vnode.el.__VUE_I18N__;
  4963. }
  4964. i18n.__deleteInstance(target);
  4965. }, target);
  4966. }
  4967. const globalExportProps = [
  4968. 'locale',
  4969. 'fallbackLocale',
  4970. 'availableLocales'
  4971. ];
  4972. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm'];
  4973. function injectGlobalFields(app, composer) {
  4974. const i18n = Object.create(null);
  4975. globalExportProps.forEach(prop => {
  4976. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  4977. if (!desc) {
  4978. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  4979. }
  4980. const wrap = vue.isRef(desc.value) // check computed props
  4981. ? {
  4982. get() {
  4983. return desc.value.value;
  4984. },
  4985. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4986. set(val) {
  4987. desc.value.value = val;
  4988. }
  4989. }
  4990. : {
  4991. get() {
  4992. return desc.get && desc.get();
  4993. }
  4994. };
  4995. Object.defineProperty(i18n, prop, wrap);
  4996. });
  4997. app.config.globalProperties.$i18n = i18n;
  4998. globalExportMethods.forEach(method => {
  4999. const desc = Object.getOwnPropertyDescriptor(composer, method);
  5000. if (!desc || !desc.value) {
  5001. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  5002. }
  5003. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  5004. });
  5005. }
  5006. // register message compiler at vue-i18n
  5007. registerMessageCompiler(compileToFunction);
  5008. // NOTE: experimental !!
  5009. {
  5010. const target = getGlobalThis();
  5011. target.__INTLIFY__ = true;
  5012. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  5013. }
  5014. {
  5015. initDev();
  5016. }
  5017. exports.DatetimeFormat = DatetimeFormat;
  5018. exports.NumberFormat = NumberFormat;
  5019. exports.Translation = Translation;
  5020. exports.VERSION = VERSION;
  5021. exports.createI18n = createI18n;
  5022. exports.useI18n = useI18n;
  5023. exports.vTDirective = vTDirective;
  5024. Object.defineProperty(exports, '__esModule', { value: true });
  5025. return exports;
  5026. }({}, Vue));