vue-i18n.esm-browser.js 167 KB

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